diff --git a/.gitignore b/.gitignore index ae6b742951..656f1cda53 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,16 @@ .DS_Store _Resharper.DefinitelyTyped +bin +obj +Properties + +# VIM backup files +*~ + +# test folder +!_infrastructure/tests/* +!_infrastructure/tests/*.js +!_infrastructure/tests/*/*.js +!_infrastructure/tests/*/*/*.js +!_infrastructure/tests/*/*/*/*.js diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000000..b30372ed1a --- /dev/null +++ b/.travis.yml @@ -0,0 +1,6 @@ +language: node_js +node_js: + - 0.8 + +notifications: + email: false \ No newline at end of file diff --git a/AzureMobileServicesClient/AzureMobileServicesClient-tests.ts b/AzureMobileServicesClient/AzureMobileServicesClient-tests.ts new file mode 100644 index 0000000000..b557a2baf2 --- /dev/null +++ b/AzureMobileServicesClient/AzureMobileServicesClient-tests.ts @@ -0,0 +1,73 @@ +/// + + +//create base client istance and read properties +var client = new WindowsAzure.MobileServiceClient("your-azure-mobile-application-URL", "your-azure-application-KEY"); +console.log("Azure application URL: " + client.applicationUrl); +console.log("Azure application KEY: " + client.applicationKey.replace(/./gi,'*')); //KEEP IT SECRET!!! + + +//user authentication, to make it work follow this guide: http://www.windowsazure.com/en-us/develop/mobile/tutorials/get-started-with-users-html/?fb=it-it#add-authentication +if (client.currentUser === null) { + client.login("facebook") + .then((u: Microsoft.WindowsAzure.User) => alert(u.level)) + .done(() => alert("USER: " + client.currentUser.userId), + (e) => alert("ERROR: " + e)); +} else { client.logout(); } + + +//define an interface that map to server side Table data +interface TodoItem { id?: number; text?: string; complete?: bool; } +var data: TodoItem[]; +var tableTodoItems = client.getTable('todoitem'); + + +//read all data from server using Promise .then() and error handling in .done() +tableTodoItems.read() +.then((retList: TodoItem[]) => { + data = retList; return retList.length +}) +.done((n: number) => + alert(n + " items downloaded"), (e) => alert("ERROR: " + e)); + + +//define simple handler used in callback calls for insert/update and delete +function handlerInsUpd(e, i) => { if (!e) data.push( i); }; +function handlerDelErr(e) => { if (e) alert("ERROR: " + e); } + + +//insert one data passing info in POST + custom data in QueryString + simple callback handler +tableTodoItems.insert({ text: 'hello world!', complete: false }, {timestamp: new Date()} , handlerInsUpd); + + +//update last item changing complete and calling simple handler when done +var todo = data.pop(); +todo.complete = !todo.complete; +tableTodoItems.update(todo, null, handlerInsUpd) + + +//delete first item +tableTodoItems.del({ id: data[0].id },null).done(null, handlerDelErr) + + +//testing some simple Query fluent +var query = tableTodoItems.select('text', 'id') + .where({ complete: false }) + .orderBy('text') +query.read().done(printOut); //Execute query remotly and return data filtered + + +//testing more complicated Query in composition with previous using function Predicate and Projection +var minlength = 15; //parameter value for filter Predicate +query.where(function (len: number) { return this.text != null && this.text.length > len }, minlength) + .orderByDescending('id').skip(2).take(3) //some other ordering and paging filters + .select(function () { return { abc: this.text + '|' + this.id }; }) //Projection + .read().done(printOut); //return 3 object {abd: 'ttttttttttttttt|ID'} + + +//function that printout the query result in JSON +function printOut(ret:any[]) { + if (!ret) console.log("NO DATA FOUND!") + else for (var i = 0; i < ret.length; i++) { + console.log(JSON.stringify(ret[i])); } +} diff --git a/AzureMobileServicesClient/AzureMobileServicesClient.d.ts b/AzureMobileServicesClient/AzureMobileServicesClient.d.ts new file mode 100644 index 0000000000..1dcf9e5a67 --- /dev/null +++ b/AzureMobileServicesClient/AzureMobileServicesClient.d.ts @@ -0,0 +1,94 @@ +// Type definitions for Microsoft.Windows.Azure.MobileService.Web-1.0.0 +// Project: https://.azure-mobile.net/client/MobileServices.Web-1.0.0.min.js +// Definitions by: Morosinotto Daniele +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +module Microsoft.WindowsAzure { + + // MobileServiceClient object based on Microsoft Azure documentation: http://msdn.microsoft.com/en-us/library/windowsazure/jj554219.aspx + interface MobileServiceClient { + new (applicationUrl: string, applicationKey: string): MobileServiceClient; + applicationUrl: string; + applicationKey: string; + currentUser: User; + //for provider:string use one of ProviderEnum: 'microsoftaccount', 'facebook', 'twitter', 'google' + login(provider: string, token: string, callback: (error: any, user: User) => void ): void; + login(provider: string, token: string): asyncPromise; + login(provider: string, callback: (error: any, user: User) => void ): void; + login(provider: string): asyncPromise; + logout(): void; + getTable(tableName: string): MobileServiceTable; + withFilter(serviceFilter: (request: any, next: (request: any, callback: (error:any, response: any) => void ) => void, callback: (error: any, response: any) => void ) => void ) : MobileServiceClient; + } + + // User object based on Microsoft Azure documentation: http://msdn.microsoft.com/en-us/library/windowsazure/jj554220.aspx + interface User { + getIdentities(): any;// { [providerName: string]: { userId: string, accessToken: string, accessTokenSecret?: string }; }; + accessTokens: any; // { [providerName: string]: string; } + level: string; //for level:string use one of LevelEnum: 'admin','anonymous','authenticated' + userId: string; + } + + + // Interface to Platform.async(func) => Platform.Promise based on code MobileServices.Web-1.0.0.js + interface asyncPromise { + then(onSuccess: (result: any) => any, onError?: (error: any) => any): asyncPromise; + done(onSuccess?: (result: any) => void , onError?: (error: any) => void ): void; + } + + // MobileServiceTable object based on Microsoft Azure documentation: http://msdn.microsoft.com/en-us/library/windowsazure/jj554239.aspx + interface MobileServiceTable extends IQuery { + new (tableName: string, client: MobileServiceClient): MobileServiceTable; + getTableName(): string; + getMobileServiceClient(): MobileServiceClient; + + insert(istance: any, paramsQS: Object, callback: (error: any, retInserted: any) => any): void; + insert(istance: any, paramsQS: Object): asyncPromise; + insert(istance: any): asyncPromise; + + update(istance: any, paramsQS: Object, callback: (error: any, retUpdated: any) => any): void; + update(istance: any, paramsQS: Object): asyncPromise; + update(istance: any): asyncPromise; + + lookup(id: number, paramsQS: Object, callback: (error: any, retValue: any) => any): void; + lookup(id: number, paramsQS: Object): asyncPromise; + lookup(id: number): asyncPromise; + + del(istance: any, paramsQS: Object, callback: (error?: any) => void ): void; + del(istance: any, paramsQS: Object): asyncPromise; + del(istance: any): asyncPromise; + + + read(query: IQuery, paramsQS: Object, callback: (error: any, retValues: any) => any): void; + read(query: IQuery, paramsQS: Object): asyncPromise; + read(query: IQuery): asyncPromise; + read(): asyncPromise; + } + + + // Interface to describe Query object fluent creation based on Microsoft Azure documentation: http://msdn.microsoft.com/en-us/library/windowsazure/jj613353.aspx + interface IQuery { + read(paramsQS?: Object): asyncPromise; + + orderBy(...propName: string[]): IQuery; + orderByDescending(...propName: string[]): IQuery; + select(...propNameSelected: string[]): IQuery; + select(funcProjectionFromThis: () => any): IQuery; + where(mapObjFilterCriteria: any): IQuery; + where(funcPredicateOnThis: (...qParams: any[]) => bool, ...qValues: any[]): IQuery; + skip(n: number): IQuery; + take(n: number): IQuery; + includeTotalCount(): IQuery; + + //internals found looking into code MobileServices.Web-1.0.0.js + //new (tableName: string, context: any): IQuery; + //getComponents(): any; + //toOData(): string; + } + + interface WindowsAzureStatic { + MobileServiceClient: MobileServiceClient; + } +} + +declare var WindowsAzure: Microsoft.WindowsAzure.WindowsAzureStatic; diff --git a/Q/Q-tests.ts b/Q/Q-tests.ts new file mode 100644 index 0000000000..8724ed5a60 --- /dev/null +++ b/Q/Q-tests.ts @@ -0,0 +1,49 @@ +/// + +var delay = function (delay) { + var d = Q.defer(); + setTimeout(d.resolve, delay); + return d.promise; +}; + +Q.when(delay(1000), function () { + console.log('Hello, World!'); +}); + +var eventually = function (eventually) { + return Q.delay(eventually, 1000); +}; + +var x = Q.all([1, 2, 3].map(eventually)); +Q.when(x, function (x) { + console.log(x); +}); + +Q.all([ + eventually(10), + eventually(20) +]) +.spread(function (x, y) { + console.log(x, y); +}); + +Q.fcall(function () { }) +.then(function () { }) +.then(function () { }) +.then(function () { }) +.then(function (value4) { + // Do something with value4 +}, function (error) { + // Handle any error from step1 through step4 +}).done(); + +Q.allResolved([]) +.then(function (promises: Qpromise[]) { + promises.forEach(function (promise) { + if (promise.isFulfilled()) { + var value = promise.valueOf(); + } else { + var exception = promise.valueOf().exception; + } + }) +}); diff --git a/Q/Q.d.ts b/Q/Q.d.ts new file mode 100644 index 0000000000..029550162c --- /dev/null +++ b/Q/Q.d.ts @@ -0,0 +1,63 @@ +// Type definitions for Q +// Project: https://github.com/kriskowal/q +// Definitions by: Barrie Nemetchek +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface Qdeferred { + promise: Qpromise; + resolve(value: any): any; + reject(reason: any); + notify(value: any); + makeNodeResolver(): Function; +} + +interface Qpromise { + fail(errorCallback: Function): Qpromise; + fin(finallyCallback: Function): Qpromise; + then(onFulfilled: Function, onRejected?: Function, onProgress?: Function): Qpromise; + spread(onFulfilled: Function, onRejected?: Function): Qpromise; + catch(onRejected: Function): Qpromise; + progress(onProgress: Function): Qpromise; + done(onFulfilled?: Function, onRejected?: Function, onProgress?: Function): Qpromise; + get (propertyName: String): Qpromise; + set (propertyName: String, value: any): Qpromise; + delete (propertyName: String): Qpromise; + post(methodName: String, args: any[]): Qpromise; + invoke(methodName: String, ...args: any[]): Qpromise; + keys(): Qpromise; + fapply(args: any[]): Qpromise; + fcall(method: Function, ...args: any[]): Qpromise; + timeout(ms: number): Qpromise; + delay(ms: number): Qpromise; + isFulfilled(): bool; + isRejected(): bool; + isPending(): bool; + valueOf(): any; +} + +interface QStatic { + when(value: any, onFulfilled: Function, onRejected?: Function): Qpromise; + try(method: Function, ...args: any[]): Qpromise; + fbind(method: Function, ...args: any[]): Qpromise; + fcall(method: Function, ...args: any[]): Qpromise; + all(promises: Qpromise[]): Qpromise; + allResolved(promises: Qpromise[]): Qpromise; + spread(onFulfilled: Function, onRejected: Function): Qpromise; + timeout(ms: number): Qpromise; + delay(ms: number): Qpromise; + delay(value: any, ms: number): Qpromise; + isFulfilled(): bool; + isRejected(): bool; + isPending(): bool; + valueOf(): any; + defer(): Qdeferred; + (value: any): Qpromise; + reject(): Qpromise; + promise(factory: { resolve: Function; reject: Function; notify: Function; }): Qpromise; + isPromise(value: any): bool; + async(generatorFunction: any): Qdeferred; + nextTick(callback: Function); + oneerror: any; + longStackJumpLimit: number; +} +declare var Q: QStatic; \ No newline at end of file diff --git a/Q/q.module-tests.ts b/Q/q.module-tests.ts new file mode 100644 index 0000000000..02116c2e85 --- /dev/null +++ b/Q/q.module-tests.ts @@ -0,0 +1,75 @@ +/// +/// + +import Q = module("q"); + +describe("q", function () { + it("should return", function (done) { + Q({ myValue: true }).then(function (obj) { + + if (obj.myValue) done(); + else done("didn't work =("); + }, + (err) => done(err)); + }); + + it("should process all", function (done: (err?) => void ) { + Q.all([Q(1), Q(2), Q(3)]).then(function (arr: number[]) { + var sum = arr.reduce(function (memo, cur) { + return memo + cur; + }, 0); + + if (sum === 6) done(); + else done({ actual: sum }); + }, + (err) => done(err)); + }); +}); + +var delay = function (delay) { + var d = Q.defer(); + setTimeout(d.resolve, delay); + return d.promise; +}; + +Q.when(delay(1000), function () { + console.log('Hello, World!'); +}); + +var eventually = function (eventually) { + return Q.delay(eventually, 1000); +}; + +var x = Q.all([1, 2, 3].map(eventually)); +Q.when(x, function (x) { + console.log(x); +}); + +Q.all([ + eventually(10), + eventually(20) +]) +.spread(function (x, y) { + console.log(x, y); +}); + +Q.fcall(function () { }) +.then(function () { }) +.then(function () { }) +.then(function () { }) +.then(function (value4) { + // Do something with value4 +}, function (error) { + // Handle any error from step1 through step4 +}).done(); + +Q.allResolved([]) +.then(function (promises: Qpromise[]) { + promises.forEach(function (promise) { + if (promise.isFulfilled()) { + var value = promise.valueOf(); + } else { + var exception = promise.valueOf().exception; + } + }) +}); \ No newline at end of file diff --git a/Q/q.module.d.ts b/Q/q.module.d.ts new file mode 100644 index 0000000000..9850e72767 --- /dev/null +++ b/Q/q.module.d.ts @@ -0,0 +1,27 @@ +/// + +module "q" { + export function when(value: any, onFulfilled: Function, onRejected?: Function): Qpromise; + export function try(method: Function, ...args: any[]): Qpromise; + export function fbind(method: Function, ...args: any[]): Qpromise; + export function fcall(method: Function, ...args: any[]): Qpromise; + export function all(promises: Qpromise[]): Qpromise; + export function allResolved(promises: Qpromise[]): Qpromise; + export function spread(onFulfilled: Function, onRejected: Function): Qpromise; + export function timeout(ms: number): Qpromise; + export function delay(ms: number): Qpromise; + export function delay(value: any, ms: number): Qpromise; + export function isFulfilled(): bool; + export function isRejected(): bool; + export function isPending(): bool; + export function valueOf(): any; + export function defer(): Qdeferred; + export function (value: any): Qpromise; + export function reject(): Qpromise; + export function promise(factory: { resolve: Function; reject: Function; notify: Function; }): Qpromise; + export function isPromise(value: any): bool; + export function async(generatorFunction: any): Qdeferred; + export function nextTick(callback: Function); + export var oneerror: any; + export var longStackJumpLimit: number; +} \ No newline at end of file diff --git a/README.md b/README.md index f3fa36b019..843ef64487 100644 --- a/README.md +++ b/README.md @@ -1,142 +1,169 @@ -DefinitelyTyped -=============== - -The repository for *high quality* TypeScript type definitions. - -Use a definition file like this: - -``` -/// -``` - -Contributor Guidelines ----------------------- -Definition files should be called 'library.d.ts'. -In case there are multiple versions supported, the latest one will be without a version number in the file name. -Older versions will be in the form of 'library-1.0.d.ts'. - -Test files called 'library-tests.ts'. -They are not runnable, in the TDD way. -They contain code that should compile with no errors, usually taken from the documentation.samples of the library. -It is very desirable each new contribution to contain tests too. - -Other means to get the definitions ----------------------------------- -[TypeScript definition package manager](https://github.com/Diullei/tsd) - -NuGet package(s) coming soon - -List of Definitions -------------------- -* [AngularJS](http://angularjs.org) (by [Diego Vilar](https://github.com/diegovilar)) ([wiki](https://github.com/borisyankov/DefinitelyTyped/wiki/AngularJS-Definitions-Usage-Notes)) -* [async](https://github.com/caolan/async) (by [Boris Yankov](https://github.com/borisyankov)) -* [Backbone.js](http://backbonejs.org/) (by [Boris Yankov](https://github.com/borisyankov)) -* [Bootbox](https://github.com/makeusabrew/bootbox) (by [Vincent Bortone](https://github.com/vbortone/)) -* [Bootstrap](http://twitter.github.com/bootstrap/) (by [Boris Yankov](https://github.com/borisyankov)) -* [bootstrap.datepicker](https://github.com/eternicode/bootstrap-datepicker) (by [Boris Yankov](https://github.com/borisyankov)) -* [Box2DWeb](http://code.google.com/p/box2dweb/) (by [Josh Baldwin](https://github.com/jbaldwin/)) -* [Breeze](http://www.breezejs.com/) (by [Boris Yankov](https://github.com/borisyankov)) -* [Chosen](http://harvesthq.github.com/chosen/) (by [Boris Yankov](https://github.com/borisyankov)) -* [Chrome](http://developer.chrome.com/extensions/) (by [Matthew Kimber](https://github.com/matthewkimber)) -* [CodeMirror](http://codemirror.net) (by [Franois de Campredon](https://github.com/fdecampredon)) -* [d3.js](http://d3js.org/) (from TypeScript samples) -* [domo](http://domo-js.com/) (by [Steve Fenton](https://github.com/Steve-Fenton)) -* [EaselJS](http://www.createjs.com/#!/EaselJS) (by [Pedro Ferreira](https://bitbucket.org/drk4)) -* [ember.js](http://emberjs.com/) (by [Boris Yankov](https://github.com/borisyankov)) -* [Express](http://expressjs.com/) (by [Boris Yankov](https://github.com/borisyankov)) -* [Fabric.js](http://fabricjs.com/) (by [Oliver Klemencic](https://github.com/oklemencic/)) -* [Fancybox](http://fancybox.net/) (by [Boris Yankov](https://github.com/borisyankov)) -* [Finite State Machine](https://github.com/jakesgordon/javascript-state-machine) (by [Boris Yankov](https://github.com/borisyankov)) -* [Foundation](http://foundation.zurb.com/) (by [Boris Yankov](https://github.com/borisyankov)) -* [glDatePicker](http://glad.github.com/glDatePicker/) (by [Dniel Tar](https://github.com/qcz)) -* [GreenSock Animation Platform (GSAP)](http://www.greensock.com/get-started-js/) (by [Robert S.](https://github.com/codeBelt)) -* [GoogleMaps](https://developers.google.com/maps/) (by [Esben Nepper](https://github.com/eNepper)) -* [Hammer.js](http://eightmedia.github.com/hammer.js/) (by [Boris Yankov](https://github.com/borisyankov)) -* [Handlebars](http://handlebarsjs.com/) (by [Boris Yankov](https://github.com/borisyankov)) -* [Highcharts](http://www.highcharts.com/) (by [damianog](https://github.com/damianog)) -* [History.js](https://github.com/balupton/History.js/) (by [Boris Yankov](https://github.com/borisyankov)) -* [Humane.js](http://wavded.github.com/humane-js/) (by [John Vrbanac](https://github.com/jmvrbanac)) -* [i18next](http://i18next.com/) (by [Maarten Docter](https://github.com/mdocter)) -* [Impress.js](https://github.com/bartaz/impress.js) (by [Boris Yankov](https://github.com/borisyankov)) -* [iScroll](http://cubiq.org/iscroll-4) (by [Boris Yankov](https://github.com/borisyankov)) -* [Jasmine](http://pivotal.github.com/jasmine/) (by [Boris Yankov](https://github.com/borisyankov)) -* [jQRangeSlider](http://ghusse.github.com/jQRangeSlider) (by [Dniel Tar](https://github.com/qcz)) -* [jQuery](http://jquery.com/) (from TypeScript samples) -* [jQuery Mobile](http://jquerymobile.com) (by [Boris Yankov](https://github.com/borisyankov)) -* [jQuery UI](http://jqueryui.com/) (by [Boris Yankov](https://github.com/borisyankov)) -* [jQuery.BBQ](http://benalman.com/projects/jquery-bbq-plugin/) (by [Adam R. Smith](https://github.com/sunetos)) -* [jQuery.contextMenu](http://medialize.github.com/jQuery-contextMenu/) (by [Natan Vivo](https://github.com/nvivo/)) -* [jQuery.Cookie](https://github.com/carhartl/jquery-cookie) (by [Roy Goode](https://github.com/RoyGoode)) -* [jQuery.dynatree](http://code.google.com/p/dynatree/) (by [Franois de Campredon](https://github.com/fdecampredon)) -* [jQuery.Flot](http://www.flotcharts.org/) (by [Matt Burland](https://github.com/burlandm)) -* [jQuery.Globalize](https://github.com/jquery/globalize) (by [Boris Yankov](https://github.com/borisyankov)) -* [jQuery.jNotify]( http://jnotify.codeplex.com) (by [James Curran](https://github.com/jamescurran/)) -* [jQuery.simplePagination](https://github.com/flaviusmatis/simplePagination.js) (by [Natan Vivo](https://github.com/nvivo/)) -* [jQuery.Timepicker](http://fgelinas.com/code/timepicker/) (by [Anwar Javed](https://github.com/anwarjaved)) -* [jQuery.Transit](http://ricostacruz.com/jquery.transit/) (by [MrBigDog2U](https://github.com/MrBigDog2U)) -* [jQuery.Validation](http://bassistance.de/jquery-plugins/jquery-plugin-validation/) (by [Boris Yankov](https://github.com/borisyankov)) -* [jQuery.Watermark](http://jquery-watermark.googlecode.com) (by [Anwar Javed](https://github.com/anwarjaved)) -* [KeyboardJS](https://github.com/RobertWHurst/KeyboardJS) (by [Vincent Bortone](https://github.com/vbortone/)) -* [Knockback](http://kmalakoff.github.com/knockback/) (by [Marcel Binot](https://github.com/docgit)) -* [Knockout.js](http://knockoutjs.com/) (by [Boris Yankov](https://github.com/borisyankov)) -* [Knockout.Mapping](https://github.com/SteveSanderson/knockout.mapping) (by [Boris Yankov](https://github.com/borisyankov)) -* [Knockout.Postbox](https://github.com/rniemeyer/knockout-postbox) (by [Judah Gabriel](https://github.com/JudahGabriel)) -* [Knockout.Validation](https://github.com/ericmbarnard/Knockout-Validation) (by [Dan Ludwig](https://github.com/danludwig)) -* [Knockout.Viewmodel](http://romanych.github.com/ko.editables/) (by [Oisin Grehan](https://github.com/oising)) -* [ko.editables](http://romanych.github.com/ko.editables/) (by [Oisin Grehan](https://github.com/oising)) -* [KoLite](https://github.com/CodeSeven/kolite) (by [Boris Yankov](https://github.com/borisyankov)) -* [linq.js](http://linqjs.codeplex.com/) (by [Marcin Najder](https://github.com/marcinnajder)) -* [Marked](https://github.com/chjj/marked) (by [William Orr](https://github.com/worr)) -* [Modernizr](http://modernizr.com/) (by [Boris Yankov](https://github.com/borisyankov)) -* [Moment.js](https://github.com/timrwood/moment) (by [Michael Lakerveld](https://github.com/Lakerfield)) -* [Mousetrap](http://craig.is/killing/mice) (by [Dniel Tar](https://github.com/qcz)) -* [Mustache.js](https://github.com/janl/mustache.js) (by [Boris Yankov](https://github.com/borisyankov)) -* [Node.js](http://nodejs.org/) (from TypeScript samples) -* [node_redis](https://github.com/mranney/node_redis) (by [Boris Yankov](https://github.com/borisyankov)) -* [node-sqlserver](https://github.com/WindowsAzure/node-sqlserver) (by [Boris Yankov](https://github.com/borisyankov)) -* [Numeral.js](https://github.com/adamwdraper/Numeral-js) (by [Vincent Bortone](https://github.com/vbortone/)) -* [PhoneGap](http://phonegap.com) (by [Boris Yankov](https://github.com/borisyankov)) -* [Platform](https://github.com/bestiejs/platform.js) (by [Jake Hickman](https://github.com/JakeH)) -* [PouchDB](http://pouchdb.com) (by [Bill Sears](https://github.com/MrBigDog2U/)) -* [PreloadJS](http://www.createjs.com/#!/PreloadJS) (by [Pedro Ferreira](https://bitbucket.org/drk4)) -* [QUnit](http://qunitjs.com/) (by [Diullei Gomes](https://github.com/Diullei)) -* [Rx.js](http://rx.codeplex.com/) (by [gsino](http://www.codeplex.com/site/users/view/gsino)) -* [Raphael](http://raphaeljs.com/) (by [CheCoxshall](https://github.com/CheCoxshall)) -* [require.js](http://requirejs.org/) (by [Josh Baldwin](https://github.com/jbaldwin/)) -* [Sammy.js](http://sammyjs.org/) (by [Boris Yankov](https://github.com/borisyankov)) -* [Select2](http://ivaynberg.github.com/select2/) (by [Boris Yankov](https://github.com/borisyankov)) -* [SignalR](http://www.asp.net/signalr) (by [Boris Yankov](https://github.com/borisyankov)) -* [socket.io](http://socket.io) (by [William Orr](https://github.com/worr)) -* [SockJS](https://github.com/sockjs/sockjs-client) (by [Emil Ivanov](https://github.com/vladev)) -* [SoundJS](http://www.createjs.com/#!/SoundJS) (by [Pedro Ferreira](https://bitbucket.org/drk4)) -* [Spin](http://fgnass.github.com/spin.js/) (by [Boris Yankov](https://github.com/borisyankov)) -* [Sugar](http://sugarjs.com/) (by [Josh Baldwin](https://github.com/jbaldwin/)) -* [SwipeView](http://cubiq.org/swipeview) (by [Boris Yankov](https://github.com/borisyankov)) -* [Teechart](http://www.steema.com) (by [Steema](http://www.steema.com)) -* [Toastr](https://github.com/CodeSeven/toastr) (by [Boris Yankov](https://github.com/borisyankov)) -* [TweenJS](http://www.createjs.com/#!/TweenJS) (by [Pedro Ferreira](https://bitbucket.org/drk4)) -* [tween.js](https://github.com/sole/tween.js/) (by [Adam R. Smith](https://github.com/sunetos)) -* [twitter-bootstrap-wizard](https://github.com/VinceG/twitter-bootstrap-wizard) (by [Blake Niemyjski](https://github.com/niemyjski)) -* [Ubuntu Unity Web API](https://launchpad.net/libunity-webapps) (by [John Vrbanac](https://github.com/jmvrbanac)) -* [Underscore.js](http://underscorejs.org/) (by [Boris Yankov](https://github.com/borisyankov)) -* [Underscore.js (Typed)](http://underscorejs.org/) (by [Josh Baldwin](https://github.com/jbaldwin/)) -* [Viewporter](https://github.com/zynga/viewporter) (by [Boris Yankov](https://github.com/borisyankov)) -* [Vimeo](http://developer.vimeo.com/player/js-api) (by [Daz Wilkin](https://github.com/DazWilkin/)) -* [WebRTC](http://dev.w3.org/2011/webrtc/editor/webrtc.html) (by [Ken Smith](https://github.com/smithkl42)) -* [YouTube](https://developers.google.com/youtube/) (by [Daz Wilkin](https://github.com/DazWilkin/)) -* [Zynga Scroller](https://github.com/zynga/scroller) (by [Boris Yankov](https://github.com/borisyankov)) -* [ZeroClipboard] (https://github.com/jonrohan/ZeroClipboard) (by [Eric J. Smith] (https://github.com/ejsmith)) - -Requested Definitions ---------------------- -* [Rickshaw](https://github.com/shutterstock/rickshaw) -* [Crossfilter](https://github.com/square/crossfilter) -* [dc.js](https://github.com/NickQiZhu/dc.js) -* [store.js](https://github.com/marcuswestin/store.js) -* [google.visualizations](https://developers.google.com/chart/) -* [Tags Manager](http://welldonethings.com/tags/manager) -* [jsoneditoronline](https://github.com/wjosdejong/jsoneditoronline) -* [Tags Manager](http://welldonethings.com/tags/manager) -* [Prelude.ls](http://gkz.github.com/prelude-ls/) -* [MooTools](http://mootools.net/) -* [Lo-Dash](http://lodash.com/) \ No newline at end of file +DefinitelyTyped [![Build Status](https://travis-ci.org/borisyankov/DefinitelyTyped.png?branch=master)](https://travis-ci.org/borisyankov/DefinitelyTyped) +=============== + +The repository for *high quality* TypeScript type definitions. + +Use a definition file like this: + +``` +/// +``` + +Contributor Guidelines +---------------------- + +See the section: [How to contribute](https://github.com/borisyankov/DefinitelyTyped/wiki/How-to-contribute) + +Other means to get the definitions +---------------------------------- + +* [NuGet packages](http://nuget.org/packages?q=Definitelytyped) + +* [TypeScript definition package manager](https://github.com/Diullei/tsd) + +* [tsdpm](http://www.tsdpm.com/) - Online search + +List of Definitions +------------------- +* [Ace Cloud9 Editor](http://ace.ajax.org/) (by [Diullei Gomes](https://github.com/Diullei)) +* [AmCharts](http://www.amcharts.com/) (by [Covobonomo](https://github.com/covobonomo/)) +* [AngularJS](http://angularjs.org) (by [Diego Vilar](https://github.com/diegovilar)) ([wiki](https://github.com/borisyankov/DefinitelyTyped/wiki/AngularJS-Definitions-Usage-Notes)) +* [async](https://github.com/caolan/async) (by [Boris Yankov](https://github.com/borisyankov)) +* [Backbone.js](http://backbonejs.org/) (by [Boris Yankov](https://github.com/borisyankov)) +* [Bootbox](https://github.com/makeusabrew/bootbox) (by [Vincent Bortone](https://github.com/vbortone/)) +* [Bootstrap](http://twitter.github.com/bootstrap/) (by [Boris Yankov](https://github.com/borisyankov)) +* [bootstrap-notify](https://github.com/Nijikokun/bootstrap-notify) (by [Blake Niemyjski](https://github.com/niemyjski)) +* [bootstrap.datepicker](https://github.com/eternicode/bootstrap-datepicker) (by [Boris Yankov](https://github.com/borisyankov)) +* [Box2DWeb](http://code.google.com/p/box2dweb/) (by [Josh Baldwin](https://github.com/jbaldwin/)) +* [Breeze](http://www.breezejs.com/) (by [Boris Yankov](https://github.com/borisyankov)) +* [CasperJS](http://casperjs.org) (by [Jed Hunsaker](https://github.com/jedhunsaker)) +* [Cheerio](https://github.com/MatthewMueller/cheerio) (by [Bret Little](https://github.com/blittle)) +* [Chosen](http://harvesthq.github.com/chosen/) (by [Boris Yankov](https://github.com/borisyankov)) +* [Chrome](http://developer.chrome.com/extensions/) (by [Matthew Kimber](https://github.com/matthewkimber)) +* [CodeMirror](http://codemirror.net) (by [Fran�ois de Campredon](https://github.com/fdecampredon)) +* [Commander](http://github.com/visionmedia/commander.js) (by [Marcelo Dezem](https://github.com/mdezem)) +* [d3.js](http://d3js.org/) (from TypeScript samples) +* [domo](http://domo-js.com/) (by [Steve Fenton](https://github.com/Steve-Fenton)) +* [dust](http://linkedin.github.com/dustjs) (by [Marcelo Dezem](https://github.com/mdezem)) +* [EaselJS](http://www.createjs.com/#!/EaselJS) (by [Pedro Ferreira](https://bitbucket.org/drk4)) +* [ember.js](http://emberjs.com/) (by [Boris Yankov](https://github.com/borisyankov)) +* [EpicEditor](http://epiceditor.com/) (by [Boris Yankov](https://github.com/borisyankov)) +* [Express](http://expressjs.com/) (by [Boris Yankov](https://github.com/borisyankov)) +* [Fabric.js](http://fabricjs.com/) (by [Oliver Klemencic](https://github.com/oklemencic/)) +* [Fancybox](http://fancybox.net/) (by [Boris Yankov](https://github.com/borisyankov)) +* [File API: Directories and System](http://www.w3.org/TR/file-system-api/) (by [Kon](http://phyzkit.net/)) +* [File API: Writer](http://www.w3.org/TR/file-writer-api/) (by [Kon](http://phyzkit.net/)) +* [Finite State Machine](https://github.com/jakesgordon/javascript-state-machine) (by [Boris Yankov](https://github.com/borisyankov)) +* [FlexSlider](http://www.woothemes.com/flexslider/) (by [Diullei Gomes](https://github.com/Diullei)) +* [Foundation](http://foundation.zurb.com/) (by [Boris Yankov](https://github.com/borisyankov)) +* [Gamepad](http://www.w3.org/TR/gamepad/) (by [Kon](http://phyzkit.net/)) +* [glDatePicker](http://glad.github.com/glDatePicker/) (by [D�niel Tar](https://github.com/qcz)) +* [GreenSock Animation Platform (GSAP)](http://www.greensock.com/get-started-js/) (by [Robert S.](https://github.com/codeBelt)) +* [GoogleMaps](https://developers.google.com/maps/) (by [Esben Nepper](https://github.com/eNepper)) +* [Google Geolocation](https://code.google.com/p/geo-location-javascript/) (by [Vincent Bortone](https://github.com/vbortone)) +* [Hammer.js](http://eightmedia.github.com/hammer.js/) (by [Boris Yankov](https://github.com/borisyankov)) +* [Handlebars](http://handlebarsjs.com/) (by [Boris Yankov](https://github.com/borisyankov)) +* [Highcharts](http://www.highcharts.com/) (by [damianog](https://github.com/damianog)) +* [History.js](https://github.com/balupton/History.js/) (by [Boris Yankov](https://github.com/borisyankov)) +* [Humane.js](http://wavded.github.com/humane-js/) (by [John Vrbanac](https://github.com/jmvrbanac)) +* [i18next](http://i18next.com/) (by [Maarten Docter](https://github.com/mdocter)) +* [Impress.js](https://github.com/bartaz/impress.js) (by [Boris Yankov](https://github.com/borisyankov)) +* [iScroll](http://cubiq.org/iscroll-4) (by [Boris Yankov](https://github.com/borisyankov)) +* [jake](https://github.com/mde/jake) (by [Kon](http://phyzkit.net/)) +* [Jasmine](http://pivotal.github.com/jasmine/) (by [Boris Yankov](https://github.com/borisyankov)) +* [jQRangeSlider](http://ghusse.github.com/jQRangeSlider) (by [D�niel Tar](https://github.com/qcz)) +* [jQuery](http://jquery.com/) (from TypeScript samples) +* [jQuery Mobile](http://jquerymobile.com) (by [Boris Yankov](https://github.com/borisyankov)) +* [jQuery UI](http://jqueryui.com/) (by [Boris Yankov](https://github.com/borisyankov)) +* [jQuery.BBQ](http://benalman.com/projects/jquery-bbq-plugin/) (by [Adam R. Smith](https://github.com/sunetos)) +* [jQuery.contextMenu](http://medialize.github.com/jQuery-contextMenu/) (by [Natan Vivo](https://github.com/nvivo/)) +* [jQuery.clientSideLogging](https://github.com/remybach/jQuery.clientSideLogging/) (by [Diullei Gomes](https://github.com/diullei/)) +* [jQuery.Cookie](https://github.com/carhartl/jquery-cookie) (by [Roy Goode](https://github.com/RoyGoode)) +* [jQuery.Cycle](http://jquery.malsup.com/cycle/) (by [Fran�ois Guillot](http://fguillot.developpez.com/)) +* [jQuery.dynatree](http://code.google.com/p/dynatree/) (by [Fran�ois de Campredon](https://github.com/fdecampredon)) +* [jQuery.Flot](http://www.flotcharts.org/) (by [Matt Burland](https://github.com/burlandm)) +* [jQuery.form](http://malsup.com/jquery/form/) (by [Fran�ois Guillot](http://fguillot.developpez.com/)) +* [jQuery.Globalize](https://github.com/jquery/globalize) (by [Boris Yankov](https://github.com/borisyankov)) +* [jQuery.jNotify](http://jnotify.codeplex.com) (by [James Curran](https://github.com/jamescurran/)) +* [jQuery.scrollTo](https://github.com/flesler/jquery.scrollTo) (by [Neil Stalker](https://github.com/nestalk/)) +* [jQuery.simplePagination](https://github.com/flaviusmatis/simplePagination.js) (by [Natan Vivo](https://github.com/nvivo/)) +* [jQuery.timeago](http://timeago.yarp.com/) (by [Fran�ois Guillot](http://fguillot.developpez.com/)) +* [jQuery.Timepicker](http://fgelinas.com/code/timepicker/) (by [Anwar Javed](https://github.com/anwarjaved)) +* [jQuery.Transit](http://ricostacruz.com/jquery.transit/) (by [MrBigDog2U](https://github.com/MrBigDog2U)) +* [jQuery.Validation](http://bassistance.de/jquery-plugins/jquery-plugin-validation/) (by [Boris Yankov](https://github.com/borisyankov)) +* [jQuery.Watermark](http://jquery-watermark.googlecode.com) (by [Anwar Javed](https://github.com/anwarjaved)) +* [JSDeferred](http://cho45.stfuawsc.com/jsdeferred/) (by [Daisuke Mino](https://github.com/minodisk)) +* [JSONEditorOnline](https://github.com/josdejong/jsoneditoronline) (by [Vincent Bortone](https://github.com/vbortone/)) +* [KeyboardJS](https://github.com/RobertWHurst/KeyboardJS) (by [Vincent Bortone](https://github.com/vbortone/)) +* [Knockback](http://kmalakoff.github.com/knockback/) (by [Marcel Binot](https://github.com/docgit)) +* [Knockout.js](http://knockoutjs.com/) (by [Boris Yankov](https://github.com/borisyankov)) +* [Knockout.Mapping](https://github.com/SteveSanderson/knockout.mapping) (by [Boris Yankov](https://github.com/borisyankov)) +* [Knockout.Postbox](https://github.com/rniemeyer/knockout-postbox) (by [Judah Gabriel](https://github.com/JudahGabriel)) +* [Knockout.Validation](https://github.com/ericmbarnard/Knockout-Validation) (by [Dan Ludwig](https://github.com/danludwig)) +* [Knockout.Viewmodel](http://coderenaissance.github.com/knockout.viewmodel/) (by [Oisin Grehan](https://github.com/oising)) +* [ko.editables](http://romanych.github.com/ko.editables/) (by [Oisin Grehan](https://github.com/oising)) +* [KoLite](https://github.com/CodeSeven/kolite) (by [Boris Yankov](https://github.com/borisyankov)) +* [Leaflet](https://github.com/Leaflet/Leaflet) (by [Vladimir](https://github.com/rgripper)) +* [Libxmljs](https://github.com/polotek/libxmljs) (by [François de Campredon](https://github.com/fdecampredon)) +* [linq.js](http://linqjs.codeplex.com/) (by [Marcin Najder](https://github.com/marcinnajder)) +* [Livestamp.js](https://github.com/mattbradley/livestampjs) (by [Vincent Bortone] (https://github.com/vbortone)) +* [Marked](https://github.com/chjj/marked) (by [William Orr](https://github.com/worr)) +* [Modernizr](http://modernizr.com/) (by [Boris Yankov](https://github.com/borisyankov)) +* [Moment.js](https://github.com/timrwood/moment) (by [Michael Lakerveld](https://github.com/Lakerfield)) +* [Mousetrap](http://craig.is/killing/mice) (by [D�niel Tar](https://github.com/qcz)) +* [Mustache.js](https://github.com/janl/mustache.js) (by [Boris Yankov](https://github.com/borisyankov)) +* [Node.js](http://nodejs.org/) (from TypeScript samples) +* [node_redis](https://github.com/mranney/node_redis) (by [Boris Yankov](https://github.com/borisyankov)) +* [node-sqlserver](https://github.com/WindowsAzure/node-sqlserver) (by [Boris Yankov](https://github.com/borisyankov)) +* [Numeral.js](https://github.com/adamwdraper/Numeral-js) (by [Vincent Bortone](https://github.com/vbortone/)) +* [PhantomJS](http://phantomjs.org) (by [Jed Hunsaker](https://github.com/jedhunsaker)) +* [PhoneGap](http://phonegap.com) (by [Boris Yankov](https://github.com/borisyankov)) +* [Platform](https://github.com/bestiejs/platform.js) (by [Jake Hickman](https://github.com/JakeH)) +* [PouchDB](http://pouchdb.com) (by [Bill Sears](https://github.com/MrBigDog2U/)) +* [PreloadJS](http://www.createjs.com/#!/PreloadJS) (by [Pedro Ferreira](https://bitbucket.org/drk4)) +* [QUnit](http://qunitjs.com/) (by [Diullei Gomes](https://github.com/Diullei)) +* [Restify](https://github.com/mcavage/node-restify) (by [Bret Little](https://github.com/blittle)) +* [Rx.js](http://rx.codeplex.com/) (by [gsino](http://www.codeplex.com/site/users/view/gsino)) +* [Raphael](http://raphaeljs.com/) (by [CheCoxshall](https://github.com/CheCoxshall)) +* [require.js](http://requirejs.org/) (by [Josh Baldwin](https://github.com/jbaldwin/)) +* [Sammy.js](http://sammyjs.org/) (by [Boris Yankov](https://github.com/borisyankov)) +* [Select2](http://ivaynberg.github.com/select2/) (by [Boris Yankov](https://github.com/borisyankov)) +* [SignalR](http://www.asp.net/signalr) (by [Boris Yankov](https://github.com/borisyankov)) +* [Sinon](http://sinonjs.org/) (by [William Sears](https://github.com/mrbigdog2u)) +* [socket.io](http://socket.io) (by [William Orr](https://github.com/worr)) +* [SockJS](https://github.com/sockjs/sockjs-client) (by [Emil Ivanov](https://github.com/vladev)) +* [SoundJS](http://www.createjs.com/#!/SoundJS) (by [Pedro Ferreira](https://bitbucket.org/drk4)) +* [Spin](http://fgnass.github.com/spin.js/) (by [Boris Yankov](https://github.com/borisyankov)) +* [Store.js](https://github.com/marcuswestin/store.js/) (by [Vincent Bortone](https://github.com/vbortone)) +* [Sugar](http://sugarjs.com/) (by [Josh Baldwin](https://github.com/jbaldwin/)) +* [SwipeView](http://cubiq.org/swipeview) (by [Boris Yankov](https://github.com/borisyankov)) +* [Tags Manager](http://welldonethings.com/tags/manager) (by [Vincent Bortone](https://github.com/vbortone)) +* [Teechart](http://www.steema.com) (by [Steema](http://www.steema.com)) +* [three.js](http://mrdoob.github.com/three.js/) (by [Kon](http://phyzkit.net/)) +* [Toastr](https://github.com/CodeSeven/toastr) (by [Boris Yankov](https://github.com/borisyankov)) +* [trunk8](https://github.com/rviscomi/trunk8) (by [Blake Niemyjski](https://github.com/niemyjski)) +* [TweenJS](http://www.createjs.com/#!/TweenJS) (by [Pedro Ferreira](https://bitbucket.org/drk4)) +* [tween.js](https://github.com/sole/tween.js/) (by [Adam R. Smith](https://github.com/sunetos)) +* [twitter-bootstrap-wizard](https://github.com/VinceG/twitter-bootstrap-wizard) (by [Blake Niemyjski](https://github.com/niemyjski)) +* [Ubuntu Unity Web API](https://launchpad.net/libunity-webapps) (by [John Vrbanac](https://github.com/jmvrbanac)) +* [Underscore.js](http://underscorejs.org/) (by [Boris Yankov](https://github.com/borisyankov)) +* [Underscore.js (Typed)](http://underscorejs.org/) (by [Josh Baldwin](https://github.com/jbaldwin/)) +* [Underscore-ko.js](https://github.com/kamranayub/UnderscoreKO) (by [Maurits Elbers](https://github.com/MagicMau)) +* [Viewporter](https://github.com/zynga/viewporter) (by [Boris Yankov](https://github.com/borisyankov)) +* [Vimeo](http://developer.vimeo.com/player/js-api) (by [Daz Wilkin](https://github.com/DazWilkin/)) +* [WebRTC](http://dev.w3.org/2011/webrtc/editor/webrtc.html) (by [Ken Smith](https://github.com/smithkl42)) +* [YouTube](https://developers.google.com/youtube/) (by [Daz Wilkin](https://github.com/DazWilkin/)) +* [Zynga Scroller](https://github.com/zynga/scroller) (by [Boris Yankov](https://github.com/borisyankov)) +* [ZeroClipboard](https://github.com/jonrohan/ZeroClipboard) (by [Eric J. Smith](https://github.com/ejsmith)) + +Requested Definitions +--------------------- +* [Rickshaw](https://github.com/shutterstock/rickshaw) +* [jQuery ScrollTo](https://github.com/balupton/jquery-scrollto) +* [Crossfilter](https://github.com/square/crossfilter) +* [dc.js](https://github.com/NickQiZhu/dc.js) +* [google.visualizations](https://developers.google.com/chart/) +* [Prelude.ls](http://gkz.github.com/prelude-ls/) +* [MooTools](http://mootools.net/) +* [Lo-Dash](http://lodash.com/) +* [java](https://github.com/nearinfinity/node-java) diff --git a/_infrastructure/tests/src/exec.js b/_infrastructure/tests/src/exec.js new file mode 100644 index 0000000000..b29e4c0175 --- /dev/null +++ b/_infrastructure/tests/src/exec.js @@ -0,0 +1,57 @@ +var ExecResult = (function () { + function ExecResult() { + this.stdout = ""; + this.stderr = ""; + } + return ExecResult; +})(); +var WindowsScriptHostExec = (function () { + function WindowsScriptHostExec() { } + WindowsScriptHostExec.prototype.exec = function (filename, cmdLineArgs, handleResult) { + var result = new ExecResult(); + var shell = new ActiveXObject('WScript.Shell'); + try { + var process = shell.Exec(filename + ' ' + cmdLineArgs.join(' ')); + } catch (e) { + result.stderr = e.message; + result.exitCode = 1; + handleResult(result); + return; + } + while(process.Status != 0) { + } + result.exitCode = process.ExitCode; + if(!process.StdOut.AtEndOfStream) { + result.stdout = process.StdOut.ReadAll(); + } + if(!process.StdErr.AtEndOfStream) { + result.stderr = process.StdErr.ReadAll(); + } + handleResult(result); + }; + return WindowsScriptHostExec; +})(); +var NodeExec = (function () { + function NodeExec() { } + NodeExec.prototype.exec = function (filename, cmdLineArgs, handleResult) { + var nodeExec = require('child_process').exec; + var result = new ExecResult(); + result.exitCode = null; + var cmdLine = filename + ' ' + cmdLineArgs.join(' '); + var process = nodeExec(cmdLine, function (error, stdout, stderr) { + result.stdout = stdout; + result.stderr = stderr; + result.exitCode = error ? error.code : 0; + handleResult(result); + }); + }; + return NodeExec; +})(); +var Exec = (function () { + var global = Function("return this;").call(null); + if(typeof global.ActiveXObject !== "undefined") { + return new WindowsScriptHostExec(); + } else { + return new NodeExec(); + } +})(); diff --git a/_infrastructure/tests/src/exec.ts b/_infrastructure/tests/src/exec.ts new file mode 100644 index 0000000000..f277d39425 --- /dev/null +++ b/_infrastructure/tests/src/exec.ts @@ -0,0 +1,77 @@ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +// Allows for executing a program with command-line arguments and reading the result +interface IExec { + exec: (filename: string, cmdLineArgs: string[], handleResult: (ExecResult) => void) => void; +} + +declare var require; + +class ExecResult { + public stdout = ""; + public stderr = ""; + public exitCode: number; +} + +class WindowsScriptHostExec implements IExec { + public exec(filename: string, cmdLineArgs: string[], handleResult: (ExecResult) => void) : void { + var result = new ExecResult(); + var shell = new ActiveXObject('WScript.Shell'); + try { + var process = shell.Exec(filename + ' ' + cmdLineArgs.join(' ')); + } catch(e) { + result.stderr = e.message; + result.exitCode = 1 + handleResult(result); + return; + } + // Wait for it to finish running + while (process.Status != 0) { /* todo: sleep? */ } + + + result.exitCode = process.ExitCode; + if(!process.StdOut.AtEndOfStream) result.stdout = process.StdOut.ReadAll(); + if(!process.StdErr.AtEndOfStream) result.stderr = process.StdErr.ReadAll(); + + handleResult(result); + } +} + +class NodeExec implements IExec { + public exec(filename: string, cmdLineArgs: string[], handleResult: (ExecResult) => void) : void { + var nodeExec = require('child_process').exec; + + var result = new ExecResult(); + result.exitCode = null; + var cmdLine = filename + ' ' + cmdLineArgs.join(' '); + + var process = nodeExec(cmdLine, function (error, stdout, stderr) { + result.stdout = stdout; + result.stderr = stderr; + result.exitCode = error ? error.code : 0; + handleResult(result); + }); + } +} + +var Exec: IExec = function() : IExec { + var global = Function("return this;").call(null); + if(typeof global.ActiveXObject !== "undefined") { + return new WindowsScriptHostExec(); + } else { + return new NodeExec(); + } +}(); \ No newline at end of file diff --git a/_infrastructure/tests/src/io.js b/_infrastructure/tests/src/io.js new file mode 100644 index 0000000000..591fc94431 --- /dev/null +++ b/_infrastructure/tests/src/io.js @@ -0,0 +1,425 @@ +var IOUtils; +(function (IOUtils) { + function createDirectoryStructure(ioHost, dirName) { + if(ioHost.directoryExists(dirName)) { + return; + } + var parentDirectory = ioHost.dirName(dirName); + if(parentDirectory != "") { + createDirectoryStructure(ioHost, parentDirectory); + } + ioHost.createDirectory(dirName); + } + function createFileAndFolderStructure(ioHost, fileName, useUTF8) { + var path = ioHost.resolvePath(fileName); + var dirName = ioHost.dirName(path); + createDirectoryStructure(ioHost, dirName); + return ioHost.createFile(path, useUTF8); + } + IOUtils.createFileAndFolderStructure = createFileAndFolderStructure; + function throwIOError(message, error) { + var errorMessage = message; + if(error && error.message) { + errorMessage += (" " + error.message); + } + throw new Error(errorMessage); + } + IOUtils.throwIOError = throwIOError; +})(IOUtils || (IOUtils = {})); + +var IO = (function () { + function getWindowsScriptHostIO() { + var fso = new ActiveXObject("Scripting.FileSystemObject"); + var streamObjectPool = []; + function getStreamObject() { + if(streamObjectPool.length > 0) { + return streamObjectPool.pop(); + } else { + return new ActiveXObject("ADODB.Stream"); + } + } + function releaseStreamObject(obj) { + streamObjectPool.push(obj); + } + var args = []; + for(var i = 0; i < WScript.Arguments.length; i++) { + args[i] = WScript.Arguments.Item(i); + } + return { + readFile: function (path) { + try { + var streamObj = getStreamObject(); + streamObj.Open(); + streamObj.Type = 2; + streamObj.Charset = 'x-ansi'; + streamObj.LoadFromFile(path); + var bomChar = streamObj.ReadText(2); + streamObj.Position = 0; + if((bomChar.charCodeAt(0) == 254 && bomChar.charCodeAt(1) == 255) || (bomChar.charCodeAt(0) == 255 && bomChar.charCodeAt(1) == 254)) { + streamObj.Charset = 'unicode'; + } else if(bomChar.charCodeAt(0) == 239 && bomChar.charCodeAt(1) == 187) { + streamObj.Charset = 'utf-8'; + } + var str = streamObj.ReadText(-1); + streamObj.Close(); + releaseStreamObject(streamObj); + return str; + } catch (err) { + IOUtils.throwIOError("Error reading file \"" + path + "\".", err); + } + }, + writeFile: function (path, contents) { + var file = this.createFile(path); + file.Write(contents); + file.Close(); + }, + fileExists: function (path) { + return fso.FileExists(path); + }, + resolvePath: function (path) { + return fso.GetAbsolutePathName(path); + }, + dirName: function (path) { + return fso.GetParentFolderName(path); + }, + findFile: function (rootPath, partialFilePath) { + var path = fso.GetAbsolutePathName(rootPath) + "/" + partialFilePath; + while(true) { + if(fso.FileExists(path)) { + try { + var content = this.readFile(path); + return { + content: content, + path: path + }; + } catch (err) { + } + } else { + rootPath = fso.GetParentFolderName(fso.GetAbsolutePathName(rootPath)); + if(rootPath == "") { + return null; + } else { + path = fso.BuildPath(rootPath, partialFilePath); + } + } + } + }, + deleteFile: function (path) { + try { + if(fso.FileExists(path)) { + fso.DeleteFile(path, true); + } + } catch (e) { + IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); + } + }, + createFile: function (path, useUTF8) { + try { + var streamObj = getStreamObject(); + streamObj.Charset = useUTF8 ? 'utf-8' : 'x-ansi'; + streamObj.Open(); + return { + Write: function (str) { + streamObj.WriteText(str, 0); + }, + WriteLine: function (str) { + streamObj.WriteText(str, 1); + }, + Close: function () { + try { + streamObj.SaveToFile(path, 2); + } catch (saveError) { + IOUtils.throwIOError("Couldn't write to file '" + path + "'.", saveError); + }finally { + if(streamObj.State != 0) { + streamObj.Close(); + } + releaseStreamObject(streamObj); + } + } + }; + } catch (creationError) { + IOUtils.throwIOError("Couldn't write to file '" + path + "'.", creationError); + } + }, + directoryExists: function (path) { + return fso.FolderExists(path); + }, + createDirectory: function (path) { + try { + if(!this.directoryExists(path)) { + fso.CreateFolder(path); + } + } catch (e) { + IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e); + } + }, + dir: function (path, spec, options) { + options = options || { + }; + function filesInFolder(folder, root) { + var paths = []; + var fc; + if(options.recursive) { + fc = new Enumerator(folder.subfolders); + for(; !fc.atEnd(); fc.moveNext()) { + paths = paths.concat(filesInFolder(fc.item(), root + "/" + fc.item().Name)); + } + } + fc = new Enumerator(folder.files); + for(; !fc.atEnd(); fc.moveNext()) { + if(!spec || fc.item().Name.match(spec)) { + paths.push(root + "/" + fc.item().Name); + } + } + return paths; + } + var folder = fso.GetFolder(path); + var paths = []; + return filesInFolder(folder, path); + }, + print: function (str) { + WScript.StdOut.Write(str); + }, + printLine: function (str) { + WScript.Echo(str); + }, + arguments: args, + stderr: WScript.StdErr, + stdout: WScript.StdOut, + watchFile: null, + run: function (source, filename) { + try { + eval(source); + } catch (e) { + IOUtils.throwIOError("Error while executing file '" + filename + "'.", e); + } + }, + getExecutingFilePath: function () { + return WScript.ScriptFullName; + }, + quit: function (exitCode) { + if (typeof exitCode === "undefined") { exitCode = 0; } + try { + WScript.Quit(exitCode); + } catch (e) { + } + } + }; + } + ; + function getNodeIO() { + var _fs = require('fs'); + var _path = require('path'); + var _module = require('module'); + return { + readFile: function (file) { + try { + var buffer = _fs.readFileSync(file); + switch(buffer[0]) { + case 254: + if(buffer[1] == 255) { + var i = 0; + while((i + 1) < buffer.length) { + var temp = buffer[i]; + buffer[i] = buffer[i + 1]; + buffer[i + 1] = temp; + i += 2; + } + return buffer.toString("ucs2", 2); + } + break; + case 255: + if(buffer[1] == 254) { + return buffer.toString("ucs2", 2); + } + break; + case 239: + if(buffer[1] == 187) { + return buffer.toString("utf8", 3); + } + } + return buffer.toString(); + } catch (e) { + IOUtils.throwIOError("Error reading file \"" + file + "\".", e); + } + }, + writeFile: _fs.writeFileSync, + deleteFile: function (path) { + try { + _fs.unlinkSync(path); + } catch (e) { + IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); + } + }, + fileExists: function (path) { + return _fs.existsSync(path); + }, + createFile: function (path, useUTF8) { + function mkdirRecursiveSync(path) { + var stats = _fs.statSync(path); + if(stats.isFile()) { + IOUtils.throwIOError("\"" + path + "\" exists but isn't a directory.", null); + } else if(stats.isDirectory()) { + return; + } else { + mkdirRecursiveSync(_path.dirname(path)); + _fs.mkdirSync(path, 775); + } + } + mkdirRecursiveSync(_path.dirname(path)); + try { + var fd = _fs.openSync(path, 'w'); + } catch (e) { + IOUtils.throwIOError("Couldn't write to file '" + path + "'.", e); + } + return { + Write: function (str) { + _fs.writeSync(fd, str); + }, + WriteLine: function (str) { + _fs.writeSync(fd, str + '\r\n'); + }, + Close: function () { + _fs.closeSync(fd); + fd = null; + } + }; + }, + dir: function dir(path, spec, options) { + options = options || { + }; + function filesInFolder(folder) { + var paths = []; + var files = _fs.readdirSync(folder); + for(var i = 0; i < files.length; i++) { + var stat = _fs.statSync(folder + "/" + files[i]); + if(options.recursive && stat.isDirectory()) { + paths = paths.concat(filesInFolder(folder + "/" + files[i])); + } else if(stat.isFile() && (!spec || files[i].match(spec))) { + paths.push(folder + "/" + files[i]); + } + } + return paths; + } + return filesInFolder(path); + }, + createDirectory: function (path) { + try { + if(!this.directoryExists(path)) { + _fs.mkdirSync(path); + } + } catch (e) { + IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e); + } + }, + directoryExists: function (path) { + return _fs.existsSync(path) && _fs.lstatSync(path).isDirectory(); + }, + resolvePath: function (path) { + return _path.resolve(path); + }, + dirName: function (path) { + return _path.dirname(path); + }, + findFile: function (rootPath, partialFilePath) { + var path = rootPath + "/" + partialFilePath; + while(true) { + if(_fs.existsSync(path)) { + try { + var content = this.readFile(path); + return { + content: content, + path: path + }; + } catch (err) { + } + } else { + var parentPath = _path.resolve(rootPath, ".."); + if(rootPath === parentPath) { + return null; + } else { + rootPath = parentPath; + path = _path.resolve(rootPath, partialFilePath); + } + } + } + }, + print: function (str) { + process.stdout.write(str); + }, + printLine: function (str) { + process.stdout.write(str + '\n'); + }, + arguments: process.argv.slice(2), + stderr: { + Write: function (str) { + process.stderr.write(str); + }, + WriteLine: function (str) { + process.stderr.write(str + '\n'); + }, + Close: function () { + } + }, + stdout: { + Write: function (str) { + process.stdout.write(str); + }, + WriteLine: function (str) { + process.stdout.write(str + '\n'); + }, + Close: function () { + } + }, + watchFile: function (filename, callback) { + var firstRun = true; + var processingChange = false; + var fileChanged = function (curr, prev) { + if(!firstRun) { + if(curr.mtime < prev.mtime) { + return; + } + _fs.unwatchFile(filename, fileChanged); + if(!processingChange) { + processingChange = true; + callback(filename); + setTimeout(function () { + processingChange = false; + }, 100); + } + } + firstRun = false; + _fs.watchFile(filename, { + persistent: true, + interval: 500 + }, fileChanged); + }; + fileChanged(); + return { + filename: filename, + close: function () { + _fs.unwatchFile(filename, fileChanged); + } + }; + }, + run: function (source, filename) { + require.main.filename = filename; + require.main.paths = _module._nodeModulePaths(_path.dirname(_fs.realpathSync(filename))); + require.main._compile(source, filename); + }, + getExecutingFilePath: function () { + return process.mainModule.filename; + }, + quit: process.exit + }; + } + ; + if(typeof ActiveXObject === "function") { + return getWindowsScriptHostIO(); + } else if(typeof require === "function") { + return getNodeIO(); + } else { + return null; + } +})(); diff --git a/_infrastructure/tests/src/io.ts b/_infrastructure/tests/src/io.ts new file mode 100644 index 0000000000..641ace09de --- /dev/null +++ b/_infrastructure/tests/src/io.ts @@ -0,0 +1,525 @@ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +interface IResolvedFile { + content: string; + path: string; +} + +interface IFileWatcher { + close(): void; +} + +interface IIO { + readFile(path: string): string; + writeFile(path: string, contents: string): void; + createFile(path: string, useUTF8?: bool): ITextWriter; + deleteFile(path: string): void; + dir(path: string, re?: RegExp, options?: { recursive?: bool; deep?: number; }): string[]; + fileExists(path: string): bool; + directoryExists(path: string): bool; + createDirectory(path: string): void; + resolvePath(path: string): string; + dirName(path: string): string; + findFile(rootPath: string, partialFilePath: string): IResolvedFile; + print(str: string): void; + printLine(str: string): void; + arguments: string[]; + stderr: ITextWriter; + stdout: ITextWriter; + watchFile(filename: string, callback: (string) => void ): IFileWatcher; + run(source: string, filename: string): void; + getExecutingFilePath(): string; + quit(exitCode?: number); +} + +module IOUtils { + // Creates the directory including its parent if not already present + function createDirectoryStructure(ioHost: IIO, dirName: string) { + if (ioHost.directoryExists(dirName)) { + return; + } + + var parentDirectory = ioHost.dirName(dirName); + if (parentDirectory != "") { + createDirectoryStructure(ioHost, parentDirectory); + } + ioHost.createDirectory(dirName); + } + + // Creates a file including its directory structure if not already present + export function createFileAndFolderStructure(ioHost: IIO, fileName: string, useUTF8?: bool) { + var path = ioHost.resolvePath(fileName); + var dirName = ioHost.dirName(path); + createDirectoryStructure(ioHost, dirName); + return ioHost.createFile(path, useUTF8); + } + + export function throwIOError(message: string, error: Error) { + var errorMessage = message; + if (error && error.message) { + errorMessage += (" " + error.message); + } + throw new Error(errorMessage); + } +} + +// Declare dependencies needed for all supported hosts +declare class Enumerator { + public atEnd(): bool; + public moveNext(); + public item(): any; + constructor (o: any); +} +declare function setTimeout(callback: () =>void , ms?: number); +declare var require: any; +declare module process { + export var argv: string[]; + export var platform: string; + export function on(event: string, handler: (any) => void ): void; + export module stdout { + export function write(str: string); + } + export module stderr { + export function write(str: string); + } + export module mainModule { + export var filename: string; + } + export function exit(exitCode?: number); +} + +var IO = (function() { + + // Create an IO object for use inside WindowsScriptHost hosts + // Depends on WSCript and FileSystemObject + function getWindowsScriptHostIO(): IIO { + var fso = new ActiveXObject("Scripting.FileSystemObject"); + var streamObjectPool = []; + + function getStreamObject(): any { + if (streamObjectPool.length > 0) { + return streamObjectPool.pop(); + } else { + return new ActiveXObject("ADODB.Stream"); + } + } + + function releaseStreamObject(obj: any) { + streamObjectPool.push(obj); + } + + var args = []; + for (var i = 0; i < WScript.Arguments.length; i++) { + args[i] = WScript.Arguments.Item(i); + } + + return { + readFile: function(path) { + try { + var streamObj = getStreamObject(); + streamObj.Open(); + streamObj.Type = 2; // Text data + streamObj.Charset = 'x-ansi'; // Assume we are reading ansi text + streamObj.LoadFromFile(path); + var bomChar = streamObj.ReadText(2); // Read the BOM char + streamObj.Position = 0; // Position has to be at 0 before changing the encoding + if ((bomChar.charCodeAt(0) == 0xFE && bomChar.charCodeAt(1) == 0xFF) + || (bomChar.charCodeAt(0) == 0xFF && bomChar.charCodeAt(1) == 0xFE)) { + streamObj.Charset = 'unicode'; + } else if (bomChar.charCodeAt(0) == 0xEF && bomChar.charCodeAt(1) == 0xBB) { + streamObj.Charset = 'utf-8'; + } + + // Read the whole file + var str = streamObj.ReadText(-1 /* read from the current position to EOS */); + streamObj.Close(); + releaseStreamObject(streamObj); + return str; + } + catch (err) { + IOUtils.throwIOError("Error reading file \"" + path + "\".", err); + } + }, + + writeFile: function(path, contents) { + var file = this.createFile(path); + file.Write(contents); + file.Close(); + }, + + fileExists: function(path: string): bool { + return fso.FileExists(path); + }, + + resolvePath: function(path: string): string { + return fso.GetAbsolutePathName(path); + }, + + dirName: function(path: string): string { + return fso.GetParentFolderName(path); + }, + + findFile: function(rootPath: string, partialFilePath: string): IResolvedFile { + var path = fso.GetAbsolutePathName(rootPath) + "/" + partialFilePath; + + while (true) { + if (fso.FileExists(path)) { + try { + var content = this.readFile(path); + return { content: content, path: path }; + } + catch (err) { + //Tools.CompilerDiagnostics.debugPrint("Could not find " + path + ", trying parent"); + } + } + else { + rootPath = fso.GetParentFolderName(fso.GetAbsolutePathName(rootPath)); + + if (rootPath == "") { + return null; + } + else { + path = fso.BuildPath(rootPath, partialFilePath); + } + } + } + }, + + deleteFile: function(path: string): void { + try { + if (fso.FileExists(path)) { + fso.DeleteFile(path, true); // true: delete read-only files + } + } catch (e) { + IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); + } + }, + + createFile: function (path, useUTF8?) { + try { + var streamObj = getStreamObject(); + streamObj.Charset = useUTF8 ? 'utf-8' : 'x-ansi'; + streamObj.Open(); + return { + Write: function (str) { streamObj.WriteText(str, 0); }, + WriteLine: function (str) { streamObj.WriteText(str, 1); }, + Close: function() { + try { + streamObj.SaveToFile(path, 2); + } catch (saveError) { + IOUtils.throwIOError("Couldn't write to file '" + path + "'.", saveError); + } + finally { + if (streamObj.State != 0 /*adStateClosed*/) { + streamObj.Close(); + } + releaseStreamObject(streamObj); + } + } + }; + } catch (creationError) { + IOUtils.throwIOError("Couldn't write to file '" + path + "'.", creationError); + } + }, + + directoryExists: function(path) { + return fso.FolderExists(path); + }, + + createDirectory: function(path) { + try { + if (!this.directoryExists(path)) { + fso.CreateFolder(path); + } + } catch (e) { + IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e); + } + }, + + dir: function(path, spec?, options?) { + options = options || <{ recursive?: bool; deep?: number; }>{}; + function filesInFolder(folder, root): string[]{ + var paths = []; + var fc: Enumerator; + + if (options.recursive) { + fc = new Enumerator(folder.subfolders); + + for (; !fc.atEnd() ; fc.moveNext()) { + paths = paths.concat(filesInFolder(fc.item(), root + "/" + fc.item().Name)); + } + } + + fc = new Enumerator(folder.files); + + for (; !fc.atEnd() ; fc.moveNext()) { + if (!spec || fc.item().Name.match(spec)) { + paths.push(root + "/" + fc.item().Name); + } + } + + return paths; + } + + var folder = fso.GetFolder(path); + var paths = []; + + return filesInFolder(folder, path); + }, + + print: function(str) { + WScript.StdOut.Write(str); + }, + + printLine: function(str) { + WScript.Echo(str); + }, + + arguments: args, + stderr: WScript.StdErr, + stdout: WScript.StdOut, + watchFile: null, + run: function(source, filename) { + try { + eval(source); + } catch (e) { + IOUtils.throwIOError("Error while executing file '" + filename + "'.", e); + } + }, + getExecutingFilePath: function () { + return WScript.ScriptFullName; + }, + quit: function (exitCode? : number = 0) { + try { + WScript.Quit(exitCode); + } catch (e) { + } + } + } + + }; + + // Create an IO object for use inside Node.js hosts + // Depends on 'fs' and 'path' modules + function getNodeIO(): IIO { + + var _fs = require('fs'); + var _path = require('path'); + var _module = require('module'); + + return { + readFile: function(file) { + try { + var buffer = _fs.readFileSync(file); + switch (buffer[0]) { + case 0xFE: + if (buffer[1] == 0xFF) { + // utf16-be. Reading the buffer as big endian is not supported, so convert it to + // Little Endian first + var i = 0; + while ((i + 1) < buffer.length) { + var temp = buffer[i] + buffer[i] = buffer[i + 1]; + buffer[i + 1] = temp; + i += 2; + } + return buffer.toString("ucs2", 2); + } + break; + case 0xFF: + if (buffer[1] == 0xFE) { + // utf16-le + return buffer.toString("ucs2", 2); + } + break; + case 0xEF: + if (buffer[1] == 0xBB) { + // utf-8 + return buffer.toString("utf8", 3); + } + } + // Default behaviour + return buffer.toString(); + } catch (e) { + IOUtils.throwIOError("Error reading file \"" + file + "\".", e); + } + }, + writeFile: <(path: string, contents: string) => void >_fs.writeFileSync, + deleteFile: function(path) { + try { + _fs.unlinkSync(path); + } catch (e) { + IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); + } + }, + fileExists: function(path): bool { + return _fs.existsSync(path); + }, + createFile: function(path, useUTF8?) { + function mkdirRecursiveSync(path) { + var stats = _fs.statSync(path); + if (stats.isFile()) { + IOUtils.throwIOError("\"" + path + "\" exists but isn't a directory.", null); + } else if (stats.isDirectory()) { + return; + } else { + mkdirRecursiveSync(_path.dirname(path)); + _fs.mkdirSync(path, 0775); + } + } + + mkdirRecursiveSync(_path.dirname(path)); + + try { + var fd = _fs.openSync(path, 'w'); + } catch (e) { + IOUtils.throwIOError("Couldn't write to file '" + path + "'.", e); + } + return { + Write: function(str) { _fs.writeSync(fd, str); }, + WriteLine: function(str) { _fs.writeSync(fd, str + '\r\n'); }, + Close: function() { _fs.closeSync(fd); fd = null; } + }; + }, + dir: function dir(path, spec?, options?) { + options = options || <{ recursive?: bool; deep?: number; }>{}; + + function filesInFolder(folder: string, deep?: number): string[]{ + var paths = []; + + var files = _fs.readdirSync(folder); + for (var i = 0; i < files.length; i++) { + var stat = _fs.statSync(folder + "/" + files[i]); + if (options.recursive && stat.isDirectory()) { + if (deep < (options.deep || 100)) { + paths = paths.concat(filesInFolder(folder + "/" + files[i], 1)); + } + } else if (stat.isFile() && (!spec || files[i].match(spec))) { + paths.push(folder + "/" + files[i]); + } + } + + return paths; + } + + return filesInFolder(path, 0); + }, + createDirectory: function(path: string): void { + try { + if (!this.directoryExists(path)) { + _fs.mkdirSync(path); + } + } catch (e) { + IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e); + } + }, + + directoryExists: function(path: string): bool { + return _fs.existsSync(path) && _fs.lstatSync(path).isDirectory(); + }, + resolvePath: function(path: string): string { + return _path.resolve(path); + }, + dirName: function(path: string): string { + return _path.dirname(path); + }, + findFile: function(rootPath: string, partialFilePath): IResolvedFile { + var path = rootPath + "/" + partialFilePath; + + while (true) { + if (_fs.existsSync(path)) { + try { + var content = this.readFile(path); + return { content: content, path: path }; + } catch (err) { + //Tools.CompilerDiagnostics.debugPrint(("Could not find " + path) + ", trying parent"); + } + } + else { + var parentPath = _path.resolve(rootPath, ".."); + + // Node will just continue to repeat the root path, rather than return null + if (rootPath === parentPath) { + return null; + } + else { + rootPath = parentPath; + path = _path.resolve(rootPath, partialFilePath); + } + } + } + }, + print: function(str) { process.stdout.write(str) }, + printLine: function(str) { process.stdout.write(str + '\n') }, + arguments: process.argv.slice(2), + stderr: { + Write: function(str) { process.stderr.write(str); }, + WriteLine: function(str) { process.stderr.write(str + '\n'); }, + Close: function() { } + }, + stdout: { + Write: function(str) { process.stdout.write(str); }, + WriteLine: function(str) { process.stdout.write(str + '\n'); }, + Close: function() { } + }, + watchFile: function(filename: string, callback: (string) => void ): IFileWatcher { + var firstRun = true; + var processingChange = false; + + var fileChanged: any = function(curr, prev) { + if (!firstRun) { + if (curr.mtime < prev.mtime) { + return; + } + + _fs.unwatchFile(filename, fileChanged); + if (!processingChange) { + processingChange = true; + callback(filename); + setTimeout(function() { processingChange = false; }, 100); + } + } + firstRun = false; + _fs.watchFile(filename, { persistent: true, interval: 500 }, fileChanged); + }; + + fileChanged(); + return { + filename: filename, + close: function() { + _fs.unwatchFile(filename, fileChanged); + } + }; + }, + run: function(source, filename) { + require.main.filename = filename; + require.main.paths = _module._nodeModulePaths(_path.dirname(_fs.realpathSync(filename))); + require.main._compile(source, filename); + }, + getExecutingFilePath: function () { + return process.mainModule.filename; + }, + quit: process.exit + } + }; + + if (typeof ActiveXObject === "function") + return getWindowsScriptHostIO(); + else if (typeof require === "function") + return getNodeIO(); + else + return null; // Unsupported host +})(); diff --git a/_infrastructure/tests/testRunner.js b/_infrastructure/tests/testRunner.js new file mode 100644 index 0000000000..14040f24b7 --- /dev/null +++ b/_infrastructure/tests/testRunner.js @@ -0,0 +1,619 @@ +var ExecResult = (function () { + function ExecResult() { + this.stdout = ""; + this.stderr = ""; + } + return ExecResult; +})(); +var WindowsScriptHostExec = (function () { + function WindowsScriptHostExec() { } + WindowsScriptHostExec.prototype.exec = function (filename, cmdLineArgs, handleResult) { + var result = new ExecResult(); + var shell = new ActiveXObject('WScript.Shell'); + try { + var process = shell.Exec(filename + ' ' + cmdLineArgs.join(' ')); + } catch (e) { + result.stderr = e.message; + result.exitCode = 1; + handleResult(result); + return; + } + while(process.Status != 0) { + } + result.exitCode = process.ExitCode; + if(!process.StdOut.AtEndOfStream) { + result.stdout = process.StdOut.ReadAll(); + } + if(!process.StdErr.AtEndOfStream) { + result.stderr = process.StdErr.ReadAll(); + } + handleResult(result); + }; + return WindowsScriptHostExec; +})(); +var NodeExec = (function () { + function NodeExec() { } + NodeExec.prototype.exec = function (filename, cmdLineArgs, handleResult) { + var nodeExec = require('child_process').exec; + var result = new ExecResult(); + result.exitCode = null; + var cmdLine = filename + ' ' + cmdLineArgs.join(' '); + var process = nodeExec(cmdLine, function (error, stdout, stderr) { + result.stdout = stdout; + result.stderr = stderr; + result.exitCode = error ? error.code : 0; + handleResult(result); + }); + }; + return NodeExec; +})(); +var Exec = (function () { + var global = Function("return this;").call(null); + if(typeof global.ActiveXObject !== "undefined") { + return new WindowsScriptHostExec(); + } else { + return new NodeExec(); + } +})(); +var IOUtils; +(function (IOUtils) { + function createDirectoryStructure(ioHost, dirName) { + if(ioHost.directoryExists(dirName)) { + return; + } + var parentDirectory = ioHost.dirName(dirName); + if(parentDirectory != "") { + createDirectoryStructure(ioHost, parentDirectory); + } + ioHost.createDirectory(dirName); + } + function createFileAndFolderStructure(ioHost, fileName, useUTF8) { + var path = ioHost.resolvePath(fileName); + var dirName = ioHost.dirName(path); + createDirectoryStructure(ioHost, dirName); + return ioHost.createFile(path, useUTF8); + } + IOUtils.createFileAndFolderStructure = createFileAndFolderStructure; + function throwIOError(message, error) { + var errorMessage = message; + if(error && error.message) { + errorMessage += (" " + error.message); + } + throw new Error(errorMessage); + } + IOUtils.throwIOError = throwIOError; +})(IOUtils || (IOUtils = {})); + +var IO = (function () { + function getWindowsScriptHostIO() { + var fso = new ActiveXObject("Scripting.FileSystemObject"); + var streamObjectPool = []; + function getStreamObject() { + if(streamObjectPool.length > 0) { + return streamObjectPool.pop(); + } else { + return new ActiveXObject("ADODB.Stream"); + } + } + function releaseStreamObject(obj) { + streamObjectPool.push(obj); + } + var args = []; + for(var i = 0; i < WScript.Arguments.length; i++) { + args[i] = WScript.Arguments.Item(i); + } + return { + readFile: function (path) { + try { + var streamObj = getStreamObject(); + streamObj.Open(); + streamObj.Type = 2; + streamObj.Charset = 'x-ansi'; + streamObj.LoadFromFile(path); + var bomChar = streamObj.ReadText(2); + streamObj.Position = 0; + if((bomChar.charCodeAt(0) == 254 && bomChar.charCodeAt(1) == 255) || (bomChar.charCodeAt(0) == 255 && bomChar.charCodeAt(1) == 254)) { + streamObj.Charset = 'unicode'; + } else if(bomChar.charCodeAt(0) == 239 && bomChar.charCodeAt(1) == 187) { + streamObj.Charset = 'utf-8'; + } + var str = streamObj.ReadText(-1); + streamObj.Close(); + releaseStreamObject(streamObj); + return str; + } catch (err) { + IOUtils.throwIOError("Error reading file \"" + path + "\".", err); + } + }, + writeFile: function (path, contents) { + var file = this.createFile(path); + file.Write(contents); + file.Close(); + }, + fileExists: function (path) { + return fso.FileExists(path); + }, + resolvePath: function (path) { + return fso.GetAbsolutePathName(path); + }, + dirName: function (path) { + return fso.GetParentFolderName(path); + }, + findFile: function (rootPath, partialFilePath) { + var path = fso.GetAbsolutePathName(rootPath) + "/" + partialFilePath; + while(true) { + if(fso.FileExists(path)) { + try { + var content = this.readFile(path); + return { + content: content, + path: path + }; + } catch (err) { + } + } else { + rootPath = fso.GetParentFolderName(fso.GetAbsolutePathName(rootPath)); + if(rootPath == "") { + return null; + } else { + path = fso.BuildPath(rootPath, partialFilePath); + } + } + } + }, + deleteFile: function (path) { + try { + if(fso.FileExists(path)) { + fso.DeleteFile(path, true); + } + } catch (e) { + IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); + } + }, + createFile: function (path, useUTF8) { + try { + var streamObj = getStreamObject(); + streamObj.Charset = useUTF8 ? 'utf-8' : 'x-ansi'; + streamObj.Open(); + return { + Write: function (str) { + streamObj.WriteText(str, 0); + }, + WriteLine: function (str) { + streamObj.WriteText(str, 1); + }, + Close: function () { + try { + streamObj.SaveToFile(path, 2); + } catch (saveError) { + IOUtils.throwIOError("Couldn't write to file '" + path + "'.", saveError); + }finally { + if(streamObj.State != 0) { + streamObj.Close(); + } + releaseStreamObject(streamObj); + } + } + }; + } catch (creationError) { + IOUtils.throwIOError("Couldn't write to file '" + path + "'.", creationError); + } + }, + directoryExists: function (path) { + return fso.FolderExists(path); + }, + createDirectory: function (path) { + try { + if(!this.directoryExists(path)) { + fso.CreateFolder(path); + } + } catch (e) { + IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e); + } + }, + dir: function (path, spec, options) { + options = options || { + }; + function filesInFolder(folder, root) { + var paths = []; + var fc; + if(options.recursive) { + fc = new Enumerator(folder.subfolders); + for(; !fc.atEnd(); fc.moveNext()) { + paths = paths.concat(filesInFolder(fc.item(), root + "/" + fc.item().Name)); + } + } + fc = new Enumerator(folder.files); + for(; !fc.atEnd(); fc.moveNext()) { + if(!spec || fc.item().Name.match(spec)) { + paths.push(root + "/" + fc.item().Name); + } + } + return paths; + } + var folder = fso.GetFolder(path); + var paths = []; + return filesInFolder(folder, path); + }, + print: function (str) { + WScript.StdOut.Write(str); + }, + printLine: function (str) { + WScript.Echo(str); + }, + arguments: args, + stderr: WScript.StdErr, + stdout: WScript.StdOut, + watchFile: null, + run: function (source, filename) { + try { + eval(source); + } catch (e) { + IOUtils.throwIOError("Error while executing file '" + filename + "'.", e); + } + }, + getExecutingFilePath: function () { + return WScript.ScriptFullName; + }, + quit: function (exitCode) { + if (typeof exitCode === "undefined") { exitCode = 0; } + try { + WScript.Quit(exitCode); + } catch (e) { + } + } + }; + } + ; + function getNodeIO() { + var _fs = require('fs'); + var _path = require('path'); + var _module = require('module'); + return { + readFile: function (file) { + try { + var buffer = _fs.readFileSync(file); + switch(buffer[0]) { + case 254: + if(buffer[1] == 255) { + var i = 0; + while((i + 1) < buffer.length) { + var temp = buffer[i]; + buffer[i] = buffer[i + 1]; + buffer[i + 1] = temp; + i += 2; + } + return buffer.toString("ucs2", 2); + } + break; + case 255: + if(buffer[1] == 254) { + return buffer.toString("ucs2", 2); + } + break; + case 239: + if(buffer[1] == 187) { + return buffer.toString("utf8", 3); + } + } + return buffer.toString(); + } catch (e) { + IOUtils.throwIOError("Error reading file \"" + file + "\".", e); + } + }, + writeFile: _fs.writeFileSync, + deleteFile: function (path) { + try { + _fs.unlinkSync(path); + } catch (e) { + IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); + } + }, + fileExists: function (path) { + return _fs.existsSync(path); + }, + createFile: function (path, useUTF8) { + function mkdirRecursiveSync(path) { + var stats = _fs.statSync(path); + if(stats.isFile()) { + IOUtils.throwIOError("\"" + path + "\" exists but isn't a directory.", null); + } else if(stats.isDirectory()) { + return; + } else { + mkdirRecursiveSync(_path.dirname(path)); + _fs.mkdirSync(path, 775); + } + } + mkdirRecursiveSync(_path.dirname(path)); + try { + var fd = _fs.openSync(path, 'w'); + } catch (e) { + IOUtils.throwIOError("Couldn't write to file '" + path + "'.", e); + } + return { + Write: function (str) { + _fs.writeSync(fd, str); + }, + WriteLine: function (str) { + _fs.writeSync(fd, str + '\r\n'); + }, + Close: function () { + _fs.closeSync(fd); + fd = null; + } + }; + }, + dir: function dir(path, spec, options) { + options = options || { + }; + function filesInFolder(folder, deep) { + var paths = []; + var files = _fs.readdirSync(folder); + for(var i = 0; i < files.length; i++) { + var stat = _fs.statSync(folder + "/" + files[i]); + if(options.recursive && stat.isDirectory()) { + if(deep < (options.deep || 100)) { + paths = paths.concat(filesInFolder(folder + "/" + files[i], 1)); + } + } else if(stat.isFile() && (!spec || files[i].match(spec))) { + paths.push(folder + "/" + files[i]); + } + } + return paths; + } + return filesInFolder(path, 0); + }, + createDirectory: function (path) { + try { + if(!this.directoryExists(path)) { + _fs.mkdirSync(path); + } + } catch (e) { + IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e); + } + }, + directoryExists: function (path) { + return _fs.existsSync(path) && _fs.lstatSync(path).isDirectory(); + }, + resolvePath: function (path) { + return _path.resolve(path); + }, + dirName: function (path) { + return _path.dirname(path); + }, + findFile: function (rootPath, partialFilePath) { + var path = rootPath + "/" + partialFilePath; + while(true) { + if(_fs.existsSync(path)) { + try { + var content = this.readFile(path); + return { + content: content, + path: path + }; + } catch (err) { + } + } else { + var parentPath = _path.resolve(rootPath, ".."); + if(rootPath === parentPath) { + return null; + } else { + rootPath = parentPath; + path = _path.resolve(rootPath, partialFilePath); + } + } + } + }, + print: function (str) { + process.stdout.write(str); + }, + printLine: function (str) { + process.stdout.write(str + '\n'); + }, + arguments: process.argv.slice(2), + stderr: { + Write: function (str) { + process.stderr.write(str); + }, + WriteLine: function (str) { + process.stderr.write(str + '\n'); + }, + Close: function () { + } + }, + stdout: { + Write: function (str) { + process.stdout.write(str); + }, + WriteLine: function (str) { + process.stdout.write(str + '\n'); + }, + Close: function () { + } + }, + watchFile: function (filename, callback) { + var firstRun = true; + var processingChange = false; + var fileChanged = function (curr, prev) { + if(!firstRun) { + if(curr.mtime < prev.mtime) { + return; + } + _fs.unwatchFile(filename, fileChanged); + if(!processingChange) { + processingChange = true; + callback(filename); + setTimeout(function () { + processingChange = false; + }, 100); + } + } + firstRun = false; + _fs.watchFile(filename, { + persistent: true, + interval: 500 + }, fileChanged); + }; + fileChanged(); + return { + filename: filename, + close: function () { + _fs.unwatchFile(filename, fileChanged); + } + }; + }, + run: function (source, filename) { + require.main.filename = filename; + require.main.paths = _module._nodeModulePaths(_path.dirname(_fs.realpathSync(filename))); + require.main._compile(source, filename); + }, + getExecutingFilePath: function () { + return process.mainModule.filename; + }, + quit: process.exit + }; + } + ; + if(typeof ActiveXObject === "function") { + return getWindowsScriptHostIO(); + } else if(typeof require === "function") { + return getNodeIO(); + } else { + return null; + } +})(); +var cfg = { + root: '.', + pattern: /.\-tests\.ts/g, + tsc: 'node ./_infrastructure/tests/typescript_0.8.3/tsc.js ', + exclude: { + '.git': true, + '.gitignore': true, + 'package.json': true, + '_infrastructure': true, + '.travis.yml': true, + 'LICENSE': true, + 'README.md': true, + '_ReSharper.DefinitelyTyped': true, + 'obj': true, + 'bin': true, + 'Properties': true, + 'DefinitelyTyped.csproj': true, + 'DefinitelyTyped.csproj.user': true, + 'DefinitelyTyped.sln': true, + 'DefinitelyTyped.v11.suo': true + } +}; +if(process.argv.length > 2) { + cfg.root = process.argv[2]; +} +var TestFile = (function () { + function TestFile() { + this.errors = []; + } + return TestFile; +})(); +var Test = (function () { + function Test(lib) { + this.lib = lib; + this.files = []; + } + return Test; +})(); +var Tests = (function () { + function Tests() { + this.tests = []; + } + return Tests; +})(); +function getLibDirectory(file) { + return file.substr(cfg.root.length).split('/')[1]; +} +function getErrorList(out) { + var splitContentByNewlines = function (content) { + var lines = content.split('\r\n'); + if(lines.length === 1) { + lines = content.split('\n'); + } + return lines; + }; + var result = []; + var lines = splitContentByNewlines(out); + for(var i = 0; i < lines.length; i++) { + if(lines[i]) { + result.push(lines[i]); + } + } + return result; +} +function runTests(testFiles) { + var tests = new Tests(); + Exec.exec(cfg.tsc, [ + testFiles[testIndex] + ], function (ExecResult) { + var lib = getLibDirectory(testFiles[testIndex]); + cache_visited_libs[lib] = true; + var testFile = new TestFile(); + testFile.name = testFiles[testIndex]; + testFile.errors = getErrorList(ExecResult.stderr); + if(testFile.errors.length == 0) { + total_success++; + } else { + total_failure++; + } + console.log(' [\033[36m' + lib + '\033[0m] ' + testFiles[testIndex].substr(cfg.root.length) + ' - ' + (testFile.errors.length == 0 ? '\033[32msuccess\033[0m' : '\033[31mfailure\033[0m')); + var test = new Test(lib); + test.files.push(testFile); + tests.tests.push(test); + testIndex++; + if(testIndex < totalTest) { + Exec.exec(cfg.tsc, [ + testFiles[testIndex] + ], arguments.callee); + } else { + var withoutTests = { + }; + for(var k = 0; k < allFiles.length; k++) { + var rootFolder = allFiles[k].substr(cfg.root.length).split('/')[1]; + if(!(rootFolder in cfg.exclude)) { + if(!(rootFolder in cache_visited_libs)) { + withoutTests[rootFolder] = true; + } + } + } + var withoutTestsCount = 0; + for(var attr in withoutTests) { + var test = new Test(attr); + tests.tests.push(test); + console.log(' [\033[36m' + attr + '\033[0m] without tests'); + withoutTestsCount++; + } + console.log('\n> ' + (total_failure + total_success + withoutTestsCount) + ' tests. ' + '\033[32m' + total_success + ' tests success\033[0m, ' + '\033[31m' + total_failure + ' tests failed\033[0m and ' + withoutTestsCount + ' definitions without tests.\n'); + if(total_failure > 0) { + process.exit(1); + } + } + }); +} +var testFiles = IO.dir(cfg.root, cfg.pattern, { + recursive: true, + deep: 1 +}); +var allFiles = IO.dir(cfg.root, null, { + recursive: true +}); +var totalTest = testFiles.length; +var testIndex = 0; +var cache_visited_libs = { +}; +var total_failure = 0; +var total_success = 0; +var tscVersion = '?.?.?'; +Exec.exec(cfg.tsc, [ + '-version' +], function (ExecResult) { + tscVersion = ExecResult.stdout; + console.log('$ tsc -version'); + console.log(tscVersion); + runTests(testFiles); +}); diff --git a/_infrastructure/tests/testRunner.ts b/_infrastructure/tests/testRunner.ts new file mode 100644 index 0000000000..0fd9198d5d --- /dev/null +++ b/_infrastructure/tests/testRunner.ts @@ -0,0 +1,168 @@ +/// +/// + +var cfg = { + root: '.', + pattern: /.\-tests\.ts/g, + tsc: 'node ./_infrastructure/tests/typescript_0.8.3/tsc.js ', + exclude: { + '.git': true, + '.gitignore': true, + 'package.json': true, + '_infrastructure': true, + '.travis.yml': true, + 'LICENSE': true, + 'README.md': true, + '_ReSharper.DefinitelyTyped': true, + 'obj': true, + 'bin': true, + 'Properties': true, + 'DefinitelyTyped.csproj': true, + 'DefinitelyTyped.csproj.user': true, + 'DefinitelyTyped.sln': true, + 'DefinitelyTyped.v11.suo': true + } +}; + +if (process.argv.length > 2) { + cfg.root = process.argv[2]; +} + +class TestFile { + public name: string; + public errors: string[] = []; +} + +class Test { + public files: TestFile[] = []; + constructor(public lib: string) { } +} + +class Tests { + public tests: Test[] = []; +} + +function getLibDirectory(file: string) { + return file.substr(cfg.root.length).split('/')[1]; +} + +function getErrorList(out): string[] { + var splitContentByNewlines = function (content: string) { + var lines = content.split('\r\n'); + if (lines.length === 1) { + lines = content.split('\n'); + } + return lines; + } + + var result: string[] = []; + + var lines = splitContentByNewlines(out); + + for (var i = 0; i < lines.length; i++) { + if (lines[i]) { + result.push(lines[i]); + } + } + + return result; +} + +function runTests(testFiles) { + var tests = new Tests(); + + Exec.exec( + cfg.tsc, + [testFiles[testIndex]], + (ExecResult) => { + var lib = getLibDirectory(testFiles[testIndex]); + + cache_visited_libs[lib] = true; + + var testFile = new TestFile(); + testFile.name = testFiles[testIndex]; + testFile.errors = getErrorList(ExecResult.stderr); + + if (testFile.errors.length == 0) { + total_success++; + } else { + total_failure++; + } + + console.log(' [\033[36m' + lib + '\033[0m] ' + testFiles[testIndex].substr(cfg.root.length) + + ' - ' + (testFile.errors.length == 0 ? '\033[32msuccess\033[0m' : '\033[31mfailure\033[0m')); + + var test = new Test(lib); + test.files.push(testFile); + tests.tests.push(test); + + testIndex++; + if (testIndex < totalTest) { + Exec.exec( + cfg.tsc, + [testFiles[testIndex]], + <(ExecResult) => any>arguments.callee); + } else { + var withoutTests = {}; + for (var k = 0; k < allFiles.length; k++) { + var rootFolder = allFiles[k].substr(cfg.root.length).split('/')[1]; + if (!(rootFolder in cfg.exclude)) { + if (!(rootFolder in cache_visited_libs)) { + withoutTests[rootFolder] = true; + } + } + } + + var withoutTestsCount = 0; + for (var attr in withoutTests) { + + var test = new Test(attr); + tests.tests.push(test); + + console.log(' [\033[36m' + attr + '\033[0m] without tests'); + withoutTestsCount++; + } + + console.log('\n> ' + (total_failure + total_success + withoutTestsCount) + + ' tests. ' + + '\033[32m' + total_success + ' tests success\033[0m, ' + + '\033[31m' + total_failure + ' tests failed\033[0m and ' + + withoutTestsCount + ' definitions without tests.\n'); + + if (total_failure > 0) { + process.exit(1); + } + } + }); +} + +////// GLOBAL VARS + +// get all files: "*-tests.ts" +var testFiles = IO.dir(cfg.root, cfg.pattern, { recursive: true, deep: 1 }); + +// get all proect files +var allFiles = IO.dir(cfg.root, null, { recursive: true }); + +var totalTest = testFiles.length; +var testIndex = 0; +var cache_visited_libs = {}; + +// total +var total_failure = 0; +var total_success = 0; + +// var to have current typescript version +var tscVersion = '?.?.?'; + +////// END GLOBAL VARS + +// entry point +Exec.exec(cfg.tsc, ['-version'], (ExecResult) => { + tscVersion = ExecResult.stdout; + + console.log('$ tsc -version'); + console.log(tscVersion); + + runTests(testFiles); +}); \ No newline at end of file diff --git a/_infrastructure/tests/typescript_0.8.2/lib.d.ts b/_infrastructure/tests/typescript_0.8.2/lib.d.ts new file mode 100644 index 0000000000..528c2439f4 --- /dev/null +++ b/_infrastructure/tests/typescript_0.8.2/lib.d.ts @@ -0,0 +1,8236 @@ +/* ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + +/// + +//////////////// +/// ECMAScript APIs +//////////////// + +declare var NaN: number; +declare var Infinity: number; + +/** + * Evaluates JavaScript code and executes it. + * @param x A String value that contains valid JavaScript code. + */ +declare function eval(x: string): any; + +/** + * Converts A string to an integer. + * @param s A string to convert into a number. + * @param radix A value between 2 and 36 that specifies the base of the number in numString. + * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. + * All other strings are considered decimal. + */ +declare function parseInt(s: string, radix?: number): number; + +/** + * Converts a string to a floating-point number. + * @param string A string that contains a floating-point number. + */ +declare function parseFloat(string: string): number; + +/** + * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number). + * @param number A numeric value. + */ +declare function isNaN(number: number): bool; + +/** + * Determines whether a supplied number is finite. + * @param number Any numeric value. + */ +declare function isFinite(number: number): bool; + +/** + * Gets the unencoded version of an encoded Uniform Resource Identifier (URI). + * @param encodedURI A value representing an encoded URI. + */ +declare function decodeURI(encodedURI: string): string; + +/** + * Gets the unencoded version of an encoded component of a Uniform Resource Identifier (URI). + * @param encodedURIComponent A value representing an encoded URI component. + */ +declare function decodeURIComponent(encodedURIComponent: string): string; + +/** + * Encodes a text string as a valid Uniform Resource Identifier (URI) + * @param uri A value representing an encoded URI. + */ +declare function encodeURI(uri: string): string; + +/** + * Encodes a text string as a valid component of a Uniform Resource Identifier (URI). + * @param uriComponent A value representing an encoded URI component. + */ +declare function encodeURIComponent(uriComponent: string): string; + +interface PropertyDescriptor { + configurable?: bool; + enumerable?: bool; + value?: any; + writable?: bool; + get?(): any; + set?(v: any): void; +} + +interface PropertyDescriptorMap { + [s: string]: PropertyDescriptor; +} + +interface Object { + /** Returns a string representation of an object. */ + toString(): string; + + /** Returns a date converted to a string using the current locale. */ + toLocaleString(): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): Object; + + /** + * Determines whether an object has a property with the specified name. + * @param v A property name. + */ + hasOwnProperty(v: string): bool; + + /** + * Determines whether an object exists in another object's prototype chain. + * @param v Another object whose prototype chain is to be checked. + */ + isPrototypeOf(v: Object): bool; + + /** + * Determines whether a specified property is enumerable. + * @param v A property name. + */ + propertyIsEnumerable(v: string): bool; + + [s: string]: any; +} + +/** + * Provides functionality common to all JavaScript objects. + */ +declare var Object: { + new (value?: any): Object; + (): any; + (value: any): any; + + /** A reference to the prototype for a class of objects. */ + prototype: Object; + + /** + * Returns the prototype of an object. + * @param o The object that references the prototype. + */ + getPrototypeOf(o: any): any; + + /** + * Gets the own property descriptor of the specified object. + * An own property descriptor is one that is defined directly on the object and is not inherited from the object's prototype. + * @param o Object that contains the property. + * @param p Name of the property. + */ + getOwnPropertyDescriptor(o: any, p: string): PropertyDescriptor; + + /** + * Returns the names of the own properties of an object. The own properties of an object are those that are defined directly + * on that object, and are not inherited from the object's prototype. The properties of an object include both fields (objects) and functions. + * @param o Object that contains the own properties. + */ + getOwnPropertyNames(o: any): string[]; + + /** + * Creates an object that has the specified prototype, and that optionally contains specified properties. + * @param o Object to use as a prototype. May be null + * @param properties JavaScript object that contains one or more property descriptors. + */ + create(o: any, properties?: PropertyDescriptorMap): any; + + /** + * Adds a property to an object, or modifies attributes of an existing property. + * @param o Object on which to add or modify the property. This can be a native JavaScript object (that is, a user-defined object or a built in object) or a DOM object. + * @param p The property name. + * @param attributes Descriptor for the property. It can be for a data property or an accessor property. + */ + defineProperty(o: any, p: string, attributes: PropertyDescriptor): any; + + /** + * Adds one or more properties to an object, and/or modifies attributes of existing properties. + * @param o Object on which to add or modify the properties. This can be a native JavaScript object or a DOM object. + * @param properties JavaScript object that contains one or more descriptor objects. Each descriptor object describes a data property or an accessor property. + */ + defineProperties(o: any, properties: PropertyDescriptorMap): any; + + /** + * Prevents the modification of attributes of existing properties, and prevents the addition of new properties. + * @param o Object on which to lock the attributes. + */ + seal(o: any): any; + + /** + * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. + * @param o Object on which to lock the attributes. + */ + freeze(o: any): any; + + /** + * Prevents the addition of new properties to an object. + * @param o Object to make non-extensible. + */ + preventExtensions(o: any): any; + + /** + * Returns true if existing property attributes cannot be modified in an object and new properties cannot be added to the object. + * @param o Object to test. + */ + isSealed(o: any): bool; + + /** + * Returns true if existing property attributes and values cannot be modified in an object, and new properties cannot be added to the object. + * @param o Object to test. + */ + isFrozen(o: any): bool; + + /** + * Returns a value that indicates whether new properties can be added to an object. + * @param o Object to test. + */ + isExtensible(o: any): bool; + + /** + * Returns the names of the enumerable properties and methods of an object. + * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. + */ + keys(o: any): string[]; +} + +/** + * Creates a new function. + */ +interface Function { + /** + * Calls the function, substituting the specified object for the this value of the function, and the specified array for the arguments of the function. + * @param thisArg The object to be used as the this object. + * @param argArray A set of arguments to be passed to the function. + */ + apply(thisArg: any, ...argArray: any[]): any; + + /** + * Calls a method of an object, substituting another object for the current object. + * @param thisArg The object to be used as the current object. + * @param argArray A list of arguments to be passed to the method. + */ + call(thisArg: any, ...argArray: any[]): any; + + /** + * For a given function, creates a bound function that has the same body as the original function. + * The this object of the bound function is associated with the specified object, and has the specified initial parameters. + * @param thisArg An object to which the this keyword can refer inside the new function. + * @param argArray A list of arguments to be passed to the new function. + */ + bind(thisArg: any, ...argArray: any[]): any; + + prototype: any; + length: number; +} + +declare var Function: { + /** + * Creates a new function. + * @param args A list of arguments the function accepts. + */ + new (...args: string[]): Function; + (...args: string[]): Function; + prototype: Function; +} + +interface IArguments { + [index: number]: any; + length: number; + callee: Function; +} + +interface String { + /** Returns a string representation of a string. */ + toString(): string; + + /** + * Returns the character at the specified index. + * @param pos The zero-based index of the desired character. + */ + charAt(pos: number): string; + + /** + * Returns the Unicode value of the character at the specified location. + * @param index The zero-based index of the desired character. If there is no character at the specified index, NaN is returned. + */ + charCodeAt(index: number): number; + + /** + * Returns a string that contains the concatenation of two or more strings. + * @param strings The strings to append to the end of the string. + */ + concat(...strings: string[]): string; + + /** + * Returns the position of the first occurrence of a substring. + * @param searchString The substring to search for in the string + * @param position The index at which to begin searching the String object. If omitted, search starts at the beginning of the string. + */ + indexOf(searchString: string, position?: number): number; + + /** + * Returns the last occurrence of a substring in the string. + * @param searchString The substring to search for. + * @param position The index at which to begin searching. If omitted, the search begins at the end of the string. + */ + lastIndexOf(searchString: string, position?: number): number; + + /** + * Determines whether two strings are equivalent in the current locale. + * @param that String to compare to target string + */ + localeCompare(that: string): number; + + /** + * Matches a string with a regular expression, and returns an array containing the results of that search. + * @param regexp A variable name or string literal containing the regular expression pattern and flags. + */ + match(regexp: string): string[]; + /** + * Matches a string with a regular expression, and returns an array containing the results of that search. + * @param regexp A regular expression object that contains the regular expression pattern and applicable flags. + */ + match(regexp: RegExp): string[]; + + /** + * Replaces text in a string, using a regular expression or search string. + * @param searchValue A String object or string literal that represents the regular expression + * @param replaceValue A String object or string literal containing the text to replace for every successful match of rgExp in stringObj. + */ + replace(searchValue: string, replaceValue: string): string; + /** + * Replaces text in a string, using a regular expression or search string. + * @param searchValue A String object or string literal that represents the regular expression + * @param replaceValue A function that returns the replacement text. + */ + replace(searchValue: string, replaceValue: (substring: string, ...args: any[]) => string): string; + /** + * Replaces text in a string, using a regular expression or search string. + * @param searchValue A Regular Expression object containing the regular expression pattern and applicable flags + * @param replaceValue A String object or string literal containing the text to replace for every successful match of rgExp in stringObj. + */ + replace(searchValue: RegExp, replaceValue: string): string; + /** + * Replaces text in a string, using a regular expression or search string. + * @param searchValue A Regular Expression object containing the regular expression pattern and applicable flags + * @param replaceValue A function that returns the replacement text. + */ + replace(searchValue: RegExp, replaceValue: (substring: string, ...args: any[]) => string): string; + + /** + * Finds the first substring match in a regular expression search. + * @param regexp The regular expression pattern and applicable flags. + */ + search(regexp: string): number; + /** + * Finds the first substring match in a regular expression search. + * @param regexp The regular expression pattern and applicable flags. + */ + search(regexp: RegExp): number; + + /** + * Returns a section of a string. + * @param start The index to the beginning of the specified portion of stringObj. + * @param end The index to the end of the specified portion of stringObj. The substring includes the characters up to, but not including, the character indicated by end. + * If this value is not specified, the substring continues to the end of stringObj. + */ + slice(start: number, end?: number): string; + + /** + * Split a string into substrings using the specified separator and return them as an array. + * @param separator A string that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned. + * @param limit A value used to limit the number of elements returned in the array. + */ + split(separator: string, limit?: number): string[]; + /** + * Split a string into substrings using the specified separator and return them as an array. + * @param separator A Regular Express that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned. + * @param limit A value used to limit the number of elements returned in the array. + */ + split(separator: RegExp, limit?: number): string[]; + + /** + * Returns the substring at the specified location within a String object. + * @param start The zero-based index integer indicating the beginning of the substring. + * @param end Zero-based index integer indicating the end of the substring. The substring includes the characters up to, but not including, the character indicated by end. + * If end is omitted, the characters from start through the end of the original string are returned. + */ + substring(start: number, end?: number): string; + + /** Converts all the alphabetic characters in a string to lowercase. */ + toLowerCase(): string; + + /** Converts all alphabetic characters to lowercase, taking into account the host environment's current locale. */ + toLocaleLowerCase(): string; + + /** Converts all the alphabetic characters in a string to uppercase. */ + toUpperCase(): string; + + /** Returns a string where all alphabetic characters have been converted to uppercase, taking into account the host environment's current locale. */ + toLocaleUpperCase(): string; + + /** Removes the leading and trailing white space and line terminator characters from a string. */ + trim(): string; + + /** Returns the length of a String object. */ + length: number; + + // IE extensions + /** + * Gets a substring beginning at the specified location and having the specified length. + * @param from The starting position of the desired substring. The index of the first character in the string is zero. + * @param length The number of characters to include in the returned substring. + */ + substr(from: number, length?: number): string; +} + +/** + * Allows manipulation and formatting of text strings and determination and location of substrings within strings. + */ +declare var String: { + new (value?: any): String; + (value?: any): string; + prototype: String; + fromCharCode(...codes: number[]): string; +} + +interface Boolean { +} +declare var Boolean: { + new (value?: any): Boolean; + (value?: any): bool; + prototype: Boolean; +} + +interface Number { + toString(radix?: number): string; + toFixed(fractionDigits?: number): string; + toExponential(fractionDigits?: number): string; + toPrecision(precision: number): string; +} +/** An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers. */ +declare var Number: { + new (value?: any): Number; + (value?: any): number; + prototype: Number; + /** The largest number that can be represented in JavaScript. Equal to approximately 1.79E+308. */ + MAX_VALUE: number; + /** The closest number to zero that can be represented in JavaScript. Equal to approximately 5.00E-324. */ + MIN_VALUE: number; + /** + * A value that is not a number. + * In equality comparisons, NaN does not equal any value, including itself. To test whether a value is equivalent to NaN, use the isNaN function. + */ + NaN: number; + /** + * A value that is less than the largest negative number that can be represented in JavaScript. + * JavaScript displays NEGATIVE_INFINITY values as -infinity. + */ + NEGATIVE_INFINITY: number; + /** + * A value greater than the largest number that can be represented in JavaScript. + * JavaScript displays POSITIVE_INFINITY values as infinity. + */ + POSITIVE_INFINITY: number; +} + +interface Math { + /** The mathematical constant e. This is Euler's number, the base of natural logarithms. */ + E: number; + /** The natural logarithm of 10. */ + LN10: number; + /** The natural logarithm of 2. */ + LN2: number; + /** The base-2 logarithm of e. */ + LOG2E: number; + /** The base-10 logarithm of e. */ + LOG10E: number; + /** Pi. This is the ratio of the circumference of a circle to its diameter. */ + PI: number; + /** The square root of 0.5, or, equivalently, one divided by the square root of 2. */ + SQRT1_2: number; + /** The square root of 2. */ + SQRT2: number; + /** + * Returns the absolute value of a number (the value without regard to whether it is positive or negative). + * For example, the absolute value of -5 is the same as the absolute value of 5. + * @param x A numeric expression for which the absolute value is needed. + */ + abs(x: number): number; + /** + * Returns the arc cosine (or inverse cosine) of a number. + * @param x A numeric expression. + */ + acos(x: number): number; + /** + * Returns the arcsine of a number. + * @param x A numeric expression. + */ + asin(x: number): number; + /** + * Returns the arctangent of a number. + * @param x A numeric expression for which the arctangent is needed. + */ + atan(x: number): number; + /** + * Returns the angle (in radians) from the X axis to a point (y,x). + * @param y A numeric expression representing the cartesian y-coordinate. + * @param x A numeric expression representing the cartesian x-coordinate. + */ + atan2(y: number, x: number): number; + /** + * Returns the smallest integer greater than or equal to its numeric argument. + * @param x A numeric expression. + */ + ceil(x: number): number; + /** + * Returns the cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + cos(x: number): number; + /** + * Returns e (the base of natural logarithms) raised to a power. + * @param x A numeric expression representing the power of e. + */ + exp(x: number): number; + /** + * Returns the greatest integer less than or equal to its numeric argument. + * @param x A numeric expression. + */ + floor(x: number): number; + /** + * Returns the natural logarithm (base e) of a number. + * @param x A numeric expression. + */ + log(x: number): number; + /** + * Returns the larger of a set of supplied numeric expressions. + * @param values Numeric expressions to be evaluated. + */ + max(...values: number[]): number; + /** + * Returns the smaller of a set of supplied numeric expressions. + * @param values Numeric expressions to be evaluated. + */ + min(...values: number[]): number; + /** + * Returns the value of a base expression taken to a specified power. + * @param x The base value of the expression. + * @param y The exponent value of the expression. + */ + pow(x: number, y: number): number; + /** Returns a pseudorandom number between 0 and 1. */ + random(): number; + /** + * Returns a supplied numeric expression rounded to the nearest integer. + * @param x The value to be rounded to the nearest integer. + */ + round(x: number): number; + /** + * Returns the sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + sin(x: number): number; + /** + * Returns the square root of a number. + * @param x A numeric expression. + */ + sqrt(x: number): number; + /** + * Returns the tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + tan(x: number): number; +} +/** An intrinsic object that provides basic mathematics functionality and constants. */ +declare var Math: Math; + +/** Enables basic storage and retrieval of dates and times. */ +interface Date { + /** Returns a string representation of a date. The format of the string depends on the locale. */ + toString(): string; + /** Returns a date as a string value. */ + toDateString(): string; + /** Returns a time as a string value. */ + toTimeString(): string; + toLocaleString(): string; + /** Returns a date as a string value appropriate to the host environment's current locale. */ + toLocaleDateString(): string; + /** Returns a time as a string value appropriate to the host environment's current locale. */ + toLocaleTimeString(): string; + /** Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC. */ + valueOf(): number; + /** Gets the time value in milliseconds. */ + getTime(): number; + /** Gets the year, using local time. */ + getFullYear(): number; + /** Gets the year using Universal Coordinated Time (UTC). */ + getUTCFullYear(): number; + /** Gets the month, using local time. */ + getMonth(): number; + /** Gets the month of a Date object using Universal Coordinated Time (UTC). */ + getUTCMonth(): number; + /** Gets the day-of-the-month, using local time. */ + getDate(): number; + /** Gets the day-of-the-month, using Universal Coordinated Time (UTC). */ + getUTCDate(): number; + /** Gets the day of the week, using local time. */ + getDay(): number; + /** Gets the day of the week using Universal Coordinated Time (UTC). */ + getUTCDay(): number; + /** Gets the hours in a date, using local time. */ + getHours(): number; + /** Gets the hours value in a Date object using Universal Coordinated Time (UTC). */ + getUTCHours(): number; + /** Gets the minutes of a Date object, using local time. */ + getMinutes(): number; + /** Gets the minutes of a Date object using Universal Coordinated Time (UTC). */ + getUTCMinutes(): number; + /** Gets the seconds of a Date object, using local time. */ + getSeconds(): number; + /** Gets the seconds of a Date object using Universal Coordinated Time (UTC). */ + getUTCSeconds(): number; + /** Gets the milliseconds of a Date, using local time. */ + getMilliseconds(): number; + /** Gets the milliseconds of a Date object using Universal Coordinated Time (UTC). */ + getUTCMilliseconds(): number; + /** Gets the difference in minutes between the time on the local computer and Universal Coordinated Time (UTC). */ + getTimezoneOffset(): number; + /** + * Sets the date and time value in the Date object. + * @param time A numeric value representing the number of elapsed milliseconds since midnight, January 1, 1970 GMT. + */ + setTime(time: number): void; + /** + * Sets the milliseconds value in the Date object using local time. + * @param ms A numeric value equal to the millisecond value. + */ + setMilliseconds(ms: number): void; + /** + * Sets the milliseconds value in the Date object using Universal Coordinated Time (UTC). + * @param ms A numeric value equal to the millisecond value. + */ + setUTCMilliseconds(ms: number): void; + + /** + * Sets the seconds value in the Date object using local time. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setSeconds(sec: number, ms?: number): void; + /** + * Sets the seconds value in the Date object using Universal Coordinated Time (UTC). + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setUTCSeconds(sec: number, ms?: number): void; + /** + * Sets the minutes value in the Date object using local time. + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setMinutes(min: number, sec?: number, ms?: number): void; + /** + * Sets the minutes value in the Date object using Universal Coordinated Time (UTC). + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setUTCMinutes(min: number, sec?: number, ms?: number): void; + /** + * Sets the hour value in the Date object using local time. + * @param hours A numeric value equal to the hours value. + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setHours(hours: number, min?: number, sec?: number, ms?: number): void; + /** + * Sets the hours value in the Date object using Universal Coordinated Time (UTC). + * @param hours A numeric value equal to the hours value. + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setUTCHours(hours: number, min?: number, sec?: number, ms?: number): void; + /** + * Sets the numeric day-of-the-month value of the Date object using local time. + * @param date A numeric value equal to the day of the month. + */ + setDate(date: number): void; + /** + * Sets the numeric day of the month in the Date object using Universal Coordinated Time (UTC). + * @param date A numeric value equal to the day of the month. + */ + setUTCDate(date: number): void; + /** + * Sets the month value in the Date object using local time. + * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. + * @param date A numeric value representing the day of the month. If this value is not supplied, the value from a call to the getDate method is used. + */ + setMonth(month: number, date?: number): void; + /** + * Sets the month value in the Date object using Universal Coordinated Time (UTC). + * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. + * @param date A numeric value representing the day of the month. If it is not supplied, the value from a call to the getUTCDate method is used. + */ + setUTCMonth(month: number, date?: number): void; + /** + * Sets the year of the Date object using local time. + * @param year A numeric value for the year. + * @param month A zero-based numeric value for the month (0 for January, 11 for December). Must be specified if numDate is specified. + * @param date A numeric value equal for the day of the month. + */ + setFullYear(year: number, month?: number, date?: number): void; + /** + * Sets the year value in the Date object using Universal Coordinated Time (UTC). + * @param year A numeric value equal to the year. + * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. Must be supplied if numDate is supplied. + * @param date A numeric value equal to the day of the month. + */ + setUTCFullYear(year: number, month?: number, date?: number): void; + /** Returns a date converted to a string using Universal Coordinated Time (UTC). */ + toUTCString(): string; + /** Returns a date as a string value in ISO format. */ + toISOString(): string; + /** Used by the JSON.stringify method to enable the transformation of an object's data for JavaScript Object Notation (JSON) serialization. */ + toJSON(key?: any): string; +} +/** + * Enables basic storage and retrieval of dates and times. + */ +declare var Date: { + new (): Date; + new (value: number): Date; + new (value: string): Date; + new (year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date; + (): string; + prototype: Date; + /** + * Parses a string containing a date, and returns the number of milliseconds between that date and midnight, January 1, 1970. + * @param s A date string + */ + parse(s: string): number; + /** + * Returns the number of milliseconds between midnight, January 1, 1970 Universal Coordinated Time (UTC) (or GMT) and the specified date. + * @param year The full year designation is required for cross-century date accuracy. If year is between 0 and 99 is used, then year is assumed to be 1900 + year. + * @param month The month as an integer between 0 and 11 (January to December). + * @param date The date as an integer between 1 and 31. + * @param hours Must be supplied if minutes is supplied. An integer from 0 to 23 (midnight to 11pm) that specifies the hour. + * @param minutes Must be supplied if seconds is supplied. An integer from 0 to 59 that specifies the minutes. + * @param seconds Must be supplied if milliseconds is supplied. An integer from 0 to 59 that specifies the seconds. + * @param ms An integer from 0 to 999 that specifies the milliseconds. + */ + UTC(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): number; + now(): number; +} + +interface RegExpExecArray { + [index: number]: string; + length: number; + + index: number; + input: string; + + toString(): string; + toLocaleString(): string; + concat(...items: string[][]): string[]; + join(seperator?: string): string; + pop(): string; + push(...items: string[]): number; + reverse(): string[]; + shift(): string; + slice(start: number, end?: number): string[]; + sort(compareFn?: (a: string, b: string) => number): string[]; + splice(start: number): string[]; + splice(start: number, deleteCount: number, ...items: string[]): string[]; + unshift(...items: string[]): number; + + indexOf(searchElement: string, fromIndex?: number): number; + lastIndexOf(searchElement: string, fromIndex?: number): number; + every(callbackfn: (value: string, index: number, array: string[]) => bool, thisArg?: any): bool; + some(callbackfn: (value: string, index: number, array: string[]) => bool, thisArg?: any): bool; + forEach(callbackfn: (value: string, index: number, array: string[]) => void , thisArg?: any): void; + map(callbackfn: (value: string, index: number, array: string[]) => any, thisArg?: any): any[]; + filter(callbackfn: (value: string, index: number, array: string[]) => bool, thisArg?: any): string[]; + reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: string[]) => any, initialValue?: any): any; + reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: string[]) => any, initialValue?: any): any; +} + + +interface RegExp { + /** + * Executes a search on a string using a regular expression pattern, and returns an array containing the results of that search. + * @param string The String object or string literal on which to perform the search. + */ + exec(string: string): RegExpExecArray; + /** + * Returns a Boolean value that indicates whether or not a pattern exists in a searched string. + * @param string String on which to perform the search. + */ + test(string: string): bool; + /** Returns a copy of the text of the regular expression pattern. Read-only. The rgExp argument is a Regular expression object. It can be a variable name or a literal. */ + source: string; + /** Returns a Boolean value indicating the state of the global flag (g) used with a regular expression. Default is false. Read-only. */ + global: bool; + /** Returns a Boolean value indicating the state of the ignoreCase flag (i) used with a regular expression. Default is false. Read-only. */ + ignoreCase: bool; + /** Returns a Boolean value indicating the state of the multiline flag (m) used with a regular expression. Default is false. Read-only. */ + multiline: bool; + + lastIndex: number; +} +declare var RegExp: { + new (pattern: string, flags?: string): RegExp; + (pattern: string, flags?: string): RegExp; +} + +interface Error { + name: string; + message: string; +} +declare var Error: { + new (message?: string): Error; + (message?: string): Error; + prototype: Error; +} + +interface EvalError extends Error { +} +declare var EvalError: { + new (message?: string): EvalError; + (message?: string): EvalError; + prototype: EvalError; +} + +interface RangeError extends Error { +} +declare var RangeError: { + new (message?: string): RangeError; + (message?: string): RangeError; + prototype: RangeError; +} + +interface ReferenceError extends Error { +} +declare var ReferenceError: { + new (message?: string): ReferenceError; + (message?: string): ReferenceError; + prototype: ReferenceError; +} + +interface SyntaxError extends Error { +} +declare var SyntaxError: { + new (message?: string): SyntaxError; + (message?: string): SyntaxError; + prototype: SyntaxError; +} + +interface TypeError extends Error { +} +declare var TypeError: { + new (message?: string): TypeError; + (message?: string): TypeError; + prototype: TypeError; +} + +interface URIError extends Error { +} +declare var URIError: { + new (message?: string): URIError; + (message?: string): URIError; + prototype: URIError; +} + +interface JSON { + /** + * Converts a JavaScript Object Notation (JSON) string into an object. + * @param text A valid JSON string. + * @param reviver A function that transforms the results. This function is called for each member of the object. + * If a member contains nested objects, the nested objects are transformed before the parent object is. + */ + parse(text: string, reviver?: (key: any, value: any) => any): any; + /** + * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. + * @param value A JavaScript value, usually an object or array, to be converted. + */ + stringify(value: any): string; + /** + * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. + * @param value A JavaScript value, usually an object or array, to be converted. + * @param replacer A function that transforms the results. + */ + stringify(value: any, replacer: (key: string, value: any) => any): string; + /** + * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. + * @param value A JavaScript value, usually an object or array, to be converted. + * @param replacer Array that transforms the results. + */ + stringify(value: any, replacer: any[]): string; + /** + * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. + * @param value A JavaScript value, usually an object or array, to be converted. + * @param replacer A function that transforms the results. + * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. + */ + stringify(value: any, replacer: (key: string, value: any) => any, space: any): string; + /** + * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. + * @param value A JavaScript value, usually an object or array, to be converted. + * @param replacer Array that transforms the results. + * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. + */ + stringify(value: any, replacer: any[], space: any): string; +} +/** + * An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format. + */ +declare var JSON: JSON; + +//////////////// +/// ECMAScript Array API (specially handled by compiler) +//////////////// + +interface Array { + toString(): string; + toLocaleString(): string; + concat(...items: _element[][]): _element[]; + join(seperator?: string): string; + pop(): _element; + push(...items: _element[]): number; + reverse(): _element[]; + shift(): _element; + slice(start: number, end?: number): _element[]; + sort(compareFn?: (a: _element, b: _element) => number): _element[]; + splice(start: number): _element[]; + splice(start: number, deleteCount: number, ...items: _element[]): _element[]; + unshift(...items: _element[]): number; + + indexOf(searchElement: _element, fromIndex?: number): number; + lastIndexOf(searchElement: _element, fromIndex?: number): number; + every(callbackfn: (value: _element, index: number, array: _element[]) => bool, thisArg?: any): bool; + some(callbackfn: (value: _element, index: number, array: _element[]) => bool, thisArg?: any): bool; + forEach(callbackfn: (value: _element, index: number, array: _element[]) => void , thisArg?: any): void; + map(callbackfn: (value: _element, index: number, array: _element[]) => any, thisArg?: any): any[]; + filter(callbackfn: (value: _element, index: number, array: _element[]) => bool, thisArg?: any): _element[]; + reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: _element[]) => any, initialValue?: any): any; + reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: _element[]) => any, initialValue?: any): any; + + length: number; +} +declare var Array: { + new (...items: any[]): any[]; + (...items: any[]): any[]; + isArray(arg: any): bool; + prototype: Array; +} + +//////////////// +/// IE10 ECMAScript Extensions +//////////////// + +interface ArrayBuffer { + byteLength: number; +} +declare var ArrayBuffer: { + prototype: ArrayBuffer; + new (byteLength: number); +} + +interface ArrayBufferView { + buffer: ArrayBuffer; + byteOffset: number; + byteLength: number; +} + +interface Int8Array extends ArrayBufferView { + BYTES_PER_ELEMENT: number; + length: number; + [index: number]: number; + get(index: number): number; + set(index: number, value: number): void; + set(array: Int8Array, offset?: number): void; + set(array: number[], offset?: number): void; + subarray(begin: number, end?: number): Int8Array; +} +declare var Int8Array: { + prototype: Int8Array; + new (length: number): Int8Array; + new (array: Int8Array): Int8Array; + new (array: number[]): Int8Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int8Array; + BYTES_PER_ELEMENT: number; +} + +interface Uint8Array extends ArrayBufferView { + BYTES_PER_ELEMENT: number; + length: number; + [index: number]: number; + get(index: number): number; + set(index: number, value: number): void; + set(array: Uint8Array, offset?: number): void; + set(array: number[], offset?: number): void; + subarray(begin: number, end?: number): Uint8Array; +} +declare var Uint8Array: { + prototype: Uint8Array; + new (length: number): Uint8Array; + new (array: Uint8Array): Uint8Array; + new (array: number[]): Uint8Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8Array; + BYTES_PER_ELEMENT: number; +} + +interface Int16Array extends ArrayBufferView { + BYTES_PER_ELEMENT: number; + length: number; + [index: number]: number; + get(index: number): number; + set(index: number, value: number): void; + set(array: Int16Array, offset?: number): void; + set(array: number[], offset?: number): void; + subarray(begin: number, end?: number): Int16Array; +} +declare var Int16Array: { + prototype: Int16Array; + new (length: number): Int16Array; + new (array: Int16Array): Int16Array; + new (array: number[]): Int16Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int16Array; + BYTES_PER_ELEMENT: number; +} + +interface Uint16Array extends ArrayBufferView { + BYTES_PER_ELEMENT: number; + length: number; + [index: number]: number; + get(index: number): number; + set(index: number, value: number): void; + set(array: Uint16Array, offset?: number): void; + set(array: number[], offset?: number): void; + subarray(begin: number, end?: number): Uint16Array; +} +declare var Uint16Array: { + prototype: Uint16Array; + new (length: number): Uint16Array; + new (array: Uint16Array): Uint16Array; + new (array: number[]): Uint16Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint16Array; + BYTES_PER_ELEMENT: number; +} + +interface Int32Array extends ArrayBufferView { + BYTES_PER_ELEMENT: number; + length: number; + [index: number]: number; + get(index: number): number; + set(index: number, value: number): void; + set(array: Int32Array, offset?: number): void; + set(array: number[], offset?: number): void; + subarray(begin: number, end?: number): Int32Array; +} +declare var Int32Array: { + prototype: Int32Array; + new (length: number): Int32Array; + new (array: Int32Array): Int32Array; + new (array: number[]): Int32Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int32Array; + BYTES_PER_ELEMENT: number; +} + +interface Uint32Array extends ArrayBufferView { + BYTES_PER_ELEMENT: number; + length: number; + [index: number]: number; + get(index: number): number; + set(index: number, value: number): void; + set(array: Uint32Array, offset?: number): void; + set(array: number[], offset?: number): void; + subarray(begin: number, end?: number): Uint32Array; +} +declare var Uint32Array: { + prototype: Uint32Array; + new (length: number): Uint32Array; + new (array: Uint32Array): Uint32Array; + new (array: number[]): Uint32Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint32Array; + BYTES_PER_ELEMENT: number; +} + +interface Float32Array extends ArrayBufferView { + BYTES_PER_ELEMENT: number; + length: number; + [index: number]: number; + get(index: number): number; + set(index: number, value: number): void; + set(array: Float32Array, offset?: number): void; + set(array: number[], offset?: number): void; + subarray(begin: number, end?: number): Float32Array; +} +declare var Float32Array: { + prototype: Float32Array; + new (length: number): Float32Array; + new (array: Float32Array): Float32Array; + new (array: number[]): Float32Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float32Array; + BYTES_PER_ELEMENT: number; +} + +interface Float64Array extends ArrayBufferView { + BYTES_PER_ELEMENT: number; + length: number; + [index: number]: number; + get(index: number): number; + set(index: number, value: number): void; + set(array: Float64Array, offset?: number): void; + set(array: number[], offset?: number): void; + subarray(begin: number, end?: number): Float64Array; +} +declare var Float64Array: { + prototype: Float64Array; + new (length: number): Float64Array; + new (array: Float64Array): Float64Array; + new (array: number[]): Float64Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float64Array; + BYTES_PER_ELEMENT: number; +} + +interface DataView extends ArrayBufferView { + getInt8(byteOffset: number): number; + getUint8(byteOffset: number): number; + getInt16(byteOffset: number, littleEndian?: bool): number; + getUint16(byteOffset: number, littleEndian?: bool): number; + getInt32(byteOffset: number, littleEndian?: bool): number; + getUint32(byteOffset: number, littleEndian?: bool): number; + getFloat32(byteOffset: number, littleEndian?: bool): number; + getFloat64(byteOffset: number, littleEndian?: bool): number; + + setInt8(byteOffset: number, value: number): void; + setUint8(byteOffset: number, value: number): void; + setInt16(byteOffset: number, value: number, littleEndian?: bool): void; + setUint16(byteOffset: number, value: number, littleEndian?: bool): void; + setInt32(byteOffset: number, value: number, littleEndian?: bool): void; + setUint32(byteOffset: number, value: number, littleEndian?: bool): void; + setFloat32(byteOffset: number, value: number, littleEndian?: bool): void; + setFloat64(byteOffset: number, value: number, littleEndian?: bool): void; +} +declare var DataView: { + prototype: DataView; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): DataView; +} + +//////////////// +/// IE9 DOM APIs (note that +//////////////// + +interface NavigatorID { + appVersion: string; + appName: string; + userAgent: string; + platform: string; +} + +interface HTMLTableElement extends HTMLElement, DOML2DeprecatedBorderStyle_HTMLTableElement, DOML2DeprecatedAlignmentStyle_HTMLTableElement, MSBorderColorStyle, MSDataBindingExtensions, MSHTMLTableElementExtensions, DOML2DeprecatedBackgroundStyle, MSBorderColorHighlightStyle, MSDataBindingTableExtensions, DOML2DeprecatedBackgroundColorStyle { + tBodies: HTMLCollection; + width: string; + tHead: HTMLTableSectionElement; + cellSpacing: string; + tFoot: HTMLTableSectionElement; + frame: string; + rows: HTMLCollection; + rules: string; + cellPadding: string; + summary: string; + caption: HTMLTableCaptionElement; + deleteRow(index?: number): void; + createTBody(): HTMLElement; + deleteCaption(): void; + insertRow(index?: number): HTMLElement; + deleteTFoot(): void; + createTHead(): HTMLElement; + deleteTHead(): void; + createCaption(): HTMLElement; + createTFoot(): HTMLElement; +} +declare var HTMLTableElement: { + prototype: HTMLTableElement; + new(): HTMLTableElement; +} + +interface TreeWalker { + whatToShow: number; + filter: NodeFilterCallback; + root: Node; + currentNode: Node; + expandEntityReferences: bool; + previousSibling(): Node; + lastChild(): Node; + nextSibling(): Node; + nextNode(): Node; + parentNode(): Node; + firstChild(): Node; + previousNode(): Node; +} +declare var TreeWalker: { + prototype: TreeWalker; + new(): TreeWalker; +} + +interface GetSVGDocument { + getSVGDocument(): SVGDocument; +} + +interface HTMLHtmlElementDOML2Deprecated { + version: string; +} + +interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { + y: number; + y1: number; + x: number; + x1: number; +} +declare var SVGPathSegCurvetoQuadraticRel: { + prototype: SVGPathSegCurvetoQuadraticRel; + new(): SVGPathSegCurvetoQuadraticRel; +} + +interface Performance { + navigation: PerformanceNavigation; + timing: PerformanceTiming; + toJSON(): any; +} +declare var Performance: { + prototype: Performance; + new(): Performance; +} + +interface SVGSVGElementEventHandlers { + onresize: (ev: UIEvent) => any; + onunload: (ev: Event) => any; + onscroll: (ev: UIEvent) => any; + onerror: (ev: Event) => any; + onzoom: (ev: any) => any; + onabort: (ev: UIEvent) => any; +} + +interface MSDataBindingTableExtensions { + dataPageSize: number; + nextPage(): void; + firstPage(): void; + refresh(): void; + previousPage(): void; + lastPage(): void; +} + +interface DOML2DeprecatedAlignmentStyle_HTMLParagraphElement { + align: string; +} + +interface CompositionEvent extends UIEvent { + data: string; + locale: string; + initCompositionEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, dataArg: string, locale: string): void; +} +declare var CompositionEvent: { + prototype: CompositionEvent; + new(): CompositionEvent; +} + +interface SVGMarkerElement extends SVGElement, SVGStylable, SVGLangSpace, SVGFitToViewBox { + orientType: SVGAnimatedEnumeration; + markerUnits: SVGAnimatedEnumeration; + markerWidth: SVGAnimatedLength; + markerHeight: SVGAnimatedLength; + orientAngle: SVGAnimatedAngle; + refY: SVGAnimatedLength; + refX: SVGAnimatedLength; + setOrientToAngle(angle: SVGAngle): void; + setOrientToAuto(): void; + SVG_MARKER_ORIENT_UNKNOWN: number; + SVG_MARKER_ORIENT_ANGLE: number; + SVG_MARKERUNITS_UNKNOWN: number; + SVG_MARKERUNITS_STROKEWIDTH: number; + SVG_MARKER_ORIENT_AUTO: number; + SVG_MARKERUNITS_USERSPACEONUSE: number; +} +declare var SVGMarkerElement: { + prototype: SVGMarkerElement; + new(): SVGMarkerElement; + SVG_MARKER_ORIENT_UNKNOWN: number; + SVG_MARKER_ORIENT_ANGLE: number; + SVG_MARKERUNITS_UNKNOWN: number; + SVG_MARKERUNITS_STROKEWIDTH: number; + SVG_MARKER_ORIENT_AUTO: number; + SVG_MARKERUNITS_USERSPACEONUSE: number; +} + +interface WindowTimers { + clearTimeout(handle: number): void; + setTimeout(expression: any, msec?: number, language?: any): number; + clearInterval(handle: number): void; + setInterval(expression: any, msec?: number, language?: any): number; +} + +interface CSSStyleDeclaration extends CSS3Properties, SVG1_1Properties, CSS2Properties { + cssText: string; + length: number; + parentRule: CSSRule; + getPropertyPriority(propertyName: string): string; + getPropertyValue(propertyName: string): string; + removeProperty(propertyName: string): string; + item(index: number): string; + [index: number]: string; + setProperty(propertyName: string, value: string, priority?: string): void; +} +declare var CSSStyleDeclaration: { + prototype: CSSStyleDeclaration; + new(): CSSStyleDeclaration; +} + +interface SVGGElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests { +} +declare var SVGGElement: { + prototype: SVGGElement; + new(): SVGGElement; +} + +interface MSStyleCSSProperties extends MSCSSProperties { + pixelWidth: number; + posHeight: number; + posLeft: number; + pixelTop: number; + pixelBottom: number; + textDecorationNone: bool; + pixelLeft: number; + posTop: number; + posBottom: number; + textDecorationOverline: bool; + posWidth: number; + textDecorationLineThrough: bool; + pixelHeight: number; + textDecorationBlink: bool; + posRight: number; + pixelRight: number; + textDecorationUnderline: bool; +} +declare var MSStyleCSSProperties: { + prototype: MSStyleCSSProperties; + new(): MSStyleCSSProperties; +} + +interface MSCSSStyleSheetExtensions { + owningElement: Element; + imports: StyleSheetList; + isAlternate: bool; + rules: MSCSSRuleList; + isPrefAlternate: bool; + readOnly: bool; + cssText: string; + href: string; + id: string; + pages: StyleSheetPageList; + addImport(bstrURL: string, lIndex?: number): number; + addPageRule(bstrSelector: string, bstrStyle: string, lIndex?: number): number; + removeRule(lIndex: number): void; + addRule(bstrSelector: string, bstrStyle?: string, lIndex?: number): number; + removeImport(lIndex: number): void; +} + +interface Navigator extends NavigatorID, NavigatorOnLine, NavigatorDoNotTrack, NavigatorAbilities, NavigatorGeolocation, MSNavigatorAbilities { +} +declare var Navigator: { + prototype: Navigator; + new(): Navigator; +} + +interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { + y: number; + x2: number; + x: number; + y2: number; +} +declare var SVGPathSegCurvetoCubicSmoothAbs: { + prototype: SVGPathSegCurvetoCubicSmoothAbs; + new(): SVGPathSegCurvetoCubicSmoothAbs; +} + +interface MSBorderColorStyle_HTMLFrameSetElement { + borderColor: any; +} + +interface SVGZoomEvent extends UIEvent { + zoomRectScreen: SVGRect; + previousScale: number; + newScale: number; + previousTranslate: SVGPoint; + newTranslate: SVGPoint; +} +declare var SVGZoomEvent: { + prototype: SVGZoomEvent; + new(): SVGZoomEvent; +} + +interface NodeSelector { + querySelectorAll(selectors: string): NodeList; + querySelector(selectors: string): Element; +} + +interface HTMLTableDataCellElement extends HTMLTableCellElement, MSHTMLTableDataCellElementExtensions { +} +declare var HTMLTableDataCellElement: { + prototype: HTMLTableDataCellElement; + new(): HTMLTableDataCellElement; +} + +interface MSHTMLDirectoryElementExtensions extends DOML2DeprecatedListNumberingAndBulletStyle { +} + +interface HTMLBaseElement extends HTMLElement { + target: string; + href: string; +} +declare var HTMLBaseElement: { + prototype: HTMLBaseElement; + new(): HTMLBaseElement; +} + +interface ClientRect { + left: number; + width: number; + right: number; + top: number; + bottom: number; + height: number; +} +declare var ClientRect: { + prototype: ClientRect; + new(): ClientRect; +} + +interface PositionErrorCallback { + (error: PositionError): void; +} + +interface DOMImplementation extends DOMHTMLImplementation { + createDocumentType(qualifiedName: string, publicId: string, systemId: string): DocumentType; + createDocument(namespaceURI: string, qualifiedName: string, doctype: DocumentType): Document; + hasFeature(feature: string, version?: string): bool; +} +declare var DOMImplementation: { + prototype: DOMImplementation; + new(): DOMImplementation; +} + +interface DOML2DeprecatedWidthStyle_HTMLBlockElement { + width: number; +} + +interface SVGUnitTypes { + SVG_UNIT_TYPE_UNKNOWN: number; + SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: number; + SVG_UNIT_TYPE_USERSPACEONUSE: number; +} +declare var SVGUnitTypes: { + prototype: SVGUnitTypes; + new(): SVGUnitTypes; + SVG_UNIT_TYPE_UNKNOWN: number; + SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: number; + SVG_UNIT_TYPE_USERSPACEONUSE: number; +} + +interface DocumentRange { + createRange(): Range; +} + +interface MSHTMLDocumentExtensions { + onrowexit: (ev: MSEventObj) => any; + compatible: MSCompatibleInfoCollection; + oncontrolselect: (ev: MSEventObj) => any; + onrowsinserted: (ev: MSEventObj) => any; + onpropertychange: (ev: MSEventObj) => any; + media: string; + onafterupdate: (ev: MSEventObj) => any; + onhelp: (ev: Event) => any; + uniqueID: string; + onbeforeactivate: (ev: UIEvent) => any; + onstoragecommit: (ev: StorageEvent) => any; + onselectionchange: (ev: Event) => any; + documentMode: number; + onfocusout: (ev: FocusEvent) => any; + ondataavailable: (ev: MSEventObj) => any; + onbeforeupdate: (ev: MSEventObj) => any; + onfocusin: (ev: FocusEvent) => any; + security: string; + namespaces: MSNamespaceInfoCollection; + ondatasetcomplete: (ev: MSEventObj) => any; + onbeforedeactivate: (ev: UIEvent) => any; + onstop: (ev: Event) => any; + onactivate: (ev: UIEvent) => any; + onmssitemodejumplistitemremoved: (ev: MSSiteModeEvent) => any; + frames: Window; + onselectstart: (ev: Event) => any; + onerrorupdate: (ev: MSEventObj) => any; + parentWindow: Window; + ondeactivate: (ev: UIEvent) => any; + ondatasetchanged: (ev: MSEventObj) => any; + onrowsdelete: (ev: MSEventObj) => any; + onmsthumbnailclick: (ev: MSSiteModeEvent) => any; + onrowenter: (ev: MSEventObj) => any; + onbeforeeditfocus: (ev: MSEventObj) => any; + Script: MSScriptHost; + oncellchange: (ev: MSEventObj) => any; + URLUnencoded: string; + updateSettings(): void; + execCommandShowHelp(commandId: string): bool; + releaseCapture(): void; + focus(): void; +} + +interface CSS2Properties { + backgroundAttachment: string; + visibility: string; + fontFamily: string; + borderRightStyle: string; + clear: string; + content: string; + counterIncrement: string; + orphans: string; + marginBottom: string; + borderStyle: string; + counterReset: string; + outlineWidth: string; + marginRight: string; + paddingLeft: string; + borderBottom: string; + marginTop: string; + borderTopColor: string; + top: string; + fontWeight: string; + textIndent: string; + borderRight: string; + width: string; + listStyleImage: string; + cursor: string; + listStylePosition: string; + borderTopStyle: string; + direction: string; + maxWidth: string; + color: string; + clip: string; + borderRightWidth: string; + verticalAlign: string; + pageBreakAfter: string; + overflow: string; + borderBottomStyle: string; + borderLeftStyle: string; + fontStretch: string; + emptyCells: string; + padding: string; + paddingRight: string; + background: string; + bottom: string; + height: string; + paddingTop: string; + right: string; + borderLeftWidth: string; + borderLeft: string; + backgroundPosition: string; + backgroundColor: string; + widows: string; + lineHeight: string; + pageBreakInside: string; + borderTopWidth: string; + left: string; + outlineStyle: string; + borderTop: string; + paddingBottom: string; + outlineColor: string; + wordSpacing: string; + outline: string; + font: string; + marginLeft: string; + display: string; + maxHeight: string; + cssFloat: string; + letterSpacing: string; + borderSpacing: string; + backgroundRepeat: string; + fontSizeAdjust: string; + borderLeftColor: string; + borderWidth: string; + backgroundImage: string; + listStyleType: string; + whiteSpace: string; + fontStyle: string; + borderBottomColor: string; + minWidth: string; + position: string; + zIndex: string; + borderColor: string; + listStyle: string; + captionSide: string; + borderCollapse: string; + fontVariant: string; + quotes: string; + tableLayout: string; + unicodeBidi: string; + borderBottomWidth: string; + minHeight: string; + textDecoration: string; + fontSize: string; + border: string; + pageBreakBefore: string; + textAlign: string; + textTransform: string; + margin: string; + borderRightColor: string; +} + +interface MSImageResourceExtensions_HTMLInputElement { + dynsrc: string; + vrml: string; + lowsrc: string; + start: string; + loop: number; +} + +interface MSHTMLEmbedElementExtensions { + palette: string; + hidden: string; + pluginspage: string; + units: string; +} + +interface MSHTMLModElementExtensions { +} + +interface Element extends Node, NodeSelector, ElementTraversal, MSElementExtensions { + scrollTop: number; + clientLeft: number; + scrollLeft: number; + tagName: string; + clientWidth: number; + scrollWidth: number; + clientHeight: number; + clientTop: number; + scrollHeight: number; + getAttribute(name?: string): string; + getElementsByTagNameNS(namespaceURI: string, localName: string): NodeList; + hasAttributeNS(namespaceURI: string, localName: string): bool; + getBoundingClientRect(): ClientRect; + getAttributeNS(namespaceURI: string, localName: string): string; + getAttributeNodeNS(namespaceURI: string, localName: string): Attr; + setAttributeNodeNS(newAttr: Attr): Attr; + hasAttribute(name: string): bool; + removeAttribute(name?: string): void; + setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; + getAttributeNode(name: string): Attr; + getElementsByTagName(name: string): NodeList; + setAttributeNode(newAttr: Attr): Attr; + getClientRects(): ClientRectList; + removeAttributeNode(oldAttr: Attr): Attr; + setAttribute(name?: string, value?: string): void; + removeAttributeNS(namespaceURI: string, localName: string): void; +} +declare var Element: { + prototype: Element; + new(): Element; +} + +interface SVGDocument { + rootElement: SVGSVGElement; +} + +interface HTMLNextIdElement extends HTMLElement { + n: string; +} +declare var HTMLNextIdElement: { + prototype: HTMLNextIdElement; + new(): HTMLNextIdElement; +} + +interface SVGPathSegMovetoRel extends SVGPathSeg { + y: number; + x: number; +} +declare var SVGPathSegMovetoRel: { + prototype: SVGPathSegMovetoRel; + new(): SVGPathSegMovetoRel; +} + +interface SVGLineElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests { + y1: SVGAnimatedLength; + x2: SVGAnimatedLength; + x1: SVGAnimatedLength; + y2: SVGAnimatedLength; +} +declare var SVGLineElement: { + prototype: SVGLineElement; + new(): SVGLineElement; +} + +interface HTMLParagraphElement extends HTMLElement, DOML2DeprecatedAlignmentStyle_HTMLParagraphElement, MSHTMLParagraphElementExtensions { +} +declare var HTMLParagraphElement: { + prototype: HTMLParagraphElement; + new(): HTMLParagraphElement; +} + +interface MSHTMLTextAreaElementExtensions { + status: any; + createTextRange(): TextRange; +} + +interface ErrorFunction { + (eventOrMessage: any, source: string, fileno: number): any; +} + +interface HTMLAreasCollection extends HTMLCollection { + remove(index?: number): void; + add(element: HTMLElement, before?: any): void; +} +declare var HTMLAreasCollection: { + prototype: HTMLAreasCollection; + new(): HTMLAreasCollection; +} + +interface SVGDescElement extends SVGElement, SVGStylable, SVGLangSpace { +} +declare var SVGDescElement: { + prototype: SVGDescElement; + new(): SVGDescElement; +} + +interface Node extends EventTarget { + nodeType: number; + previousSibling: Node; + localName: string; + namespaceURI: string; + textContent: string; + parentNode: Node; + nextSibling: Node; + nodeValue: string; + lastChild: Node; + childNodes: NodeList; + nodeName: string; + ownerDocument: Document; + attributes: Attr[]; + firstChild: Node; + prefix: string; + removeChild(oldChild: Node): Node; + appendChild(newChild: Node): Node; + isSupported(feature: string, version: string): bool; + isEqualNode(arg: Node): bool; + lookupPrefix(namespaceURI: string): string; + isDefaultNamespace(namespaceURI: string): bool; + compareDocumentPosition(other: Node): number; + normalize(): void; + isSameNode(other: Node): bool; + hasAttributes(): bool; + lookupNamespaceURI(prefix: string): string; + cloneNode(deep?: bool): Node; + hasChildNodes(): bool; + replaceChild(newChild: Node, oldChild: Node): Node; + insertBefore(newChild: Node, refChild?: Node): Node; + ENTITY_REFERENCE_NODE: number; + ATTRIBUTE_NODE: number; + DOCUMENT_FRAGMENT_NODE: number; + TEXT_NODE: number; + ELEMENT_NODE: number; + COMMENT_NODE: number; + DOCUMENT_POSITION_DISCONNECTED: number; + DOCUMENT_POSITION_CONTAINED_BY: number; + DOCUMENT_POSITION_CONTAINS: number; + DOCUMENT_TYPE_NODE: number; + DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: number; + DOCUMENT_NODE: number; + ENTITY_NODE: number; + PROCESSING_INSTRUCTION_NODE: number; + CDATA_SECTION_NODE: number; + NOTATION_NODE: number; + DOCUMENT_POSITION_FOLLOWING: number; + DOCUMENT_POSITION_PRECEDING: number; +} +declare var Node: { + prototype: Node; + new(): Node; + ENTITY_REFERENCE_NODE: number; + ATTRIBUTE_NODE: number; + DOCUMENT_FRAGMENT_NODE: number; + TEXT_NODE: number; + ELEMENT_NODE: number; + COMMENT_NODE: number; + DOCUMENT_POSITION_DISCONNECTED: number; + DOCUMENT_POSITION_CONTAINED_BY: number; + DOCUMENT_POSITION_CONTAINS: number; + DOCUMENT_TYPE_NODE: number; + DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: number; + DOCUMENT_NODE: number; + ENTITY_NODE: number; + PROCESSING_INSTRUCTION_NODE: number; + CDATA_SECTION_NODE: number; + NOTATION_NODE: number; + DOCUMENT_POSITION_FOLLOWING: number; + DOCUMENT_POSITION_PRECEDING: number; +} + +interface MSHTMLLegendElementExtensions { +} + +interface MSCSSStyleDeclarationExtensions { + getAttribute(attributeName: string, flags?: number): any; + setAttribute(attributeName: string, AttributeValue: any, flags?: number): void; + removeAttribute(attributeName: string, flags?: number): bool; +} + +interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { + y: number; + x: number; +} +declare var SVGPathSegCurvetoQuadraticSmoothRel: { + prototype: SVGPathSegCurvetoQuadraticSmoothRel; + new(): SVGPathSegCurvetoQuadraticSmoothRel; +} + +interface DOML2DeprecatedAlignmentStyle_HTMLTableRowElement { + align: string; +} + +interface DOML2DeprecatedBorderStyle_HTMLObjectElement { + border: string; +} + +interface MSHTMLSpanElementExtensions { +} + +interface MSHTMLObjectElementExtensions { + object: Object; + alt: string; + classid: string; + altHtml: string; + BaseHref: string; +} + +interface DOML2DeprecatedListSpaceReduction { + compact: bool; +} + +interface CSS3Properties { + textAlignLast: string; + textUnderlinePosition: string; + wordWrap: string; + borderTopLeftRadius: string; + backgroundClip: string; + msTransformOrigin: string; + opacity: string; + overflowY: string; + boxShadow: string; + backgroundSize: string; + wordBreak: string; + boxSizing: string; + rubyOverhang: string; + rubyAlign: string; + textJustify: string; + borderRadius: string; + overflowX: string; + borderTopRightRadius: string; + msTransform: string; + borderBottomLeftRadius: string; + rubyPosition: string; + borderBottomRightRadius: string; + backgroundOrigin: string; + textOverflow: string; +} + +interface MSScriptHost { +} +declare var MSScriptHost: { + prototype: MSScriptHost; + new(): MSScriptHost; +} + +interface SVGClipPathElement extends SVGElement, SVGUnitTypes, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests { + clipPathUnits: SVGAnimatedEnumeration; +} +declare var SVGClipPathElement: { + prototype: SVGClipPathElement; + new(): SVGClipPathElement; +} + +interface MouseEvent extends UIEvent, MSMouseEventExtensions { + pageX: number; + offsetY: number; + x: number; + y: number; + altKey: bool; + metaKey: bool; + ctrlKey: bool; + offsetX: number; + screenX: number; + clientY: number; + shiftKey: bool; + screenY: number; + relatedTarget: EventTarget; + button: number; + pageY: number; + buttons: number; + clientX: number; + initMouseEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: bool, altKeyArg: bool, shiftKeyArg: bool, metaKeyArg: bool, buttonArg: number, relatedTargetArg: EventTarget): void; + getModifierState(keyArg: string): bool; +} +declare var MouseEvent: { + prototype: MouseEvent; + new(): MouseEvent; +} + +interface DOML2DeprecatedAlignmentStyle_HTMLTableElement { + align: string; +} + +interface RangeException { + code: number; + message: string; + toString(): string; + INVALID_NODE_TYPE_ERR: number; + BAD_BOUNDARYPOINTS_ERR: number; +} +declare var RangeException: { + prototype: RangeException; + new(): RangeException; + INVALID_NODE_TYPE_ERR: number; + BAD_BOUNDARYPOINTS_ERR: number; +} + +interface DOML2DeprecatedAlignmentStyle_HTMLHRElement { + align: string; +} + +interface SVGTextPositioningElement extends SVGTextContentElement { + y: SVGAnimatedLengthList; + rotate: SVGAnimatedNumberList; + dy: SVGAnimatedLengthList; + x: SVGAnimatedLengthList; + dx: SVGAnimatedLengthList; +} +declare var SVGTextPositioningElement: { + prototype: SVGTextPositioningElement; + new(): SVGTextPositioningElement; +} + +interface HTMLAppletElement extends HTMLElement, DOML2DeprecatedWidthStyle_HTMLAppletElement, DOML2DeprecatedMarginStyle_HTMLObjectElement, MSHTMLAppletElementExtensions, MSDataBindingExtensions, MSDataBindingRecordSetExtensions, DOML2DeprecatedAlignmentStyle_HTMLObjectElement { + object: string; + archive: string; + codeBase: string; + alt: string; + name: string; + height: string; + code: string; +} +declare var HTMLAppletElement: { + prototype: HTMLAppletElement; + new(): HTMLAppletElement; +} + +interface MSHTMLFieldSetElementExtensions extends DOML2DeprecatedAlignmentStyle_HTMLFieldSetElement { +} + +interface DocumentEvent { + createEvent(eventInterface: string): Event; +} + +interface MSHTMLUnknownElementExtensions { +} + +interface TextMetrics { + width: number; +} +declare var TextMetrics: { + prototype: TextMetrics; + new(): TextMetrics; +} + +interface DOML2DeprecatedWordWrapSuppression_HTMLBodyElement { + noWrap: bool; +} + +interface HTMLOListElement extends HTMLElement, DOML2DeprecatedListNumberingAndBulletStyle, DOML2DeprecatedListSpaceReduction, MSHTMLOListElementExtensions { + start: number; +} +declare var HTMLOListElement: { + prototype: HTMLOListElement; + new(): HTMLOListElement; +} + +interface MSHTMLTableCaptionElementExtensions { + vAlign: string; +} + +interface SVGAnimatedString { + animVal: string; + baseVal: string; +} +declare var SVGAnimatedString: { + prototype: SVGAnimatedString; + new(): SVGAnimatedString; +} + +interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { + y: number; +} +declare var SVGPathSegLinetoVerticalRel: { + prototype: SVGPathSegLinetoVerticalRel; + new(): SVGPathSegLinetoVerticalRel; +} + +interface CDATASection extends Text { +} +declare var CDATASection: { + prototype: CDATASection; + new(): CDATASection; +} + +interface StyleMedia { + type: string; + matchMedium(mediaquery: string): bool; +} +declare var StyleMedia: { + prototype: StyleMedia; + new(): StyleMedia; +} + +interface TextRange { + boundingLeft: number; + htmlText: string; + offsetLeft: number; + boundingWidth: number; + boundingHeight: number; + boundingTop: number; + text: string; + offsetTop: number; + moveToPoint(x: number, y: number): void; + queryCommandValue(cmdID: string): any; + getBookmark(): string; + move(Unit: string, Count?: number): number; + queryCommandIndeterm(cmdID: string): bool; + scrollIntoView(fStart?: bool): void; + findText(string: string, count?: number, flags?: number): bool; + execCommand(cmdID: string, showUI?: bool, value?: any): bool; + getBoundingClientRect(): ClientRect; + moveToBookmark(Bookmark: string): bool; + isEqual(range: TextRange): bool; + duplicate(): TextRange; + collapse(Start?: bool): void; + queryCommandText(cmdID: string): string; + select(): void; + pasteHTML(html: string): void; + inRange(range: TextRange): bool; + moveEnd(Unit: string, Count?: number): number; + getClientRects(): ClientRectList; + moveStart(Unit: string, Count?: number): number; + parentElement(): Element; + queryCommandState(cmdID: string): bool; + compareEndPoints(how: string, sourceRange: TextRange): number; + execCommandShowHelp(cmdID: string): bool; + moveToElementText(element: Element): void; + expand(Unit: string): bool; + queryCommandSupported(cmdID: string): bool; + setEndPoint(how: string, SourceRange: TextRange): void; + queryCommandEnabled(cmdID: string): bool; +} +declare var TextRange: { + prototype: TextRange; + new(): TextRange; +} + +interface HTMLSelectElement extends HTMLElement, MSHTMLCollectionExtensions, MSDataBindingExtensions, MSHTMLSelectElementExtensions { + options: HTMLSelectElement; + value: string; + form: HTMLFormElement; + name: string; + size: number; + length: number; + selectedIndex: number; + multiple: bool; + type: string; + remove(index?: number): void; + add(element: HTMLElement, before?: any): void; + item(name?: any, index?: any): any; + (name: any, index: any): any; + namedItem(name: string): any; + [name: string]: any; + (name: string): any; +} +declare var HTMLSelectElement: { + prototype: HTMLSelectElement; + new(): HTMLSelectElement; +} + +interface CSSStyleSheet extends StyleSheet, MSCSSStyleSheetExtensions { + ownerRule: CSSRule; + cssRules: CSSRuleList; + insertRule(rule: string, index?: number): number; + deleteRule(index?: number): void; +} +declare var CSSStyleSheet: { + prototype: CSSStyleSheet; + new(): CSSStyleSheet; +} + +interface HTMLBlockElement extends HTMLElement, DOML2DeprecatedTextFlowControl_HTMLBlockElement, DOML2DeprecatedWidthStyle_HTMLBlockElement { + cite: string; +} +declare var HTMLBlockElement: { + prototype: HTMLBlockElement; + new(): HTMLBlockElement; +} + +interface SVGTests { + requiredFeatures: SVGStringList; + requiredExtensions: SVGStringList; + systemLanguage: SVGStringList; + hasExtension(extension: string): bool; +} + +interface MSSelection { + type: string; + typeDetail: string; + createRange(): TextRange; + clear(): void; + createRangeCollection(): TextRangeCollection; + empty(): void; +} +declare var MSSelection: { + prototype: MSSelection; + new(): MSSelection; +} + +interface MSHTMLDListElementExtensions { +} + +interface HTMLMetaElement extends HTMLElement, MSHTMLMetaElementExtensions { + httpEquiv: string; + name: string; + content: string; + scheme: string; +} +declare var HTMLMetaElement: { + prototype: HTMLMetaElement; + new(): HTMLMetaElement; +} + +interface Selection { + isCollapsed: bool; + anchorNode: Node; + focusNode: Node; + anchorOffset: number; + focusOffset: number; + rangeCount: number; + addRange(range: Range): void; + collapseToEnd(): void; + toString(): string; + selectAllChildren(parentNode: Node): void; + getRangeAt(index: number): Range; + collapse(parentNode: Node, offset: number): void; + removeAllRanges(): void; + collapseToStart(): void; + deleteFromDocument(): void; + removeRange(range: Range): void; +} +declare var Selection: { + prototype: Selection; + new(): Selection; +} + +interface SVGAnimatedAngle { + animVal: SVGAngle; + baseVal: SVGAngle; +} +declare var SVGAnimatedAngle: { + prototype: SVGAnimatedAngle; + new(): SVGAnimatedAngle; +} + +interface SVGPatternElement extends SVGElement, SVGUnitTypes, SVGStylable, SVGLangSpace, SVGTests, SVGFitToViewBox, SVGURIReference { + patternUnits: SVGAnimatedEnumeration; + y: SVGAnimatedLength; + width: SVGAnimatedLength; + x: SVGAnimatedLength; + patternContentUnits: SVGAnimatedEnumeration; + patternTransform: SVGAnimatedTransformList; + height: SVGAnimatedLength; +} +declare var SVGPatternElement: { + prototype: SVGPatternElement; + new(): SVGPatternElement; +} + +interface SVGScriptElement extends SVGElement, SVGURIReference { + type: string; +} +declare var SVGScriptElement: { + prototype: SVGScriptElement; + new(): SVGScriptElement; +} + +interface HTMLDDElement extends HTMLElement, DOML2DeprecatedWordWrapSuppression_HTMLDDElement { +} +declare var HTMLDDElement: { + prototype: HTMLDDElement; + new(): HTMLDDElement; +} + +interface NodeIterator { + whatToShow: number; + filter: NodeFilterCallback; + root: Node; + expandEntityReferences: bool; + nextNode(): Node; + detach(): void; + previousNode(): Node; +} +declare var NodeIterator: { + prototype: NodeIterator; + new(): NodeIterator; +} + +interface CSSStyleRule extends CSSRule, MSCSSStyleRuleExtensions { + selectorText: string; + style: MSStyleCSSProperties; +} +declare var CSSStyleRule: { + prototype: CSSStyleRule; + new(): CSSStyleRule; +} + +interface MSDataBindingRecordSetReadonlyExtensions { + recordset: Object; + namedRecordset(dataMember: string, hierarchy?: any): Object; +} + +interface HTMLLinkElement extends HTMLElement, MSLinkStyleExtensions, LinkStyle { + rel: string; + target: string; + href: string; + media: string; + rev: string; + type: string; + charset: string; + hreflang: string; +} +declare var HTMLLinkElement: { + prototype: HTMLLinkElement; + new(): HTMLLinkElement; +} + +interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { + viewTarget: SVGStringList; +} +declare var SVGViewElement: { + prototype: SVGViewElement; + new(): SVGViewElement; +} + +interface MSHTMLAppletElementExtensions extends DOML2DeprecatedBorderStyle_HTMLObjectElement { + codeType: string; + standby: string; + classid: string; + useMap: string; + form: HTMLFormElement; + data: string; + contentDocument: Document; + altHtml: string; + declare: bool; + type: string; + BaseHref: string; +} + +interface SVGLocatable { + farthestViewportElement: SVGElement; + nearestViewportElement: SVGElement; + getBBox(): SVGRect; + getTransformToElement(element: SVGElement): SVGMatrix; + getCTM(): SVGMatrix; + getScreenCTM(): SVGMatrix; +} + +interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, MSHTMLFontElementExtensions, DOML2DeprecatedSizeProperty { + face: string; +} +declare var HTMLFontElement: { + prototype: HTMLFontElement; + new(): HTMLFontElement; +} + +interface MSHTMLTableElementExtensions { + cells: HTMLCollection; + height: any; + cols: number; + moveRow(indexFrom?: number, indexTo?: number): Object; +} + +interface SVGTitleElement extends SVGElement, SVGStylable, SVGLangSpace { +} +declare var SVGTitleElement: { + prototype: SVGTitleElement; + new(): SVGTitleElement; +} + +interface ControlRangeCollection { + length: number; + queryCommandValue(cmdID: string): any; + remove(index: number): void; + add(item: Element): void; + queryCommandIndeterm(cmdID: string): bool; + scrollIntoView(varargStart?: any): void; + item(index: number): Element; + [index: number]: Element; + execCommand(cmdID: string, showUI?: bool, value?: any): bool; + addElement(item: Element): void; + queryCommandState(cmdID: string): bool; + queryCommandSupported(cmdID: string): bool; + queryCommandEnabled(cmdID: string): bool; + queryCommandText(cmdID: string): string; + select(): void; +} +declare var ControlRangeCollection: { + prototype: ControlRangeCollection; + new(): ControlRangeCollection; +} + +interface DOML2DeprecatedAlignmentStyle_HTMLImageElement { + align: string; +} + +interface MSHTMLFrameElementExtensions { + width: any; + contentWindow: Window; + onload: (ev: Event) => any; + frameBorder: string; + height: any; + border: string; + frameSpacing: any; +} + +interface MSNamespaceInfo extends MSEventAttachmentTarget { + urn: string; + onreadystatechange: (ev: Event) => any; + name: string; + readyState: string; + doImport(implementationUrl: string): void; +} +declare var MSNamespaceInfo: { + prototype: MSNamespaceInfo; + new(): MSNamespaceInfo; +} + +interface WindowSessionStorage { + sessionStorage: Storage; +} + +interface SVGAnimatedTransformList { + animVal: SVGTransformList; + baseVal: SVGTransformList; +} +declare var SVGAnimatedTransformList: { + prototype: SVGAnimatedTransformList; + new(): SVGAnimatedTransformList; +} + +interface HTMLTableCaptionElement extends HTMLElement, MSHTMLTableCaptionElementExtensions, DOML2DeprecatedAlignmentStyle_HTMLTableCaptionElement { +} +declare var HTMLTableCaptionElement: { + prototype: HTMLTableCaptionElement; + new(): HTMLTableCaptionElement; +} + +interface HTMLOptionElement extends HTMLElement, MSDataBindingExtensions { + index: number; + defaultSelected: bool; + value: string; + text: string; + form: HTMLFormElement; + label: string; + selected: bool; +} +declare var HTMLOptionElement: { + prototype: HTMLOptionElement; + new(): HTMLOptionElement; +} + +interface HTMLMapElement extends HTMLElement { + name: string; + areas: HTMLAreasCollection; +} +declare var HTMLMapElement: { + prototype: HTMLMapElement; + new(): HTMLMapElement; +} + +interface HTMLMenuElement extends HTMLElement, DOML2DeprecatedListSpaceReduction, MSHTMLMenuElementExtensions { + type: string; +} +declare var HTMLMenuElement: { + prototype: HTMLMenuElement; + new(): HTMLMenuElement; +} + +interface MouseWheelEvent extends MouseEvent { + wheelDelta: number; + initMouseWheelEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, buttonArg: number, relatedTargetArg: EventTarget, modifiersListArg: string, wheelDeltaArg: number): void; +} +declare var MouseWheelEvent: { + prototype: MouseWheelEvent; + new(): MouseWheelEvent; +} + +interface SVGFitToViewBox { + viewBox: SVGAnimatedRect; + preserveAspectRatio: SVGAnimatedPreserveAspectRatio; +} + +interface MSHTMLAnchorElementExtensions { + nameProp: string; + protocolLong: string; + urn: string; + mimeType: string; + Methods: string; +} + +interface SVGPointList { + numberOfItems: number; + replaceItem(newItem: SVGPoint, index: number): SVGPoint; + getItem(index: number): SVGPoint; + clear(): void; + appendItem(newItem: SVGPoint): SVGPoint; + initialize(newItem: SVGPoint): SVGPoint; + removeItem(index: number): SVGPoint; + insertItemBefore(newItem: SVGPoint, index: number): SVGPoint; +} +declare var SVGPointList: { + prototype: SVGPointList; + new(): SVGPointList; +} + +interface MSElementCSSInlineStyleExtensions { + doScroll(component?: any): void; + componentFromPoint(x: number, y: number): string; +} + +interface SVGAnimatedLengthList { + animVal: SVGLengthList; + baseVal: SVGLengthList; +} +declare var SVGAnimatedLengthList: { + prototype: SVGAnimatedLengthList; + new(): SVGAnimatedLengthList; +} + +interface MSHTMLTableDataCellElementExtensions { +} + +interface Window extends ViewCSS, MSEventAttachmentTarget, MSWindowExtensions, WindowPerformance, ScreenView, EventTarget, WindowLocalStorage, WindowSessionStorage, WindowTimers { + ondragend: (ev: DragEvent) => any; + onkeydown: (ev: KeyboardEvent) => any; + ondragover: (ev: DragEvent) => any; + onkeyup: (ev: KeyboardEvent) => any; + onreset: (ev: Event) => any; + onmouseup: (ev: MouseEvent) => any; + ondragstart: (ev: DragEvent) => any; + ondrag: (ev: DragEvent) => any; + onmouseover: (ev: MouseEvent) => any; + ondragleave: (ev: DragEvent) => any; + history: History; + name: string; + onafterprint: (ev: Event) => any; + onpause: (ev: Event) => any; + onbeforeprint: (ev: Event) => any; + top: Window; + onmousedown: (ev: MouseEvent) => any; + onseeked: (ev: Event) => any; + opener: Window; + onclick: (ev: MouseEvent) => any; + onwaiting: (ev: Event) => any; + ononline: (ev: Event) => any; + ondurationchange: (ev: Event) => any; + frames: Window; + onblur: (ev: FocusEvent) => any; + onemptied: (ev: Event) => any; + onseeking: (ev: Event) => any; + oncanplay: (ev: Event) => any; + onstalled: (ev: Event) => any; + onmousemove: (ev: MouseEvent) => any; + onoffline: (ev: Event) => any; + length: number; + onbeforeunload: (ev: BeforeUnloadEvent) => any; + onratechange: (ev: Event) => any; + onstorage: (ev: StorageEvent) => any; + onloadstart: (ev: Event) => any; + ondragenter: (ev: DragEvent) => any; + onsubmit: (ev: Event) => any; + self: Window; + onprogress: (ev: any) => any; + ondblclick: (ev: MouseEvent) => any; + oncontextmenu: (ev: MouseEvent) => any; + onchange: (ev: Event) => any; + onloadedmetadata: (ev: Event) => any; + onplay: (ev: Event) => any; + onerror: ErrorFunction; + onplaying: (ev: Event) => any; + parent: Window; + location: Location; + oncanplaythrough: (ev: Event) => any; + onabort: (ev: UIEvent) => any; + onreadystatechange: (ev: Event) => any; + onkeypress: (ev: KeyboardEvent) => any; + frameElement: Element; + onloadeddata: (ev: Event) => any; + onsuspend: (ev: Event) => any; + window: Window; + onfocus: (ev: FocusEvent) => any; + onmessage: (ev: MessageEvent) => any; + ontimeupdate: (ev: Event) => any; + onresize: (ev: UIEvent) => any; + navigator: Navigator; + onselect: (ev: UIEvent) => any; + ondrop: (ev: DragEvent) => any; + onmouseout: (ev: MouseEvent) => any; + onended: (ev: Event) => any; + onhashchange: (ev: Event) => any; + onunload: (ev: Event) => any; + onscroll: (ev: UIEvent) => any; + onmousewheel: (ev: MouseWheelEvent) => any; + onload: (ev: Event) => any; + onvolumechange: (ev: Event) => any; + oninput: (ev: Event) => any; + alert(message?: string): void; + focus(): void; + print(): void; + prompt(message?: string, defaul?: string): string; + toString(): string; + open(url?: string, target?: string, features?: string, replace?: bool): Window; + close(): void; + confirm(message?: string): bool; + postMessage(message: any, targetOrigin: string, ports?: any): void; + showModalDialog(url?: string, argument?: any, options?: any): any; + blur(): void; + getSelection(): Selection; +} +declare var Window: { + prototype: Window; + new(): Window; +} + +interface SVGAnimatedPreserveAspectRatio { + animVal: SVGPreserveAspectRatio; + baseVal: SVGPreserveAspectRatio; +} +declare var SVGAnimatedPreserveAspectRatio: { + prototype: SVGAnimatedPreserveAspectRatio; + new(): SVGAnimatedPreserveAspectRatio; +} + +interface MSSiteModeEvent extends Event { + buttonID: number; + actionURL: string; +} +declare var MSSiteModeEvent: { + prototype: MSSiteModeEvent; + new(): MSSiteModeEvent; +} + +interface MSCSSStyleRuleExtensions { + readOnly: bool; +} + +interface StyleSheetPageList { + length: number; + item(index: number): StyleSheetPage; + [index: number]: StyleSheetPage; +} +declare var StyleSheetPageList: { + prototype: StyleSheetPageList; + new(): StyleSheetPageList; +} + +interface HTMLCollection extends MSHTMLCollectionExtensions { + length: number; + item(nameOrIndex?: any, optionalIndex?: any): Element; + (nameOrIndex: any, optionalIndex: any): Element; + namedItem(name: string): Element; + [index: number]: Element; + [name: string]: Element; + (name: string): Element; +} +declare var HTMLCollection: { + prototype: HTMLCollection; + new(): HTMLCollection; +} + +interface MSCSSProperties extends CSSStyleDeclaration, MSCSSStyleDeclarationExtensions { + scrollbarShadowColor: string; + scrollbarHighlightColor: string; + layoutGridChar: string; + layoutGridType: string; + textAutospace: string; + textKashidaSpace: string; + writingMode: string; + scrollbarFaceColor: string; + backgroundPositionY: string; + lineBreak: string; + imeMode: string; + msBlockProgression: string; + layoutGridLine: string; + scrollbarBaseColor: string; + layoutGrid: string; + layoutFlow: string; + textKashida: string; + filter: string; + zoom: string; + scrollbarArrowColor: string; + behavior: string; + backgroundPositionX: string; + accelerator: string; + layoutGridMode: string; + textJustifyTrim: string; + scrollbar3dLightColor: string; + msInterpolationMode: string; + scrollbarTrackColor: string; + scrollbarDarkShadowColor: string; + styleFloat: string; +} +declare var MSCSSProperties: { + prototype: MSCSSProperties; + new(): MSCSSProperties; +} + +interface HTMLImageElement extends HTMLElement, DOML2DeprecatedMarginStyle, DOML2DeprecatedBorderStyle, DOML2DeprecatedAlignmentStyle_HTMLImageElement, MSImageResourceExtensions, MSHTMLImageElementExtensions, MSDataBindingExtensions, MSResourceMetadata { + width: number; + naturalHeight: number; + alt: string; + src: string; + useMap: string; + naturalWidth: number; + name: string; + height: number; + longDesc: string; + isMap: bool; + complete: bool; +} +declare var HTMLImageElement: { + prototype: HTMLImageElement; + new(): HTMLImageElement; +} + +interface HTMLAreaElement extends HTMLElement, MSHTMLAreaElementExtensions { + protocol: string; + search: string; + alt: string; + coords: string; + hostname: string; + port: string; + pathname: string; + host: string; + hash: string; + target: string; + href: string; + noHref: bool; + shape: string; + toString(): string; +} +declare var HTMLAreaElement: { + prototype: HTMLAreaElement; + new(): HTMLAreaElement; +} + +interface EventTarget { + removeEventListener(type: string, listener: EventListener, useCapture?: bool): void; + addEventListener(type: string, listener: EventListener, useCapture?: bool): void; + dispatchEvent(evt: Event): bool; +} + +interface SVGAngle { + valueAsString: string; + valueInSpecifiedUnits: number; + value: number; + unitType: number; + newValueSpecifiedUnits(unitType: number, valueInSpecifiedUnits: number): void; + convertToSpecifiedUnits(unitType: number): void; + SVG_ANGLETYPE_RAD: number; + SVG_ANGLETYPE_UNKNOWN: number; + SVG_ANGLETYPE_UNSPECIFIED: number; + SVG_ANGLETYPE_DEG: number; + SVG_ANGLETYPE_GRAD: number; +} +declare var SVGAngle: { + prototype: SVGAngle; + new(): SVGAngle; + SVG_ANGLETYPE_RAD: number; + SVG_ANGLETYPE_UNKNOWN: number; + SVG_ANGLETYPE_UNSPECIFIED: number; + SVG_ANGLETYPE_DEG: number; + SVG_ANGLETYPE_GRAD: number; +} + +interface HTMLButtonElement extends HTMLElement, MSHTMLButtonElementExtensions, MSDataBindingExtensions { + value: string; + form: HTMLFormElement; + name: string; + type: string; +} +declare var HTMLButtonElement: { + prototype: HTMLButtonElement; + new(): HTMLButtonElement; +} + +interface MSHTMLLabelElementExtensions { +} + +interface HTMLSourceElement extends HTMLElement { + src: string; + media: string; + type: string; +} +declare var HTMLSourceElement: { + prototype: HTMLSourceElement; + new(): HTMLSourceElement; +} + +interface CanvasGradient { + addColorStop(offset: number, color: string): void; +} +declare var CanvasGradient: { + prototype: CanvasGradient; + new(): CanvasGradient; +} + +interface KeyboardEvent extends UIEvent, KeyboardEventExtensions { + location: number; + shiftKey: bool; + locale: string; + key: string; + altKey: bool; + metaKey: bool; + char: string; + ctrlKey: bool; + repeat: bool; + getModifierState(keyArg: string): bool; + initKeyboardEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, keyArg: string, locationArg: number, modifiersListArg: string, repeat: bool, locale: string): void; + DOM_KEY_LOCATION_RIGHT: number; + DOM_KEY_LOCATION_STANDARD: number; + DOM_KEY_LOCATION_LEFT: number; + DOM_KEY_LOCATION_NUMPAD: number; + DOM_KEY_LOCATION_JOYSTICK: number; + DOM_KEY_LOCATION_MOBILE: number; +} +declare var KeyboardEvent: { + prototype: KeyboardEvent; + new(): KeyboardEvent; + DOM_KEY_LOCATION_RIGHT: number; + DOM_KEY_LOCATION_STANDARD: number; + DOM_KEY_LOCATION_LEFT: number; + DOM_KEY_LOCATION_NUMPAD: number; + DOM_KEY_LOCATION_JOYSTICK: number; + DOM_KEY_LOCATION_MOBILE: number; +} + +interface Document extends Node, DocumentStyle, DocumentRange, HTMLDocument, NodeSelector, DocumentEvent, DocumentTraversal, DocumentView, SVGDocument { + doctype: DocumentType; + xmlVersion: string; + implementation: DOMImplementation; + xmlEncoding: string; + xmlStandalone: bool; + documentElement: HTMLElement; + inputEncoding: string; + createElement(tagName: string): HTMLElement; + adoptNode(source: Node): Node; + createComment(data: string): Comment; + createDocumentFragment(): DocumentFragment; + getElementsByTagName(tagname: string): NodeList; + getElementsByTagNameNS(namespaceURI: string, localName: string): NodeList; + createProcessingInstruction(target: string, data: string): ProcessingInstruction; + createElementNS(namespaceURI: string, qualifiedName: string): Element; + createAttribute(name: string): Attr; + createTextNode(data: string): Text; + importNode(importedNode: Node, deep: bool): Node; + createCDATASection(data: string): CDATASection; + createAttributeNS(namespaceURI: string, qualifiedName: string): Attr; + getElementById(elementId: string): HTMLElement; +} +declare var Document: { + prototype: Document; + new(): Document; +} + +interface MessageEvent extends Event { + source: Window; + origin: string; + data: any; + initMessageEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: Window): void; +} +declare var MessageEvent: { + prototype: MessageEvent; + new(): MessageEvent; +} + +interface SVGElement extends Element, SVGElementEventHandlers { + xmlbase: string; + viewportElement: SVGElement; + id: string; + ownerSVGElement: SVGSVGElement; +} +declare var SVGElement: { + prototype: SVGElement; + new(): SVGElement; +} + +interface HTMLScriptElement extends HTMLElement { + defer: bool; + text: string; + src: string; + htmlFor: string; + charset: string; + type: string; + event: string; +} +declare var HTMLScriptElement: { + prototype: HTMLScriptElement; + new(): HTMLScriptElement; +} + +interface MSHTMLBodyElementExtensions extends DOML2DeprecatedWordWrapSuppression_HTMLBodyElement { + scroll: string; + bottomMargin: any; + topMargin: any; + rightMargin: any; + bgProperties: string; + leftMargin: any; + createTextRange(): TextRange; +} + +interface HTMLTableRowElement extends HTMLElement, MSBorderColorHighlightStyle_HTMLTableRowElement, HTMLTableAlignment, MSBorderColorStyle_HTMLTableRowElement, DOML2DeprecatedAlignmentStyle_HTMLTableRowElement, DOML2DeprecatedBackgroundColorStyle, MSHTMLTableRowElementExtensions { + rowIndex: number; + cells: HTMLCollection; + sectionRowIndex: number; + deleteCell(index?: number): void; + insertCell(index?: number): HTMLElement; +} +declare var HTMLTableRowElement: { + prototype: HTMLTableRowElement; + new(): HTMLTableRowElement; +} + +interface MSCommentExtensions { + text: string; +} + +interface DOML2DeprecatedMarginStyle_HTMLMarqueeElement { + vspace: number; + hspace: number; +} + +interface MSCSSRuleList { + length: number; + item(index?: number): CSSStyleRule; + [index: number]: CSSStyleRule; +} +declare var MSCSSRuleList: { + prototype: MSCSSRuleList; + new(): MSCSSRuleList; +} + +interface CanvasRenderingContext2D { + shadowOffsetX: number; + lineWidth: number; + miterLimit: number; + canvas: HTMLCanvasElement; + strokeStyle: any; + font: string; + globalAlpha: number; + globalCompositeOperation: string; + shadowOffsetY: number; + fillStyle: any; + lineCap: string; + shadowBlur: number; + textAlign: string; + textBaseline: string; + shadowColor: string; + lineJoin: string; + restore(): void; + setTransform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; + save(): void; + arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: bool): void; + measureText(text: string): TextMetrics; + isPointInPath(x: number, y: number): bool; + quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void; + putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void; + rotate(angle: number): void; + fillText(text: string, x: number, y: number, maxWidth?: number): void; + translate(x: number, y: number): void; + scale(x: number, y: number): void; + createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient; + lineTo(x: number, y: number): void; + fill(): void; + createPattern(image: HTMLElement, repetition: string): CanvasPattern; + closePath(): void; + rect(x: number, y: number, w: number, h: number): void; + clip(): void; + createImageData(imageDataOrSw: any, sh?: number): ImageData; + clearRect(x: number, y: number, w: number, h: number): void; + moveTo(x: number, y: number): void; + getImageData(sx: number, sy: number, sw: number, sh: number): ImageData; + fillRect(x: number, y: number, w: number, h: number): void; + bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void; + drawImage(image: HTMLElement, offsetX: number, offsetY: number, width?: number, height?: number, canvasOffsetX?: number, canvasOffsetY?: number, canvasImageWidth?: number, canvasImageHeight?: number): void; + transform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; + stroke(): void; + strokeRect(x: number, y: number, w: number, h: number): void; + strokeText(text: string, x: number, y: number, maxWidth?: number): void; + beginPath(): void; + arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void; + createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; +} +declare var CanvasRenderingContext2D: { + prototype: CanvasRenderingContext2D; + new(): CanvasRenderingContext2D; +} + +interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { + x: number; +} +declare var SVGPathSegLinetoHorizontalAbs: { + prototype: SVGPathSegLinetoHorizontalAbs; + new(): SVGPathSegLinetoHorizontalAbs; +} + +interface DOML2DeprecatedAlignmentStyle_HTMLObjectElement { + align: string; +} + +interface DOML2DeprecatedBorderStyle_MSHTMLIFrameElementExtensions { + border: string; +} + +interface MSHTMLElementRangeExtensions { + createControlRange(): ControlRangeCollection; +} + +interface SVGPathSegArcAbs extends SVGPathSeg { + y: number; + sweepFlag: bool; + r2: number; + x: number; + angle: number; + r1: number; + largeArcFlag: bool; +} +declare var SVGPathSegArcAbs: { + prototype: SVGPathSegArcAbs; + new(): SVGPathSegArcAbs; +} + +interface MSScreenExtensions { + deviceXDPI: number; + fontSmoothingEnabled: bool; + bufferDepth: number; + logicalXDPI: number; + systemXDPI: number; + logicalYDPI: number; + systemYDPI: number; + updateInterval: number; + deviceYDPI: number; +} + +interface HTMLHtmlElement extends HTMLElement, HTMLHtmlElementDOML2Deprecated { +} +declare var HTMLHtmlElement: { + prototype: HTMLHtmlElement; + new(): HTMLHtmlElement; +} + +interface MSBorderColorStyle { + borderColor: any; +} + +interface SVGTransformList { + numberOfItems: number; + getItem(index: number): SVGTransform; + consolidate(): SVGTransform; + clear(): void; + appendItem(newItem: SVGTransform): SVGTransform; + initialize(newItem: SVGTransform): SVGTransform; + removeItem(index: number): SVGTransform; + insertItemBefore(newItem: SVGTransform, index: number): SVGTransform; + replaceItem(newItem: SVGTransform, index: number): SVGTransform; + createSVGTransformFromMatrix(matrix: SVGMatrix): SVGTransform; +} +declare var SVGTransformList: { + prototype: SVGTransformList; + new(): SVGTransformList; +} + +interface SVGPathSegClosePath extends SVGPathSeg { +} +declare var SVGPathSegClosePath: { + prototype: SVGPathSegClosePath; + new(): SVGPathSegClosePath; +} + +interface DOML2DeprecatedMarginStyle_MSHTMLIFrameElementExtensions { + vspace: number; + hspace: number; +} + +interface HTMLFrameElement extends HTMLElement, GetSVGDocument, MSHTMLFrameElementExtensions, MSDataBindingExtensions, MSBorderColorStyle_HTMLFrameElement { + scrolling: string; + marginHeight: string; + src: string; + name: string; + marginWidth: string; + contentDocument: Document; + longDesc: string; + noResize: bool; +} +declare var HTMLFrameElement: { + prototype: HTMLFrameElement; + new(): HTMLFrameElement; +} + +interface SVGAnimatedLength { + animVal: SVGLength; + baseVal: SVGLength; +} +declare var SVGAnimatedLength: { + prototype: SVGAnimatedLength; + new(): SVGAnimatedLength; +} + +interface CSSMediaRule extends CSSRule { + media: MediaList; + cssRules: CSSRuleList; + insertRule(rule: string, index?: number): number; + deleteRule(index?: number): void; +} +declare var CSSMediaRule: { + prototype: CSSMediaRule; + new(): CSSMediaRule; +} + +interface HTMLQuoteElement extends HTMLElement, MSHTMLQuoteElementExtensions { + cite: string; +} +declare var HTMLQuoteElement: { + prototype: HTMLQuoteElement; + new(): HTMLQuoteElement; +} + +interface SVGDefsElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests { +} +declare var SVGDefsElement: { + prototype: SVGDefsElement; + new(): SVGDefsElement; +} + +interface SVGAnimatedPoints { + points: SVGPointList; + animatedPoints: SVGPointList; +} + +interface WindowModal { + dialogArguments: any; + returnValue: any; +} + +interface MSHTMLButtonElementExtensions { + status: any; + createTextRange(): TextRange; +} + +interface XMLHttpRequest extends EventTarget, MSXMLHttpRequestExtensions { + onreadystatechange: (ev: Event) => any; + status: number; + onload: (ev: Event) => any; + readyState: number; + responseText: string; + responseXML: Document; + statusText: string; + open(method: string, url: string, async?: bool, user?: string, password?: string): void; + send(data?: any): void; + abort(): void; + getAllResponseHeaders(): string; + setRequestHeader(header: string, value: string): void; + getResponseHeader(header: string): string; + LOADING: number; + DONE: number; + UNSENT: number; + OPENED: number; + HEADERS_RECEIVED: number; +} +declare var XMLHttpRequest: { + prototype: XMLHttpRequest; + new (): XMLHttpRequest; + LOADING: number; + DONE: number; + UNSENT: number; + OPENED: number; + HEADERS_RECEIVED: number; +} + +interface HTMLTableHeaderCellElement extends HTMLTableCellElement, HTMLTableHeaderCellScope { +} +declare var HTMLTableHeaderCellElement: { + prototype: HTMLTableHeaderCellElement; + new(): HTMLTableHeaderCellElement; +} + +interface HTMLDListElement extends HTMLElement, DOML2DeprecatedListSpaceReduction, MSHTMLDListElementExtensions { +} +declare var HTMLDListElement: { + prototype: HTMLDListElement; + new(): HTMLDListElement; +} + +interface MSDataBindingExtensions { + dataSrc: string; + dataFormatAs: string; + dataFld: string; +} + +interface SVGEllipseElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests { + ry: SVGAnimatedLength; + cx: SVGAnimatedLength; + rx: SVGAnimatedLength; + cy: SVGAnimatedLength; +} +declare var SVGEllipseElement: { + prototype: SVGEllipseElement; + new(): SVGEllipseElement; +} + +interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { + x: number; +} +declare var SVGPathSegLinetoHorizontalRel: { + prototype: SVGPathSegLinetoHorizontalRel; + new(): SVGPathSegLinetoHorizontalRel; +} + +interface SVGAElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests, SVGURIReference { + target: SVGAnimatedString; +} +declare var SVGAElement: { + prototype: SVGAElement; + new(): SVGAElement; +} + +interface MSHTMLMetaElementExtensions { + url: string; + charset: string; +} + +interface SVGStylable { + className: SVGAnimatedString; + style: CSSStyleDeclaration; +} + +interface MSHTMLTableCellElementExtensions { +} + +interface HTMLFrameSetElement extends HTMLElement, MSHTMLFrameSetElementExtensions, MSBorderColorStyle_HTMLFrameSetElement { + onresize: (ev: UIEvent) => any; + ononline: (ev: Event) => any; + onafterprint: (ev: Event) => any; + onbeforeprint: (ev: Event) => any; + onoffline: (ev: Event) => any; + rows: string; + cols: string; + onblur: (ev: FocusEvent) => any; + onunload: (ev: Event) => any; + onhashchange: (ev: Event) => any; + onfocus: (ev: FocusEvent) => any; + onmessage: (ev: MessageEvent) => any; + onload: (ev: Event) => any; + onerror: (ev: Event) => any; + onbeforeunload: (ev: BeforeUnloadEvent) => any; + onstorage: (ev: StorageEvent) => any; +} +declare var HTMLFrameSetElement: { + prototype: HTMLFrameSetElement; + new(): HTMLFrameSetElement; +} + +interface SVGTransformable extends SVGLocatable { + transform: SVGAnimatedTransformList; +} + +interface Screen extends MSScreenExtensions { + width: number; + colorDepth: number; + availWidth: number; + pixelDepth: number; + availHeight: number; + height: number; +} +declare var Screen: { + prototype: Screen; + new(): Screen; +} + +interface NavigatorGeolocation { + geolocation: Geolocation; +} + +interface Coordinates { + altitudeAccuracy: number; + longitude: number; + latitude: number; + speed: number; + heading: number; + altitude: number; + accuracy: number; +} +declare var Coordinates: { + prototype: Coordinates; + new(): Coordinates; +} + +interface DOML2DeprecatedAlignmentStyle_HTMLTableColElement { + align: string; +} + +interface EventListener { + (evt: Event): void; +} + +interface SVGLangSpace { + xmllang: string; + xmlspace: string; +} + +interface DataTransfer { + effectAllowed: string; + dropEffect: string; + clearData(format?: string): bool; + setData(format: string, data: string): bool; + getData(format: string): string; +} +declare var DataTransfer: { + prototype: DataTransfer; + new(): DataTransfer; +} + +interface FocusEvent extends UIEvent { + relatedTarget: EventTarget; + initFocusEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, detailArg: number, relatedTargetArg: EventTarget): void; +} +declare var FocusEvent: { + prototype: FocusEvent; + new(): FocusEvent; +} + +interface Range { + startOffset: number; + collapsed: bool; + endOffset: number; + startContainer: Node; + endContainer: Node; + commonAncestorContainer: Node; + setStart(refNode: Node, offset: number): void; + setEndBefore(refNode: Node): void; + setStartBefore(refNode: Node): void; + selectNode(refNode: Node): void; + detach(): void; + getBoundingClientRect(): ClientRect; + toString(): string; + compareBoundaryPoints(how: number, sourceRange: Range): number; + insertNode(newNode: Node): void; + collapse(toStart: bool): void; + selectNodeContents(refNode: Node): void; + cloneContents(): DocumentFragment; + setEnd(refNode: Node, offset: number): void; + cloneRange(): Range; + getClientRects(): ClientRectList; + surroundContents(newParent: Node): void; + deleteContents(): void; + setStartAfter(refNode: Node): void; + extractContents(): DocumentFragment; + setEndAfter(refNode: Node): void; + END_TO_END: number; + START_TO_START: number; + START_TO_END: number; + END_TO_START: number; +} +declare var Range: { + prototype: Range; + new(): Range; + END_TO_END: number; + START_TO_START: number; + START_TO_END: number; + END_TO_START: number; +} + +interface MSHTMLPreElementExtensions extends DOML2DeprecatedTextFlowControl_HTMLBlockElement { + cite: string; +} + +interface SVGPoint { + y: number; + x: number; + matrixTransform(matrix: SVGMatrix): SVGPoint; +} +declare var SVGPoint: { + prototype: SVGPoint; + new(): SVGPoint; +} + +interface MSPluginsCollection { + length: number; + refresh(reload?: bool): void; +} +declare var MSPluginsCollection: { + prototype: MSPluginsCollection; + new(): MSPluginsCollection; +} + +interface MSHTMLFontElementExtensions { +} + +interface SVGAnimatedNumberList { + animVal: SVGNumberList; + baseVal: SVGNumberList; +} +declare var SVGAnimatedNumberList: { + prototype: SVGAnimatedNumberList; + new(): SVGAnimatedNumberList; +} + +interface SVGSVGElement extends SVGElement, SVGZoomAndPan, SVGLangSpace, SVGLocatable, SVGTests, SVGFitToViewBox, SVGSVGElementEventHandlers, SVGStylable, DocumentEvent, ViewCSS_SVGSVGElement { + width: SVGAnimatedLength; + x: SVGAnimatedLength; + contentStyleType: string; + screenPixelToMillimeterY: number; + height: SVGAnimatedLength; + contentScriptType: string; + pixelUnitToMillimeterX: number; + currentTranslate: SVGPoint; + y: SVGAnimatedLength; + viewport: SVGRect; + currentScale: number; + screenPixelToMillimeterX: number; + pixelUnitToMillimeterY: number; + setCurrentTime(seconds: number): void; + createSVGLength(): SVGLength; + getIntersectionList(rect: SVGRect, referenceElement: SVGElement): NodeList; + unpauseAnimations(): void; + createSVGRect(): SVGRect; + checkIntersection(element: SVGElement, rect: SVGRect): bool; + unsuspendRedrawAll(): void; + pauseAnimations(): void; + suspendRedraw(maxWaitMilliseconds: number): number; + deselectAll(): void; + createSVGAngle(): SVGAngle; + getEnclosureList(rect: SVGRect, referenceElement: SVGElement): NodeList; + createSVGTransform(): SVGTransform; + unsuspendRedraw(suspendHandleID: number): void; + forceRedraw(): void; + getCurrentTime(): number; + checkEnclosure(element: SVGElement, rect: SVGRect): bool; + createSVGMatrix(): SVGMatrix; + createSVGPoint(): SVGPoint; + createSVGNumber(): SVGNumber; + createSVGTransformFromMatrix(matrix: SVGMatrix): SVGTransform; + getElementById(elementId: string): Element; +} +declare var SVGSVGElement: { + prototype: SVGSVGElement; + new(): SVGSVGElement; +} + +interface HTMLLabelElement extends HTMLElement, MSDataBindingExtensions, MSHTMLLabelElementExtensions { + htmlFor: string; + form: HTMLFormElement; +} +declare var HTMLLabelElement: { + prototype: HTMLLabelElement; + new(): HTMLLabelElement; +} + +interface MSResourceMetadata { + protocol: string; + fileSize: string; + fileUpdatedDate: string; + nameProp: string; + fileCreatedDate: string; + fileModifiedDate: string; + mimeType: string; +} + +interface MSHTMLQuoteElementExtensions { + dateTime: string; +} + +interface DOML2DeprecatedAlignmentStyle_HTMLIFrameElement { + align: string; +} + +interface HTMLLegendElement extends HTMLElement, DOML2DeprecatedAlignmentStyle_HTMLLegendElement, MSDataBindingExtensions, MSHTMLLegendElementExtensions { + form: HTMLFormElement; +} +declare var HTMLLegendElement: { + prototype: HTMLLegendElement; + new(): HTMLLegendElement; +} + +interface HTMLDirectoryElement extends HTMLElement, DOML2DeprecatedListSpaceReduction, MSHTMLDirectoryElementExtensions { +} +declare var HTMLDirectoryElement: { + prototype: HTMLDirectoryElement; + new(): HTMLDirectoryElement; +} + +interface NavigatorAbilities { +} + +interface MSHTMLImageElementExtensions { + href: string; +} + +interface SVGAnimatedInteger { + animVal: number; + baseVal: number; +} +declare var SVGAnimatedInteger: { + prototype: SVGAnimatedInteger; + new(): SVGAnimatedInteger; +} + +interface SVGTextElement extends SVGTextPositioningElement, SVGTransformable { +} +declare var SVGTextElement: { + prototype: SVGTextElement; + new(): SVGTextElement; +} + +interface SVGTSpanElement extends SVGTextPositioningElement { +} +declare var SVGTSpanElement: { + prototype: SVGTSpanElement; + new(): SVGTSpanElement; +} + +interface HTMLLIElement extends HTMLElement, DOML2DeprecatedListNumberingAndBulletStyle, MSHTMLLIElementExtensions { + value: number; +} +declare var HTMLLIElement: { + prototype: HTMLLIElement; + new(): HTMLLIElement; +} + +interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { + y: number; +} +declare var SVGPathSegLinetoVerticalAbs: { + prototype: SVGPathSegLinetoVerticalAbs; + new(): SVGPathSegLinetoVerticalAbs; +} + +interface ViewCSS { + getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; +} + +interface MSAttrExtensions { + expando: bool; +} + +interface MSStorageExtensions { + remainingSpace: number; +} + +interface SVGStyleElement extends SVGElement, SVGLangSpace { + media: string; + type: string; + title: string; +} +declare var SVGStyleElement: { + prototype: SVGStyleElement; + new(): SVGStyleElement; +} + +interface MSCurrentStyleCSSProperties extends MSCSSProperties { + blockDirection: string; + clipBottom: string; + clipLeft: string; + clipRight: string; + clipTop: string; + hasLayout: string; +} +declare var MSCurrentStyleCSSProperties: { + prototype: MSCurrentStyleCSSProperties; + new(): MSCurrentStyleCSSProperties; +} + +interface MSLinkStyleExtensions { + styleSheet: StyleSheet; +} + +interface MSHTMLCollectionExtensions { + urns(urn: any): Object; + tags(tagName: any): Object; +} + +interface DOML2DeprecatedWordWrapSuppression_HTMLDivElement { + noWrap: bool; +} + +interface DocumentTraversal { + createNodeIterator(root: Node, whatToShow: number, filter: NodeFilterCallback, entityReferenceExpansion: bool): NodeIterator; + createTreeWalker(root: Node, whatToShow: number, filter: NodeFilterCallback, entityReferenceExpansion: bool): TreeWalker; +} + +interface Storage extends MSStorageExtensions { + length: number; + getItem(key: string): any; + [key: string]: any; + setItem(key: string, data: string): void; + clear(): void; + removeItem(key: string): void; + key(index: number): string; + [index: number]: any; +} +declare var Storage: { + prototype: Storage; + new(): Storage; +} + +interface HTMLTableHeaderCellScope { + scope: string; +} + +interface HTMLIFrameElement extends HTMLElement, GetSVGDocument, MSHTMLIFrameElementExtensions, MSDataBindingExtensions, DOML2DeprecatedAlignmentStyle_HTMLIFrameElement { + width: string; + contentWindow: Window; + scrolling: string; + src: string; + marginHeight: string; + name: string; + marginWidth: string; + height: string; + contentDocument: Document; + longDesc: string; + frameBorder: string; +} +declare var HTMLIFrameElement: { + prototype: HTMLIFrameElement; + new(): HTMLIFrameElement; +} + +interface MSNavigatorAbilities { + userLanguage: string; + plugins: MSPluginsCollection; + cookieEnabled: bool; + appCodeName: string; + cpuClass: string; + appMinorVersion: string; + connectionSpeed: number; + browserLanguage: string; + mimeTypes: MSMimeTypesCollection; + product: string; + systemLanguage: string; + javaEnabled(): bool; + taintEnabled(): bool; +} + +interface TextRangeCollection { + length: number; + item(index: number): TextRange; + [index: number]: TextRange; +} +declare var TextRangeCollection: { + prototype: TextRangeCollection; + new(): TextRangeCollection; +} + +interface HTMLBodyElement extends HTMLElement, HTMLBodyElementDOML2Deprecated, MSHTMLBodyElementExtensions, DOML2DeprecatedBackgroundStyle, DOML2DeprecatedBackgroundColorStyle { + onresize: (ev: UIEvent) => any; + ononline: (ev: Event) => any; + onafterprint: (ev: Event) => any; + onbeforeprint: (ev: Event) => any; + onoffline: (ev: Event) => any; + onblur: (ev: FocusEvent) => any; + onhashchange: (ev: Event) => any; + onunload: (ev: Event) => any; + onfocus: (ev: FocusEvent) => any; + onmessage: (ev: MessageEvent) => any; + onload: (ev: Event) => any; + onerror: (ev: Event) => any; + onbeforeunload: (ev: BeforeUnloadEvent) => any; + onstorage: (ev: StorageEvent) => any; +} +declare var HTMLBodyElement: { + prototype: HTMLBodyElement; + new(): HTMLBodyElement; +} + +interface DocumentType extends Node { + name: string; + notations: NamedNodeMap; + systemId: string; + internalSubset: string; + entities: NamedNodeMap; + publicId: string; +} +declare var DocumentType: { + prototype: DocumentType; + new(): DocumentType; +} + +interface MSHTMLInputElementExtensions extends DOML2DeprecatedMarginStyle_HTMLInputElement, DOML2DeprecatedBorderStyle_HTMLInputElement { + status: bool; + complete: bool; + createTextRange(): TextRange; +} + +interface DOML2DeprecatedAlignmentStyle_HTMLLegendElement { + align: string; +} + +interface SVGRadialGradientElement extends SVGGradientElement { + cx: SVGAnimatedLength; + r: SVGAnimatedLength; + cy: SVGAnimatedLength; + fx: SVGAnimatedLength; + fy: SVGAnimatedLength; +} +declare var SVGRadialGradientElement: { + prototype: SVGRadialGradientElement; + new(): SVGRadialGradientElement; +} + +interface MutationEvent extends Event { + newValue: string; + attrChange: number; + attrName: string; + prevValue: string; + relatedNode: Node; + initMutationEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, relatedNodeArg: Node, prevValueArg: string, newValueArg: string, attrNameArg: string, attrChangeArg: number): void; + MODIFICATION: number; + REMOVAL: number; + ADDITION: number; +} +declare var MutationEvent: { + prototype: MutationEvent; + new(): MutationEvent; + MODIFICATION: number; + REMOVAL: number; + ADDITION: number; +} + +interface DragEvent extends MouseEvent { + dataTransfer: DataTransfer; + initDragEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: bool, altKeyArg: bool, shiftKeyArg: bool, metaKeyArg: bool, buttonArg: number, relatedTargetArg: EventTarget, dataTransferArg: DataTransfer): void; +} +declare var DragEvent: { + prototype: DragEvent; + new(): DragEvent; +} + +interface DOML2DeprecatedWidthStyle_HTMLTableCellElement { + width: number; +} + +interface HTMLTableSectionElement extends HTMLElement, MSHTMLTableSectionElementExtensions, DOML2DeprecatedAlignmentStyle_HTMLTableSectionElement, HTMLTableAlignment { + rows: HTMLCollection; + deleteRow(index?: number): void; + insertRow(index?: number): HTMLElement; +} +declare var HTMLTableSectionElement: { + prototype: HTMLTableSectionElement; + new(): HTMLTableSectionElement; +} + +interface DOML2DeprecatedListNumberingAndBulletStyle { + type: string; +} + +interface HTMLInputElement extends HTMLElement, DOML2DeprecatedAlignmentStyle_HTMLInputElement, MSImageResourceExtensions_HTMLInputElement, MSHTMLInputElementExtensions, MSDataBindingExtensions { + width: string; + defaultChecked: bool; + alt: string; + accept: string; + value: string; + src: string; + useMap: string; + name: string; + form: HTMLFormElement; + selectionStart: number; + height: string; + indeterminate: bool; + readOnly: bool; + size: number; + checked: bool; + maxLength: number; + selectionEnd: number; + type: string; + defaultValue: string; + setSelectionRange(start: number, end: number): void; + select(): void; +} +declare var HTMLInputElement: { + prototype: HTMLInputElement; + new(): HTMLInputElement; +} + +interface HTMLAnchorElement extends HTMLElement, MSHTMLAnchorElementExtensions, MSDataBindingExtensions { + rel: string; + protocol: string; + search: string; + coords: string; + hostname: string; + pathname: string; + target: string; + href: string; + name: string; + charset: string; + hreflang: string; + port: string; + host: string; + hash: string; + rev: string; + type: string; + shape: string; + toString(): string; +} +declare var HTMLAnchorElement: { + prototype: HTMLAnchorElement; + new(): HTMLAnchorElement; +} + +interface SVGImageElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests, SVGURIReference { + y: SVGAnimatedLength; + width: SVGAnimatedLength; + preserveAspectRatio: SVGAnimatedPreserveAspectRatio; + x: SVGAnimatedLength; + height: SVGAnimatedLength; +} +declare var SVGImageElement: { + prototype: SVGImageElement; + new(): SVGImageElement; +} + +interface MSElementExtensions { + msMatchesSelector(selectors: string): bool; + fireEvent(eventName: string, eventObj?: any): bool; +} + +interface HTMLParamElement extends HTMLElement { + value: string; + name: string; + type: string; + valueType: string; +} +declare var HTMLParamElement: { + prototype: HTMLParamElement; + new(): HTMLParamElement; +} + +interface MSHTMLDocumentViewExtensions { + createStyleSheet(href?: string, index?: number): CSSStyleSheet; +} + +interface SVGAnimatedNumber { + animVal: number; + baseVal: number; +} +declare var SVGAnimatedNumber: { + prototype: SVGAnimatedNumber; + new(): SVGAnimatedNumber; +} + +interface PerformanceTiming { + redirectStart: number; + domainLookupEnd: number; + responseStart: number; + domComplete: number; + domainLookupStart: number; + loadEventStart: number; + msFirstPaint: number; + unloadEventEnd: number; + fetchStart: number; + requestStart: number; + domInteractive: number; + navigationStart: number; + connectEnd: number; + loadEventEnd: number; + connectStart: number; + responseEnd: number; + domLoading: number; + redirectEnd: number; + unloadEventStart: number; + domContentLoadedEventStart: number; + domContentLoadedEventEnd: number; + toJSON(): any; +} +declare var PerformanceTiming: { + prototype: PerformanceTiming; + new(): PerformanceTiming; +} + +interface DOML2DeprecatedAlignmentStyle_HTMLInputElement { + align: string; +} + +interface HTMLPreElement extends HTMLElement, DOML2DeprecatedWidthStyle, MSHTMLPreElementExtensions { +} +declare var HTMLPreElement: { + prototype: HTMLPreElement; + new(): HTMLPreElement; +} + +interface EventException { + code: number; + message: string; + toString(): string; + DISPATCH_REQUEST_ERR: number; + UNSPECIFIED_EVENT_TYPE_ERR: number; +} +declare var EventException: { + prototype: EventException; + new(): EventException; + DISPATCH_REQUEST_ERR: number; + UNSPECIFIED_EVENT_TYPE_ERR: number; +} + +interface MSBorderColorHighlightStyle_HTMLTableCellElement { + borderColorLight: any; + borderColorDark: any; +} + +interface DOMHTMLImplementation { + createHTMLDocument(title: string): Document; +} + +interface NavigatorOnLine { + onLine: bool; +} + +interface SVGElementEventHandlers { + onmouseover: (ev: MouseEvent) => any; + onmousemove: (ev: MouseEvent) => any; + onmouseout: (ev: MouseEvent) => any; + ondblclick: (ev: MouseEvent) => any; + onfocusout: (ev: FocusEvent) => any; + onfocusin: (ev: FocusEvent) => any; + onmousedown: (ev: MouseEvent) => any; + onmouseup: (ev: MouseEvent) => any; + onload: (ev: Event) => any; + onclick: (ev: MouseEvent) => any; +} + +interface WindowLocalStorage { + localStorage: Storage; +} + +interface SVGMetadataElement extends SVGElement { +} +declare var SVGMetadataElement: { + prototype: SVGMetadataElement; + new(): SVGMetadataElement; +} + +interface SVGPathSegArcRel extends SVGPathSeg { + y: number; + sweepFlag: bool; + r2: number; + x: number; + angle: number; + r1: number; + largeArcFlag: bool; +} +declare var SVGPathSegArcRel: { + prototype: SVGPathSegArcRel; + new(): SVGPathSegArcRel; +} + +interface SVGPathSegMovetoAbs extends SVGPathSeg { + y: number; + x: number; +} +declare var SVGPathSegMovetoAbs: { + prototype: SVGPathSegMovetoAbs; + new(): SVGPathSegMovetoAbs; +} + +interface SVGStringList { + numberOfItems: number; + replaceItem(newItem: string, index: number): string; + getItem(index: number): string; + clear(): void; + appendItem(newItem: string): string; + initialize(newItem: string): string; + removeItem(index: number): string; + insertItemBefore(newItem: string, index: number): string; +} +declare var SVGStringList: { + prototype: SVGStringList; + new(): SVGStringList; +} + +interface XDomainRequest { + timeout: number; + onerror: (ev: Event) => any; + onload: (ev: Event) => any; + onprogress: (ev: any) => any; + ontimeout: (ev: Event) => any; + responseText: string; + contentType: string; + open(method: string, url: string): void; + abort(): void; + send(data?: any): void; +} +declare var XDomainRequest: { + prototype: XDomainRequest; + new (): XDomainRequest; +} + +interface DOML2DeprecatedBackgroundColorStyle { + bgColor: any; +} + +interface ElementTraversal { + childElementCount: number; + previousElementSibling: Element; + lastElementChild: Element; + nextElementSibling: Element; + firstElementChild: Element; +} + +interface SVGLength { + valueAsString: string; + valueInSpecifiedUnits: number; + value: number; + unitType: number; + newValueSpecifiedUnits(unitType: number, valueInSpecifiedUnits: number): void; + convertToSpecifiedUnits(unitType: number): void; + SVG_LENGTHTYPE_NUMBER: number; + SVG_LENGTHTYPE_CM: number; + SVG_LENGTHTYPE_PC: number; + SVG_LENGTHTYPE_PERCENTAGE: number; + SVG_LENGTHTYPE_MM: number; + SVG_LENGTHTYPE_PT: number; + SVG_LENGTHTYPE_IN: number; + SVG_LENGTHTYPE_EMS: number; + SVG_LENGTHTYPE_PX: number; + SVG_LENGTHTYPE_UNKNOWN: number; + SVG_LENGTHTYPE_EXS: number; +} +declare var SVGLength: { + prototype: SVGLength; + new(): SVGLength; + SVG_LENGTHTYPE_NUMBER: number; + SVG_LENGTHTYPE_CM: number; + SVG_LENGTHTYPE_PC: number; + SVG_LENGTHTYPE_PERCENTAGE: number; + SVG_LENGTHTYPE_MM: number; + SVG_LENGTHTYPE_PT: number; + SVG_LENGTHTYPE_IN: number; + SVG_LENGTHTYPE_EMS: number; + SVG_LENGTHTYPE_PX: number; + SVG_LENGTHTYPE_UNKNOWN: number; + SVG_LENGTHTYPE_EXS: number; +} + +interface SVGPolygonElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGAnimatedPoints, SVGTests { +} +declare var SVGPolygonElement: { + prototype: SVGPolygonElement; + new(): SVGPolygonElement; +} + +interface HTMLPhraseElement extends HTMLElement { + dateTime: string; + cite: string; +} +declare var HTMLPhraseElement: { + prototype: HTMLPhraseElement; + new(): HTMLPhraseElement; +} + +interface MSHTMLAreaElementExtensions { +} + +interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { + y: number; + y1: number; + x2: number; + x: number; + x1: number; + y2: number; +} +declare var SVGPathSegCurvetoCubicRel: { + prototype: SVGPathSegCurvetoCubicRel; + new(): SVGPathSegCurvetoCubicRel; +} + +interface MSEventObj { + nextPage: string; + keyCode: number; + toElement: Element; + returnValue: any; + dataFld: string; + y: number; + dataTransfer: DataTransfer; + propertyName: string; + url: string; + offsetX: number; + recordset: Object; + screenX: number; + buttonID: number; + wheelDelta: number; + reason: number; + origin: string; + data: string; + srcFilter: Object; + boundElements: HTMLCollection; + cancelBubble: bool; + altLeft: bool; + behaviorCookie: number; + bookmarks: BookmarkCollection; + type: string; + repeat: bool; + srcElement: Element; + source: Window; + fromElement: Element; + offsetY: number; + x: number; + behaviorPart: number; + qualifier: string; + altKey: bool; + ctrlKey: bool; + clientY: number; + shiftKey: bool; + shiftLeft: bool; + contentOverflow: bool; + screenY: number; + ctrlLeft: bool; + button: number; + srcUrn: string; + clientX: number; + actionURL: string; + getAttribute(strAttributeName: string, lFlags?: number): any; + setAttribute(strAttributeName: string, AttributeValue: any, lFlags?: number): void; + removeAttribute(strAttributeName: string, lFlags?: number): bool; +} +declare var MSEventObj: { + prototype: MSEventObj; + new(): MSEventObj; +} + +interface SVGTextContentElement extends SVGElement, SVGStylable, SVGLangSpace, SVGTests { + textLength: SVGAnimatedLength; + lengthAdjust: SVGAnimatedEnumeration; + getCharNumAtPosition(point: SVGPoint): number; + getStartPositionOfChar(charnum: number): SVGPoint; + getExtentOfChar(charnum: number): SVGRect; + getComputedTextLength(): number; + getSubStringLength(charnum: number, nchars: number): number; + selectSubString(charnum: number, nchars: number): void; + getNumberOfChars(): number; + getRotationOfChar(charnum: number): number; + getEndPositionOfChar(charnum: number): SVGPoint; + LENGTHADJUST_SPACING: number; + LENGTHADJUST_SPACINGANDGLYPHS: number; + LENGTHADJUST_UNKNOWN: number; +} +declare var SVGTextContentElement: { + prototype: SVGTextContentElement; + new(): SVGTextContentElement; + LENGTHADJUST_SPACING: number; + LENGTHADJUST_SPACINGANDGLYPHS: number; + LENGTHADJUST_UNKNOWN: number; +} + +interface DOML2DeprecatedColorProperty { + color: string; +} + +interface MSHTMLLIElementExtensions { +} + +interface HTMLCanvasElement extends HTMLElement { + width: number; + height: number; + toDataURL(): string; + toDataURL(type: string, ...args: any[]): string; + getContext(contextId: string): CanvasRenderingContext2D; +} +declare var HTMLCanvasElement: { + prototype: HTMLCanvasElement; + new(): HTMLCanvasElement; +} + +interface HTMLTitleElement extends HTMLElement { + text: string; +} +declare var HTMLTitleElement: { + prototype: HTMLTitleElement; + new(): HTMLTitleElement; +} + +interface Location { + hash: string; + protocol: string; + search: string; + href: string; + hostname: string; + port: string; + pathname: string; + host: string; + reload(flag?: bool): void; + replace(url: string): void; + assign(url: string): void; + toString(): string; +} +declare var Location: { + prototype: Location; + new(): Location; +} + +interface HTMLStyleElement extends HTMLElement, MSLinkStyleExtensions, LinkStyle { + media: string; + type: string; +} +declare var HTMLStyleElement: { + prototype: HTMLStyleElement; + new(): HTMLStyleElement; +} + +interface MSHTMLOptGroupElementExtensions { + index: number; + defaultSelected: bool; + text: string; + value: string; + form: HTMLFormElement; + selected: bool; +} + +interface MSBorderColorHighlightStyle { + borderColorLight: any; + borderColorDark: any; +} + +interface DOML2DeprecatedSizeProperty_HTMLBaseFontElement { + size: number; +} + +interface SVGTransform { + type: number; + angle: number; + matrix: SVGMatrix; + setTranslate(tx: number, ty: number): void; + setScale(sx: number, sy: number): void; + setMatrix(matrix: SVGMatrix): void; + setSkewY(angle: number): void; + setRotate(angle: number, cx: number, cy: number): void; + setSkewX(angle: number): void; + SVG_TRANSFORM_SKEWX: number; + SVG_TRANSFORM_UNKNOWN: number; + SVG_TRANSFORM_SCALE: number; + SVG_TRANSFORM_TRANSLATE: number; + SVG_TRANSFORM_MATRIX: number; + SVG_TRANSFORM_ROTATE: number; + SVG_TRANSFORM_SKEWY: number; +} +declare var SVGTransform: { + prototype: SVGTransform; + new(): SVGTransform; + SVG_TRANSFORM_SKEWX: number; + SVG_TRANSFORM_UNKNOWN: number; + SVG_TRANSFORM_SCALE: number; + SVG_TRANSFORM_TRANSLATE: number; + SVG_TRANSFORM_MATRIX: number; + SVG_TRANSFORM_ROTATE: number; + SVG_TRANSFORM_SKEWY: number; +} + +interface MSCSSFilter { + Percent: number; + Enabled: bool; + Duration: number; + Play(Duration: number): void; + Apply(): void; + Stop(): void; +} +declare var MSCSSFilter: { + prototype: MSCSSFilter; + new(): MSCSSFilter; +} + +interface UIEvent extends Event { + detail: number; + view: AbstractView; + initUIEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, detailArg: number): void; +} +declare var UIEvent: { + prototype: UIEvent; + new(): UIEvent; +} + +interface ViewCSS_SVGSVGElement { + getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; +} + +interface SVGURIReference { + href: SVGAnimatedString; +} + +interface SVGPathSeg { + pathSegType: number; + pathSegTypeAsLetter: string; + PATHSEG_MOVETO_REL: number; + PATHSEG_LINETO_VERTICAL_REL: number; + PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: number; + PATHSEG_CURVETO_QUADRATIC_REL: number; + PATHSEG_CURVETO_CUBIC_ABS: number; + PATHSEG_LINETO_HORIZONTAL_ABS: number; + PATHSEG_CURVETO_QUADRATIC_ABS: number; + PATHSEG_LINETO_ABS: number; + PATHSEG_CLOSEPATH: number; + PATHSEG_LINETO_HORIZONTAL_REL: number; + PATHSEG_CURVETO_CUBIC_SMOOTH_REL: number; + PATHSEG_LINETO_REL: number; + PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: number; + PATHSEG_ARC_REL: number; + PATHSEG_CURVETO_CUBIC_REL: number; + PATHSEG_UNKNOWN: number; + PATHSEG_LINETO_VERTICAL_ABS: number; + PATHSEG_ARC_ABS: number; + PATHSEG_MOVETO_ABS: number; + PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: number; +} +declare var SVGPathSeg: { + PATHSEG_MOVETO_REL: number; + PATHSEG_LINETO_VERTICAL_REL: number; + PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: number; + PATHSEG_CURVETO_QUADRATIC_REL: number; + PATHSEG_CURVETO_CUBIC_ABS: number; + PATHSEG_LINETO_HORIZONTAL_ABS: number; + PATHSEG_CURVETO_QUADRATIC_ABS: number; + PATHSEG_LINETO_ABS: number; + PATHSEG_CLOSEPATH: number; + PATHSEG_LINETO_HORIZONTAL_REL: number; + PATHSEG_CURVETO_CUBIC_SMOOTH_REL: number; + PATHSEG_LINETO_REL: number; + PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: number; + PATHSEG_ARC_REL: number; + PATHSEG_CURVETO_CUBIC_REL: number; + PATHSEG_UNKNOWN: number; + PATHSEG_LINETO_VERTICAL_ABS: number; + PATHSEG_ARC_ABS: number; + PATHSEG_MOVETO_ABS: number; + PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: number; +} + +interface WheelEvent extends MouseEvent { + deltaZ: number; + deltaX: number; + deltaMode: number; + deltaY: number; + initWheelEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, buttonArg: number, relatedTargetArg: EventTarget, modifiersListArg: string, deltaXArg: number, deltaYArg: number, deltaZArg: number, deltaMode: number): void; + DOM_DELTA_PIXEL: number; + DOM_DELTA_LINE: number; + DOM_DELTA_PAGE: number; +} +declare var WheelEvent: { + prototype: WheelEvent; + new(): WheelEvent; + DOM_DELTA_PIXEL: number; + DOM_DELTA_LINE: number; + DOM_DELTA_PAGE: number; +} + +interface DOML2DeprecatedAlignmentStyle_HTMLDivElement { + align: string; +} + +interface MSEventAttachmentTarget { + attachEvent(event: string, listener: EventListener): bool; + detachEvent(event: string, listener: EventListener): void; +} + +interface SVGNumber { + value: number; +} +declare var SVGNumber: { + prototype: SVGNumber; + new(): SVGNumber; +} + +interface SVGPathElement extends SVGElement, SVGStylable, SVGAnimatedPathData, SVGTransformable, SVGLangSpace, SVGTests { + getPathSegAtLength(distance: number): number; + getPointAtLength(distance: number): SVGPoint; + createSVGPathSegCurvetoQuadraticAbs(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticAbs; + createSVGPathSegLinetoRel(x: number, y: number): SVGPathSegLinetoRel; + createSVGPathSegCurvetoQuadraticRel(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticRel; + createSVGPathSegCurvetoCubicAbs(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicAbs; + createSVGPathSegLinetoAbs(x: number, y: number): SVGPathSegLinetoAbs; + createSVGPathSegClosePath(): SVGPathSegClosePath; + createSVGPathSegCurvetoCubicRel(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicRel; + createSVGPathSegCurvetoQuadraticSmoothRel(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothRel; + createSVGPathSegMovetoRel(x: number, y: number): SVGPathSegMovetoRel; + createSVGPathSegCurvetoCubicSmoothAbs(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothAbs; + createSVGPathSegMovetoAbs(x: number, y: number): SVGPathSegMovetoAbs; + createSVGPathSegLinetoVerticalRel(y: number): SVGPathSegLinetoVerticalRel; + createSVGPathSegArcRel(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: bool, sweepFlag: bool): SVGPathSegArcRel; + createSVGPathSegCurvetoQuadraticSmoothAbs(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothAbs; + createSVGPathSegLinetoHorizontalRel(x: number): SVGPathSegLinetoHorizontalRel; + getTotalLength(): number; + createSVGPathSegCurvetoCubicSmoothRel(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothRel; + createSVGPathSegLinetoHorizontalAbs(x: number): SVGPathSegLinetoHorizontalAbs; + createSVGPathSegLinetoVerticalAbs(y: number): SVGPathSegLinetoVerticalAbs; + createSVGPathSegArcAbs(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: bool, sweepFlag: bool): SVGPathSegArcAbs; +} +declare var SVGPathElement: { + prototype: SVGPathElement; + new(): SVGPathElement; +} + +interface MSCompatibleInfo { + version: string; + userAgent: string; +} +declare var MSCompatibleInfo: { + prototype: MSCompatibleInfo; + new(): MSCompatibleInfo; +} + +interface MSHTMLDocumentEventExtensions { + createEventObject(eventObj?: any): MSEventObj; + fireEvent(eventName: string, eventObj?: any): bool; +} + +interface Text extends CharacterData, MSNodeExtensions { + wholeText: string; + splitText(offset: number): Text; + replaceWholeText(content: string): Text; +} +declare var Text: { + prototype: Text; + new(): Text; +} + +interface SVGAnimatedRect { + animVal: SVGRect; + baseVal: SVGRect; +} +declare var SVGAnimatedRect: { + prototype: SVGAnimatedRect; + new(): SVGAnimatedRect; +} + +interface CSSNamespaceRule extends CSSRule { + namespaceURI: string; + prefix: string; +} +declare var CSSNamespaceRule: { + prototype: CSSNamespaceRule; + new(): CSSNamespaceRule; +} + +interface HTMLUnknownElement extends HTMLElement, MSDataBindingRecordSetReadonlyExtensions, MSHTMLUnknownElementExtensions { +} +declare var HTMLUnknownElement: { + prototype: HTMLUnknownElement; + new(): HTMLUnknownElement; +} + +interface SVGPathSegList { + numberOfItems: number; + replaceItem(newItem: SVGPathSeg, index: number): SVGPathSeg; + getItem(index: number): SVGPathSeg; + clear(): void; + appendItem(newItem: SVGPathSeg): SVGPathSeg; + initialize(newItem: SVGPathSeg): SVGPathSeg; + removeItem(index: number): SVGPathSeg; + insertItemBefore(newItem: SVGPathSeg, index: number): SVGPathSeg; +} +declare var SVGPathSegList: { + prototype: SVGPathSegList; + new(): SVGPathSegList; +} + +interface HTMLAudioElement extends HTMLMediaElement { +} +declare var HTMLAudioElement: { + prototype: HTMLAudioElement; + new(): HTMLAudioElement; +} + +interface MSImageResourceExtensions { + dynsrc: string; + vrml: string; + lowsrc: string; + start: string; + loop: number; +} + +interface MSBorderColorHighlightStyle_HTMLTableRowElement { + borderColorLight: any; + borderColorDark: any; +} + +interface PositionError { + code: number; + message: string; + toString(): string; + POSITION_UNAVAILABLE: number; + PERMISSION_DENIED: number; + TIMEOUT: number; +} +declare var PositionError: { + POSITION_UNAVAILABLE: number; + PERMISSION_DENIED: number; + TIMEOUT: number; +} + +interface BrowserPublic { +} +declare var BrowserPublic: { + prototype: BrowserPublic; + new(): BrowserPublic; +} + +interface HTMLTableCellElement extends HTMLElement, DOML2DeprecatedTableCellHeight, HTMLTableAlignment, MSBorderColorHighlightStyle_HTMLTableCellElement, DOML2DeprecatedWidthStyle_HTMLTableCellElement, DOML2DeprecatedBackgroundStyle, MSBorderColorStyle_HTMLTableCellElement, MSHTMLTableCellElementExtensions, DOML2DeprecatedAlignmentStyle_HTMLTableCellElement, HTMLTableHeaderCellScope, DOML2DeprecatedWordWrapSuppression, DOML2DeprecatedBackgroundColorStyle { + headers: string; + abbr: string; + rowSpan: number; + cellIndex: number; + colSpan: number; + axis: string; +} +declare var HTMLTableCellElement: { + prototype: HTMLTableCellElement; + new(): HTMLTableCellElement; +} + +interface MSNamespaceInfoCollection { + length: number; + add(namespace?: string, urn?: string, implementationUrl?: any): Object; + item(index: any): Object; + [index: string]: Object; + (index: any): Object; +} +declare var MSNamespaceInfoCollection: { + prototype: MSNamespaceInfoCollection; + new(): MSNamespaceInfoCollection; +} + +interface SVGElementInstance extends EventTarget { + previousSibling: SVGElementInstance; + parentNode: SVGElementInstance; + lastChild: SVGElementInstance; + nextSibling: SVGElementInstance; + childNodes: SVGElementInstanceList; + correspondingUseElement: SVGUseElement; + correspondingElement: SVGElement; + firstChild: SVGElementInstance; +} +declare var SVGElementInstance: { + prototype: SVGElementInstance; + new(): SVGElementInstance; +} + +interface MSHTMLUListElementExtensions { +} + +interface SVGCircleElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests { + cx: SVGAnimatedLength; + r: SVGAnimatedLength; + cy: SVGAnimatedLength; +} +declare var SVGCircleElement: { + prototype: SVGCircleElement; + new(): SVGCircleElement; +} + +interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedSizeProperty_HTMLBaseFontElement, DOML2DeprecatedColorProperty { + face: string; +} +declare var HTMLBaseFontElement: { + prototype: HTMLBaseFontElement; + new(): HTMLBaseFontElement; +} + +interface CustomEvent extends Event { + detail: Object; + initCustomEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, detailArg: Object): void; +} +declare var CustomEvent: { + prototype: CustomEvent; + new(): CustomEvent; +} + +interface CSSImportRule extends CSSRule { + styleSheet: CSSStyleSheet; + href: string; + media: MediaList; +} +declare var CSSImportRule: { + prototype: CSSImportRule; + new(): CSSImportRule; +} + +interface StyleSheetList { + length: number; + item(index?: number): StyleSheet; + [index: number]: StyleSheet; +} +declare var StyleSheetList: { + prototype: StyleSheetList; + new(): StyleSheetList; +} + +interface HTMLTextAreaElement extends HTMLElement, MSDataBindingExtensions, MSHTMLTextAreaElementExtensions { + value: string; + form: HTMLFormElement; + name: string; + selectionStart: number; + rows: number; + cols: number; + readOnly: bool; + wrap: string; + selectionEnd: number; + type: string; + defaultValue: string; + setSelectionRange(start: number, end: number): void; + select(): void; +} +declare var HTMLTextAreaElement: { + prototype: HTMLTextAreaElement; + new(): HTMLTextAreaElement; +} + +interface MSHTMLFormElementExtensions { + encoding: string; +} + +interface DOML2DeprecatedMarginStyle { + vspace: number; + hspace: number; +} + +interface Geolocation { + clearWatch(watchId: number): void; + getCurrentPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): void; + watchPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): number; +} +declare var Geolocation: { + prototype: Geolocation; + new(): Geolocation; +} + +interface MSWindowModeless { + dialogTop: any; + dialogLeft: any; + dialogWidth: any; + dialogHeight: any; + menuArguments: any; +} + +interface HTMLMarqueeElement extends HTMLElement, DOML2DeprecatedMarginStyle_HTMLMarqueeElement, MSDataBindingExtensions, MSHTMLMarqueeElementExtensions, DOML2DeprecatedBackgroundColorStyle { + width: string; + onbounce: (ev: Event) => any; + trueSpeed: bool; + scrollAmount: number; + scrollDelay: number; + behavior: string; + height: string; + loop: number; + direction: string; + onstart: (ev: Event) => any; + onfinish: (ev: Event) => any; + stop(): void; + start(): void; +} +declare var HTMLMarqueeElement: { + prototype: HTMLMarqueeElement; + new(): HTMLMarqueeElement; +} + +interface SVGRect { + y: number; + width: number; + x: number; + height: number; +} +declare var SVGRect: { + prototype: SVGRect; + new(): SVGRect; +} + +interface MSNodeExtensions { + swapNode(otherNode: Node): Node; + removeNode(deep?: bool): Node; + replaceNode(replacement: Node): Node; +} + +interface KeyboardEventExtensions { + keyCode: number; + which: number; + charCode: number; +} + +interface History { + length: number; + back(distance?: any): void; + forward(distance?: any): void; + go(delta?: any): void; +} +declare var History: { + prototype: History; + new(): History; +} + +interface DocumentStyle { + styleSheets: StyleSheetList; +} + +interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { + y: number; + y1: number; + x2: number; + x: number; + x1: number; + y2: number; +} +declare var SVGPathSegCurvetoCubicAbs: { + prototype: SVGPathSegCurvetoCubicAbs; + new(): SVGPathSegCurvetoCubicAbs; +} + +interface TimeRanges { + length: number; + start(index: number): number; + end(index: number): number; +} +declare var TimeRanges: { + prototype: TimeRanges; + new(): TimeRanges; +} + +interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { + y: number; + y1: number; + x: number; + x1: number; +} +declare var SVGPathSegCurvetoQuadraticAbs: { + prototype: SVGPathSegCurvetoQuadraticAbs; + new(): SVGPathSegCurvetoQuadraticAbs; +} + +interface MSHTMLSelectElementExtensions { +} + +interface CSSRule { + cssText: string; + parentStyleSheet: CSSStyleSheet; + parentRule: CSSRule; + type: number; + IMPORT_RULE: number; + MEDIA_RULE: number; + STYLE_RULE: number; + NAMESPACE_RULE: number; + PAGE_RULE: number; + UNKNOWN_RULE: number; + FONT_FACE_RULE: number; + CHARSET_RULE: number; +} +declare var CSSRule: { + prototype: CSSRule; + new(): CSSRule; + IMPORT_RULE: number; + MEDIA_RULE: number; + STYLE_RULE: number; + NAMESPACE_RULE: number; + PAGE_RULE: number; + UNKNOWN_RULE: number; + FONT_FACE_RULE: number; + CHARSET_RULE: number; +} + +interface SVGPathSegLinetoAbs extends SVGPathSeg { + y: number; + x: number; +} +declare var SVGPathSegLinetoAbs: { + prototype: SVGPathSegLinetoAbs; + new(): SVGPathSegLinetoAbs; +} + +interface MSMouseEventExtensions { + toElement: Element; + layerY: number; + fromElement: Element; + which: number; + layerX: number; +} + +interface HTMLModElement extends HTMLElement, MSHTMLModElementExtensions { + dateTime: string; + cite: string; +} +declare var HTMLModElement: { + prototype: HTMLModElement; + new(): HTMLModElement; +} + +interface DOML2DeprecatedWordWrapSuppression { + noWrap: bool; +} + +interface BeforeUnloadEvent extends Event { + returnValue: string; +} +declare var BeforeUnloadEvent: { + prototype: BeforeUnloadEvent; + new(): BeforeUnloadEvent; +} + +interface MSPopupWindow { + document: HTMLDocument; + isOpen: bool; + show(x: number, y: number, w: number, h: number, element?: any): void; + hide(): void; +} +declare var MSPopupWindow: { + prototype: MSPopupWindow; + new(): MSPopupWindow; +} + +interface SVGMatrix { + e: number; + c: number; + a: number; + b: number; + d: number; + f: number; + multiply(secondMatrix: SVGMatrix): SVGMatrix; + flipY(): SVGMatrix; + skewY(angle: number): SVGMatrix; + inverse(): SVGMatrix; + scaleNonUniform(scaleFactorX: number, scaleFactorY: number): SVGMatrix; + rotate(angle: number): SVGMatrix; + flipX(): SVGMatrix; + translate(x: number, y: number): SVGMatrix; + scale(scaleFactor: number): SVGMatrix; + rotateFromVector(x: number, y: number): SVGMatrix; + skewX(angle: number): SVGMatrix; +} +declare var SVGMatrix: { + prototype: SVGMatrix; + new(): SVGMatrix; +} + +interface SVGUseElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests, SVGURIReference { + y: SVGAnimatedLength; + width: SVGAnimatedLength; + animatedInstanceRoot: SVGElementInstance; + instanceRoot: SVGElementInstance; + x: SVGAnimatedLength; + height: SVGAnimatedLength; +} +declare var SVGUseElement: { + prototype: SVGUseElement; + new(): SVGUseElement; +} + +interface Event extends MSEventExtensions { + timeStamp: number; + defaultPrevented: bool; + isTrusted: bool; + currentTarget: EventTarget; + target: EventTarget; + eventPhase: number; + type: string; + cancelable: bool; + bubbles: bool; + initEvent(eventTypeArg: string, canBubbleArg: bool, cancelableArg: bool): void; + stopPropagation(): void; + stopImmediatePropagation(): void; + preventDefault(): void; + CAPTURING_PHASE: number; + AT_TARGET: number; + BUBBLING_PHASE: number; +} +declare var Event: { + prototype: Event; + new(): Event; + CAPTURING_PHASE: number; + AT_TARGET: number; + BUBBLING_PHASE: number; +} + +interface ImageData { + width: number; + data: number[]; + height: number; +} +declare var ImageData: { + prototype: ImageData; + new(): ImageData; +} + +interface MSHTMLElementExtensions { + onlosecapture: (ev: MSEventObj) => any; + onrowexit: (ev: MSEventObj) => any; + oncontrolselect: (ev: MSEventObj) => any; + onrowsinserted: (ev: MSEventObj) => any; + onmouseleave: (ev: MouseEvent) => any; + document: HTMLDocument; + behaviorUrns: MSBehaviorUrnsCollection; + onpropertychange: (ev: MSEventObj) => any; + children: HTMLCollection; + filters: Object; + onbeforecut: (ev: DragEvent) => any; + scopeName: string; + onbeforepaste: (ev: DragEvent) => any; + onmove: (ev: MSEventObj) => any; + onafterupdate: (ev: MSEventObj) => any; + onbeforecopy: (ev: DragEvent) => any; + onlayoutcomplete: (ev: MSEventObj) => any; + onresizeend: (ev: MSEventObj) => any; + uniqueID: string; + onhelp: (ev: Event) => any; + onbeforeactivate: (ev: UIEvent) => any; + isMultiLine: bool; + uniqueNumber: number; + tagUrn: string; + onfocusout: (ev: FocusEvent) => any; + ondataavailable: (ev: MSEventObj) => any; + hideFocus: bool; + onbeforeupdate: (ev: MSEventObj) => any; + onfilterchange: (ev: MSEventObj) => any; + onfocusin: (ev: FocusEvent) => any; + recordNumber: any; + parentTextEdit: Element; + ondatasetcomplete: (ev: MSEventObj) => any; + onbeforedeactivate: (ev: UIEvent) => any; + outerText: string; + onresizestart: (ev: MSEventObj) => any; + onactivate: (ev: UIEvent) => any; + isTextEdit: bool; + isDisabled: bool; + readyState: string; + all: HTMLCollection; + onmouseenter: (ev: MouseEvent) => any; + onmovestart: (ev: MSEventObj) => any; + onselectstart: (ev: Event) => any; + onpaste: (ev: DragEvent) => any; + canHaveHTML: bool; + innerText: string; + onerrorupdate: (ev: MSEventObj) => any; + ondeactivate: (ev: UIEvent) => any; + oncut: (ev: DragEvent) => any; + onmoveend: (ev: MSEventObj) => any; + onresize: (ev: UIEvent) => any; + language: string; + ondatasetchanged: (ev: MSEventObj) => any; + oncopy: (ev: DragEvent) => any; + onrowsdelete: (ev: MSEventObj) => any; + parentElement: HTMLElement; + onrowenter: (ev: MSEventObj) => any; + onbeforeeditfocus: (ev: MSEventObj) => any; + canHaveChildren: bool; + sourceIndex: number; + oncellchange: (ev: MSEventObj) => any; + dragDrop(): bool; + releaseCapture(): void; + addFilter(filter: Object): void; + setCapture(containerCapture?: bool): void; + removeBehavior(cookie: number): bool; + contains(child: HTMLElement): bool; + applyElement(apply: Element, where?: string): Element; + replaceAdjacentText(where: string, newText: string): string; + mergeAttributes(source: HTMLElement, preserveIdentity?: bool): void; + insertAdjacentElement(position: string, insertedElement: Element): Element; + insertAdjacentText(where: string, text: string): void; + getAdjacentText(where: string): string; + removeFilter(filter: Object): void; + setActive(): void; + addBehavior(bstrUrl: string, factory?: any): number; + clearAttributes(): void; +} + +interface HTMLTableColElement extends HTMLElement, MSHTMLTableColElementExtensions, HTMLTableAlignment, DOML2DeprecatedAlignmentStyle_HTMLTableColElement { + width: any; + span: number; +} +declare var HTMLTableColElement: { + prototype: HTMLTableColElement; + new(): HTMLTableColElement; +} + +interface HTMLDocument extends MSEventAttachmentTarget, MSHTMLDocumentSelection, MSHTMLDocumentExtensions, MSNodeExtensions, MSResourceMetadata, MSHTMLDocumentEventExtensions, MSHTMLDocumentViewExtensions { + ondragend: (ev: DragEvent) => any; + ondragover: (ev: DragEvent) => any; + onkeydown: (ev: KeyboardEvent) => any; + bgColor: string; + onkeyup: (ev: KeyboardEvent) => any; + onreset: (ev: Event) => any; + onmouseup: (ev: MouseEvent) => any; + ondragstart: (ev: DragEvent) => any; + scripts: HTMLCollection; + ondrag: (ev: DragEvent) => any; + linkColor: string; + ondragleave: (ev: DragEvent) => any; + onmouseover: (ev: MouseEvent) => any; + onpause: (ev: Event) => any; + charset: string; + vlinkColor: string; + onmousedown: (ev: MouseEvent) => any; + onseeked: (ev: Event) => any; + title: string; + onclick: (ev: MouseEvent) => any; + onwaiting: (ev: Event) => any; + defaultCharset: string; + embeds: HTMLCollection; + ondurationchange: (ev: Event) => any; + all: HTMLCollection; + applets: HTMLCollection; + forms: HTMLCollection; + onblur: (ev: FocusEvent) => any; + dir: string; + body: HTMLElement; + designMode: string; + onemptied: (ev: Event) => any; + domain: string; + onseeking: (ev: Event) => any; + oncanplay: (ev: Event) => any; + onstalled: (ev: Event) => any; + onmousemove: (ev: MouseEvent) => any; + onratechange: (ev: Event) => any; + onloadstart: (ev: Event) => any; + ondragenter: (ev: DragEvent) => any; + onsubmit: (ev: Event) => any; + onprogress: (ev: any) => any; + ondblclick: (ev: MouseEvent) => any; + oncontextmenu: (ev: MouseEvent) => any; + activeElement: Element; + onchange: (ev: Event) => any; + onloadedmetadata: (ev: Event) => any; + onerror: (ev: Event) => any; + onplay: (ev: Event) => any; + links: HTMLCollection; + onplaying: (ev: Event) => any; + URL: string; + images: HTMLCollection; + head: HTMLHeadElement; + location: Location; + cookie: string; + oncanplaythrough: (ev: Event) => any; + onabort: (ev: UIEvent) => any; + characterSet: string; + anchors: HTMLCollection; + lastModified: string; + onreadystatechange: (ev: Event) => any; + onkeypress: (ev: KeyboardEvent) => any; + onloadeddata: (ev: Event) => any; + plugins: HTMLCollection; + onsuspend: (ev: Event) => any; + referrer: string; + readyState: string; + alinkColor: string; + onfocus: (ev: FocusEvent) => any; + fgColor: string; + ontimeupdate: (ev: Event) => any; + onselect: (ev: UIEvent) => any; + ondrop: (ev: DragEvent) => any; + onmouseout: (ev: MouseEvent) => any; + onended: (ev: Event) => any; + compatMode: string; + onscroll: (ev: UIEvent) => any; + onmousewheel: (ev: MouseWheelEvent) => any; + onload: (ev: Event) => any; + onvolumechange: (ev: Event) => any; + oninput: (ev: Event) => any; + queryCommandValue(commandId: string): string; + queryCommandIndeterm(commandId: string): bool; + execCommand(commandId: string, showUI?: bool, value?: any): bool; + getElementsByName(elementName: string): NodeList; + writeln(...content: string[]): void; + open(url?: string, name?: string, features?: string, replace?: bool): any; + queryCommandState(commandId: string): bool; + close(): void; + hasFocus(): bool; + getElementsByClassName(classNames: string): NodeList; + queryCommandSupported(commandId: string): bool; + getSelection(): Selection; + queryCommandEnabled(commandId: string): bool; + write(...content: string[]): void; + queryCommandText(commandId: string): string; +} + +interface SVGException { + code: number; + message: string; + toString(): string; + SVG_MATRIX_NOT_INVERTABLE: number; + SVG_WRONG_TYPE_ERR: number; + SVG_INVALID_VALUE_ERR: number; +} +declare var SVGException: { + prototype: SVGException; + new(): SVGException; + SVG_MATRIX_NOT_INVERTABLE: number; + SVG_WRONG_TYPE_ERR: number; + SVG_INVALID_VALUE_ERR: number; +} + +interface DOML2DeprecatedTableCellHeight { + height: any; +} + +interface HTMLTableAlignment { + ch: string; + vAlign: string; + chOff: string; +} + +interface SVGAnimatedEnumeration { + animVal: number; + baseVal: number; +} +declare var SVGAnimatedEnumeration: { + prototype: SVGAnimatedEnumeration; + new(): SVGAnimatedEnumeration; +} + +interface SVGLinearGradientElement extends SVGGradientElement { + y1: SVGAnimatedLength; + x2: SVGAnimatedLength; + x1: SVGAnimatedLength; + y2: SVGAnimatedLength; +} +declare var SVGLinearGradientElement: { + prototype: SVGLinearGradientElement; + new(): SVGLinearGradientElement; +} + +interface DOML2DeprecatedSizeProperty { + size: number; +} + +interface MSHTMLHeadingElementExtensions extends DOML2DeprecatedTextFlowControl_HTMLBlockElement { +} + +interface MSBorderColorStyle_HTMLTableCellElement { + borderColor: any; +} + +interface DOML2DeprecatedWidthStyle_HTMLHRElement { + width: number; +} + +interface HTMLUListElement extends HTMLElement, DOML2DeprecatedListSpaceReduction, DOML2DeprecatedListNumberingAndBulletStyle, MSHTMLUListElementExtensions { +} +declare var HTMLUListElement: { + prototype: HTMLUListElement; + new(): HTMLUListElement; +} + +interface SVGRectElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests { + y: SVGAnimatedLength; + width: SVGAnimatedLength; + ry: SVGAnimatedLength; + rx: SVGAnimatedLength; + x: SVGAnimatedLength; + height: SVGAnimatedLength; +} +declare var SVGRectElement: { + prototype: SVGRectElement; + new(): SVGRectElement; +} + +interface DOML2DeprecatedBorderStyle { + border: string; +} + +interface HTMLDivElement extends HTMLElement, DOML2DeprecatedAlignmentStyle_HTMLDivElement, MSHTMLDivElementExtensions, MSDataBindingExtensions { +} +declare var HTMLDivElement: { + prototype: HTMLDivElement; + new(): HTMLDivElement; +} + +interface NavigatorDoNotTrack { + msDoNotTrack: string; +} + +interface SVG1_1Properties { + fillRule: string; + strokeLinecap: string; + stopColor: string; + glyphOrientationHorizontal: string; + kerning: string; + alignmentBaseline: string; + dominantBaseline: string; + fill: string; + strokeMiterlimit: string; + marker: string; + glyphOrientationVertical: string; + markerMid: string; + textAnchor: string; + fillOpacity: string; + strokeDasharray: string; + mask: string; + stopOpacity: string; + stroke: string; + strokeDashoffset: string; + strokeOpacity: string; + markerStart: string; + pointerEvents: string; + baselineShift: string; + markerEnd: string; + clipRule: string; + strokeLinejoin: string; + clipPath: string; + strokeWidth: string; +} + +interface NamedNodeMap { + length: number; + removeNamedItemNS(namespaceURI: string, localName: string): Node; + item(index: number): Node; + [index: number]: Node; + removeNamedItem(name: string): Node; + getNamedItem(name: string): Node; + [name: string]: Node; + setNamedItem(arg: Node): Node; + getNamedItemNS(namespaceURI: string, localName: string): Node; + setNamedItemNS(arg: Node): Node; +} +declare var NamedNodeMap: { + prototype: NamedNodeMap; + new(): NamedNodeMap; +} + +interface MediaList { + length: number; + mediaText: string; + deleteMedium(oldMedium: string): void; + appendMedium(newMedium: string): void; + item(index: number): string; + [index: number]: string; + toString(): string; +} +declare var MediaList: { + prototype: MediaList; + new(): MediaList; +} + +interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { + y: number; + x: number; +} +declare var SVGPathSegCurvetoQuadraticSmoothAbs: { + prototype: SVGPathSegCurvetoQuadraticSmoothAbs; + new(): SVGPathSegCurvetoQuadraticSmoothAbs; +} + +interface SVGLengthList { + numberOfItems: number; + replaceItem(newItem: SVGLength, index: number): SVGLength; + getItem(index: number): SVGLength; + clear(): void; + appendItem(newItem: SVGLength): SVGLength; + initialize(newItem: SVGLength): SVGLength; + removeItem(index: number): SVGLength; + insertItemBefore(newItem: SVGLength, index: number): SVGLength; +} +declare var SVGLengthList: { + prototype: SVGLengthList; + new(): SVGLengthList; +} + +interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { + y: number; + x2: number; + x: number; + y2: number; +} +declare var SVGPathSegCurvetoCubicSmoothRel: { + prototype: SVGPathSegCurvetoCubicSmoothRel; + new(): SVGPathSegCurvetoCubicSmoothRel; +} + +interface MSWindowExtensions { + status: string; + onmouseleave: (ev: MouseEvent) => any; + screenLeft: number; + offscreenBuffering: any; + maxConnectionsPerServer: number; + onmouseenter: (ev: MouseEvent) => any; + clipboardData: DataTransfer; + defaultStatus: string; + clientInformation: Navigator; + closed: bool; + onhelp: (ev: Event) => any; + external: BrowserPublic; + event: MSEventObj; + onfocusout: (ev: FocusEvent) => any; + screenTop: number; + onfocusin: (ev: FocusEvent) => any; + showModelessDialog(url?: string, argument?: any, options?: any): Window; + navigate(url: string): void; + resizeBy(x?: number, y?: number): void; + item(index: any): any; + resizeTo(x?: number, y?: number): void; + createPopup(arguments?: any): MSPopupWindow; + toStaticHTML(html: string): string; + execScript(code: string, language?: string): any; + msWriteProfilerMark(profilerMarkName: string): void; + moveTo(x?: number, y?: number): void; + moveBy(x?: number, y?: number): void; + showHelp(url: string, helpArg?: any, features?: string): void; +} + +interface ProcessingInstruction extends Node { + target: string; + data: string; +} +declare var ProcessingInstruction: { + prototype: ProcessingInstruction; + new(): ProcessingInstruction; +} + +interface MSBehaviorUrnsCollection { + length: number; + item(index: number): string; +} +declare var MSBehaviorUrnsCollection: { + prototype: MSBehaviorUrnsCollection; + new(): MSBehaviorUrnsCollection; +} + +interface CSSFontFaceRule extends CSSRule { + style: CSSStyleDeclaration; +} +declare var CSSFontFaceRule: { + prototype: CSSFontFaceRule; + new(): CSSFontFaceRule; +} + +interface DOML2DeprecatedBackgroundStyle { + background: string; +} + +interface TextEvent extends UIEvent { + inputMethod: number; + data: string; + locale: string; + initTextEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, dataArg: string, inputMethod: number, locale: string): void; + DOM_INPUT_METHOD_KEYBOARD: number; + DOM_INPUT_METHOD_DROP: number; + DOM_INPUT_METHOD_IME: number; + DOM_INPUT_METHOD_SCRIPT: number; + DOM_INPUT_METHOD_VOICE: number; + DOM_INPUT_METHOD_UNKNOWN: number; + DOM_INPUT_METHOD_PASTE: number; + DOM_INPUT_METHOD_HANDWRITING: number; + DOM_INPUT_METHOD_OPTION: number; + DOM_INPUT_METHOD_MULTIMODAL: number; +} +declare var TextEvent: { + prototype: TextEvent; + new(): TextEvent; + DOM_INPUT_METHOD_KEYBOARD: number; + DOM_INPUT_METHOD_DROP: number; + DOM_INPUT_METHOD_IME: number; + DOM_INPUT_METHOD_SCRIPT: number; + DOM_INPUT_METHOD_VOICE: number; + DOM_INPUT_METHOD_UNKNOWN: number; + DOM_INPUT_METHOD_PASTE: number; + DOM_INPUT_METHOD_HANDWRITING: number; + DOM_INPUT_METHOD_OPTION: number; + DOM_INPUT_METHOD_MULTIMODAL: number; +} + +interface MSHTMLHRElementExtensions extends DOML2DeprecatedColorProperty { +} + +interface AbstractView { + styleMedia: StyleMedia; + document: Document; +} + +interface DocumentFragment extends Node, NodeSelector, MSEventAttachmentTarget, MSNodeExtensions { +} +declare var DocumentFragment: { + prototype: DocumentFragment; + new(): DocumentFragment; +} + +interface DOML2DeprecatedAlignmentStyle_HTMLFieldSetElement { + align: string; +} + +interface SVGPolylineElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGAnimatedPoints, SVGTests { +} +declare var SVGPolylineElement: { + prototype: SVGPolylineElement; + new(): SVGPolylineElement; +} + +interface DOML2DeprecatedWidthStyle { + width: number; +} + +interface DOML2DeprecatedAlignmentStyle_HTMLHeadingElement { + align: string; +} + +interface SVGAnimatedPathData { + pathSegList: SVGPathSegList; +} + +interface Position { + timestamp: Date; + coords: Coordinates; +} +declare var Position: { + prototype: Position; + new(): Position; +} + +interface BookmarkCollection { + length: number; + item(index: number): any; + [index: number]: any; +} +declare var BookmarkCollection: { + prototype: BookmarkCollection; + new(): BookmarkCollection; +} + +interface CSSPageRule extends CSSRule, StyleSheetPage { + selectorText: string; + style: CSSStyleDeclaration; +} +declare var CSSPageRule: { + prototype: CSSPageRule; + new(): CSSPageRule; +} + +interface WindowPerformance { + performance: any; +} + +interface HTMLBRElement extends HTMLElement, DOML2DeprecatedTextFlowControl_HTMLBRElement { +} +declare var HTMLBRElement: { + prototype: HTMLBRElement; + new(): HTMLBRElement; +} + +interface MSHTMLDivElementExtensions extends DOML2DeprecatedWordWrapSuppression_HTMLDivElement { +} + +interface DOML2DeprecatedBorderStyle_HTMLInputElement { + border: string; +} + +interface HTMLSpanElement extends HTMLElement, MSHTMLSpanElementExtensions, MSDataBindingExtensions { +} +declare var HTMLSpanElement: { + prototype: HTMLSpanElement; + new(): HTMLSpanElement; +} + +interface HTMLHRElementDOML2Deprecated { + noShade: bool; +} + +interface HTMLHeadElement extends HTMLElement { + profile: string; +} +declare var HTMLHeadElement: { + prototype: HTMLHeadElement; + new(): HTMLHeadElement; +} + +interface NodeFilterCallback { + (...args: any[]): any; +} + +interface HTMLHeadingElement extends HTMLElement, DOML2DeprecatedAlignmentStyle_HTMLHeadingElement, MSHTMLHeadingElementExtensions { +} +declare var HTMLHeadingElement: { + prototype: HTMLHeadingElement; + new(): HTMLHeadingElement; +} + +interface HTMLFormElement extends HTMLElement, MSHTMLFormElementExtensions, MSHTMLCollectionExtensions { + length: number; + target: string; + acceptCharset: string; + enctype: string; + elements: HTMLCollection; + action: string; + name: string; + method: string; + reset(): void; + item(name?: any, index?: any): any; + (name: any, index: any): any; + submit(): void; + namedItem(name: string): any; + [name: string]: any; + (name: string): any; +} +declare var HTMLFormElement: { + prototype: HTMLFormElement; + new(): HTMLFormElement; +} + +interface SVGZoomAndPan { + zoomAndPan: number; + SVG_ZOOMANDPAN_MAGNIFY: number; + SVG_ZOOMANDPAN_UNKNOWN: number; + SVG_ZOOMANDPAN_DISABLE: number; +} +declare var SVGZoomAndPan: { + prototype: SVGZoomAndPan; + new(): SVGZoomAndPan; + SVG_ZOOMANDPAN_MAGNIFY: number; + SVG_ZOOMANDPAN_UNKNOWN: number; + SVG_ZOOMANDPAN_DISABLE: number; +} + +interface MSEventExtensions { + cancelBubble: bool; + srcElement: Element; +} + +interface HTMLMediaElement extends HTMLElement { + initialTime: number; + played: TimeRanges; + currentSrc: string; + readyState: string; + autobuffer: bool; + loop: bool; + ended: bool; + buffered: TimeRanges; + error: MediaError; + seekable: TimeRanges; + autoplay: bool; + controls: bool; + volume: number; + src: string; + playbackRate: number; + duration: number; + muted: bool; + defaultPlaybackRate: number; + paused: bool; + seeking: bool; + currentTime: number; + preload: string; + networkState: number; + pause(): void; + play(): void; + load(): void; + canPlayType(type: string): string; + HAVE_METADATA: number; + HAVE_CURRENT_DATA: number; + HAVE_NOTHING: number; + NETWORK_NO_SOURCE: number; + HAVE_ENOUGH_DATA: number; + NETWORK_EMPTY: number; + NETWORK_LOADING: number; + NETWORK_IDLE: number; + HAVE_FUTURE_DATA: number; +} +declare var HTMLMediaElement: { + prototype: HTMLMediaElement; + new(): HTMLMediaElement; + HAVE_METADATA: number; + HAVE_CURRENT_DATA: number; + HAVE_NOTHING: number; + NETWORK_NO_SOURCE: number; + HAVE_ENOUGH_DATA: number; + NETWORK_EMPTY: number; + NETWORK_LOADING: number; + NETWORK_IDLE: number; + HAVE_FUTURE_DATA: number; +} + +interface ElementCSSInlineStyle extends MSElementCSSInlineStyleExtensions { + runtimeStyle: MSStyleCSSProperties; + currentStyle: MSCurrentStyleCSSProperties; +} + +interface DOMParser { + parseFromString(source: string, mimeType: string): Document; +} +declare var DOMParser: { + prototype: DOMParser; + new (): DOMParser; +} + +interface MSMimeTypesCollection { + length: number; +} +declare var MSMimeTypesCollection: { + prototype: MSMimeTypesCollection; + new(): MSMimeTypesCollection; +} + +interface StyleSheet { + disabled: bool; + ownerNode: Node; + parentStyleSheet: StyleSheet; + href: string; + media: MediaList; + type: string; + title: string; +} +declare var StyleSheet: { + prototype: StyleSheet; + new(): StyleSheet; +} + +interface DOML2DeprecatedBorderStyle_HTMLTableElement { + border: string; +} + +interface DOML2DeprecatedWidthStyle_HTMLAppletElement { + width: number; +} + +interface SVGTextPathElement extends SVGTextContentElement, SVGURIReference { + startOffset: SVGAnimatedLength; + method: SVGAnimatedEnumeration; + spacing: SVGAnimatedEnumeration; + TEXTPATH_SPACINGTYPE_EXACT: number; + TEXTPATH_METHODTYPE_STRETCH: number; + TEXTPATH_SPACINGTYPE_AUTO: number; + TEXTPATH_SPACINGTYPE_UNKNOWN: number; + TEXTPATH_METHODTYPE_UNKNOWN: number; + TEXTPATH_METHODTYPE_ALIGN: number; +} +declare var SVGTextPathElement: { + prototype: SVGTextPathElement; + new(): SVGTextPathElement; + TEXTPATH_SPACINGTYPE_EXACT: number; + TEXTPATH_METHODTYPE_STRETCH: number; + TEXTPATH_SPACINGTYPE_AUTO: number; + TEXTPATH_SPACINGTYPE_UNKNOWN: number; + TEXTPATH_METHODTYPE_UNKNOWN: number; + TEXTPATH_METHODTYPE_ALIGN: number; +} + +interface NodeList { + length: number; + item(index: number): Node; + [index: number]: Node; +} +declare var NodeList: { + prototype: NodeList; + new(): NodeList; +} + +interface HTMLDTElement extends HTMLElement, DOML2DeprecatedWordWrapSuppression_HTMLDTElement { +} +declare var HTMLDTElement: { + prototype: HTMLDTElement; + new(): HTMLDTElement; +} + +interface XMLSerializer { + serializeToString(target: Node): string; +} +declare var XMLSerializer: { + prototype: XMLSerializer; + new (): XMLSerializer; +} + +interface StyleSheetPage { + pseudoClass: string; + selector: string; +} + +interface DOML2DeprecatedWordWrapSuppression_HTMLDDElement { + noWrap: bool; +} + +interface MSHTMLTableRowElementExtensions { + height: any; +} + +interface SVGGradientElement extends SVGElement, SVGUnitTypes, SVGStylable, SVGURIReference { + spreadMethod: SVGAnimatedEnumeration; + gradientTransform: SVGAnimatedTransformList; + gradientUnits: SVGAnimatedEnumeration; + SVG_SPREADMETHOD_REFLECT: number; + SVG_SPREADMETHOD_PAD: number; + SVG_SPREADMETHOD_UNKNOWN: number; + SVG_SPREADMETHOD_REPEAT: number; +} +declare var SVGGradientElement: { + prototype: SVGGradientElement; + new(): SVGGradientElement; + SVG_SPREADMETHOD_REFLECT: number; + SVG_SPREADMETHOD_PAD: number; + SVG_SPREADMETHOD_UNKNOWN: number; + SVG_SPREADMETHOD_REPEAT: number; +} + +interface DOML2DeprecatedTextFlowControl_HTMLBRElement { + clear: string; +} + +interface MSHTMLParagraphElementExtensions extends DOML2DeprecatedTextFlowControl_HTMLBlockElement { +} + +interface NodeFilter { + acceptNode(n: Node): number; + SHOW_ENTITY_REFERENCE: number; + SHOW_NOTATION: number; + SHOW_ENTITY: number; + SHOW_DOCUMENT: number; + SHOW_PROCESSING_INSTRUCTION: number; + FILTER_REJECT: number; + SHOW_CDATA_SECTION: number; + FILTER_ACCEPT: number; + SHOW_ALL: number; + SHOW_DOCUMENT_TYPE: number; + SHOW_TEXT: number; + SHOW_ELEMENT: number; + SHOW_COMMENT: number; + FILTER_SKIP: number; + SHOW_ATTRIBUTE: number; + SHOW_DOCUMENT_FRAGMENT: number; +} +declare var NodeFilter: { + prototype: NodeFilter; + new(): NodeFilter; + SHOW_ENTITY_REFERENCE: number; + SHOW_NOTATION: number; + SHOW_ENTITY: number; + SHOW_DOCUMENT: number; + SHOW_PROCESSING_INSTRUCTION: number; + FILTER_REJECT: number; + SHOW_CDATA_SECTION: number; + FILTER_ACCEPT: number; + SHOW_ALL: number; + SHOW_DOCUMENT_TYPE: number; + SHOW_TEXT: number; + SHOW_ELEMENT: number; + SHOW_COMMENT: number; + FILTER_SKIP: number; + SHOW_ATTRIBUTE: number; + SHOW_DOCUMENT_FRAGMENT: number; +} + +interface MSBorderColorStyle_HTMLFrameElement { + borderColor: any; +} + +interface MSHTMLOListElementExtensions { +} + +interface DOML2DeprecatedWordWrapSuppression_HTMLDTElement { + noWrap: bool; +} + +interface ScreenView extends AbstractView { + outerWidth: number; + pageXOffset: number; + innerWidth: number; + pageYOffset: number; + screenY: number; + outerHeight: number; + screen: Screen; + innerHeight: number; + screenX: number; + scroll(x?: number, y?: number): void; + scrollBy(x?: number, y?: number): void; + scrollTo(x?: number, y?: number): void; +} + +interface DOML2DeprecatedMarginStyle_HTMLObjectElement { + vspace: number; + hspace: number; +} + +interface DOML2DeprecatedMarginStyle_HTMLInputElement { + vspace: number; + hspace: number; +} + +interface MSHTMLTableSectionElementExtensions extends DOML2DeprecatedBackgroundColorStyle { + moveRow(indexFrom?: number, indexTo?: number): Object; +} + +interface HTMLFieldSetElement extends HTMLElement, MSHTMLFieldSetElementExtensions { + form: HTMLFormElement; +} +declare var HTMLFieldSetElement: { + prototype: HTMLFieldSetElement; + new(): HTMLFieldSetElement; +} + +interface MediaError { + code: number; + MEDIA_ERR_ABORTED: number; + MEDIA_ERR_NETWORK: number; + MEDIA_ERR_SRC_NOT_SUPPORTED: number; + MEDIA_ERR_DECODE: number; +} +declare var MediaError: { + prototype: MediaError; + new(): MediaError; + MEDIA_ERR_ABORTED: number; + MEDIA_ERR_NETWORK: number; + MEDIA_ERR_SRC_NOT_SUPPORTED: number; + MEDIA_ERR_DECODE: number; +} + +interface SVGNumberList { + numberOfItems: number; + replaceItem(newItem: SVGNumber, index: number): SVGNumber; + getItem(index: number): SVGNumber; + clear(): void; + appendItem(newItem: SVGNumber): SVGNumber; + initialize(newItem: SVGNumber): SVGNumber; + removeItem(index: number): SVGNumber; + insertItemBefore(newItem: SVGNumber, index: number): SVGNumber; +} +declare var SVGNumberList: { + prototype: SVGNumberList; + new(): SVGNumberList; +} + +interface HTMLBGSoundElement extends HTMLElement { + balance: any; + volume: any; + src: string; + loop: number; +} +declare var HTMLBGSoundElement: { + prototype: HTMLBGSoundElement; + new(): HTMLBGSoundElement; +} + +interface HTMLElement extends Element, MSHTMLElementRangeExtensions, ElementCSSInlineStyle, MSEventAttachmentTarget, MSHTMLElementExtensions, MSNodeExtensions { + ondragend: (ev: DragEvent) => any; + onkeydown: (ev: KeyboardEvent) => any; + ondragover: (ev: DragEvent) => any; + onkeyup: (ev: KeyboardEvent) => any; + offsetTop: number; + onreset: (ev: Event) => any; + onmouseup: (ev: MouseEvent) => any; + ondragstart: (ev: DragEvent) => any; + ondrag: (ev: DragEvent) => any; + innerHTML: string; + onmouseover: (ev: MouseEvent) => any; + ondragleave: (ev: DragEvent) => any; + lang: string; + onpause: (ev: Event) => any; + className: string; + onseeked: (ev: Event) => any; + onmousedown: (ev: MouseEvent) => any; + title: string; + onclick: (ev: MouseEvent) => any; + onwaiting: (ev: Event) => any; + outerHTML: string; + offsetLeft: number; + ondurationchange: (ev: Event) => any; + offsetHeight: number; + dir: string; + onblur: (ev: FocusEvent) => any; + onemptied: (ev: Event) => any; + onseeking: (ev: Event) => any; + oncanplay: (ev: Event) => any; + onstalled: (ev: Event) => any; + onmousemove: (ev: MouseEvent) => any; + style: MSStyleCSSProperties; + isContentEditable: bool; + onratechange: (ev: Event) => any; + onloadstart: (ev: Event) => any; + ondragenter: (ev: DragEvent) => any; + contentEditable: string; + onsubmit: (ev: Event) => any; + tabIndex: number; + onprogress: (ev: any) => any; + ondblclick: (ev: MouseEvent) => any; + oncontextmenu: (ev: MouseEvent) => any; + onchange: (ev: Event) => any; + onloadedmetadata: (ev: Event) => any; + onerror: (ev: Event) => any; + onplay: (ev: Event) => any; + id: string; + onplaying: (ev: Event) => any; + oncanplaythrough: (ev: Event) => any; + onabort: (ev: UIEvent) => any; + onreadystatechange: (ev: Event) => any; + onkeypress: (ev: KeyboardEvent) => any; + offsetParent: Element; + onloadeddata: (ev: Event) => any; + disabled: bool; + onsuspend: (ev: Event) => any; + accessKey: string; + onfocus: (ev: FocusEvent) => any; + ontimeupdate: (ev: Event) => any; + onselect: (ev: UIEvent) => any; + ondrop: (ev: DragEvent) => any; + offsetWidth: number; + onmouseout: (ev: MouseEvent) => any; + onended: (ev: Event) => any; + onscroll: (ev: UIEvent) => any; + onmousewheel: (ev: MouseWheelEvent) => any; + onvolumechange: (ev: Event) => any; + onload: (ev: Event) => any; + oninput: (ev: Event) => any; + click(): void; + getElementsByClassName(classNames: string): NodeList; + scrollIntoView(top?: bool): void; + focus(): void; + blur(): void; + insertAdjacentHTML(where: string, html: string): void; +} +declare var HTMLElement: { + prototype: HTMLElement; + new(): HTMLElement; +} + +interface Comment extends CharacterData, MSCommentExtensions { +} +declare var Comment: { + prototype: Comment; + new(): Comment; +} + +interface CanvasPattern { +} +declare var CanvasPattern: { + prototype: CanvasPattern; + new(): CanvasPattern; +} + +interface HTMLHRElement extends HTMLElement, DOML2DeprecatedWidthStyle_HTMLHRElement, MSHTMLHRElementExtensions, HTMLHRElementDOML2Deprecated, DOML2DeprecatedAlignmentStyle_HTMLHRElement, DOML2DeprecatedSizeProperty { +} +declare var HTMLHRElement: { + prototype: HTMLHRElement; + new(): HTMLHRElement; +} + +interface MSHTMLFrameSetElementExtensions { + name: string; + frameBorder: string; + border: string; + frameSpacing: any; +} + +interface DOML2DeprecatedTextFlowControl_HTMLBlockElement { + clear: string; +} + +interface PositionOptions { + enableHighAccuracy?: bool; + timeout?: number; + maximumAge?: number; +} + +interface HTMLObjectElement extends HTMLElement, MSHTMLObjectElementExtensions, GetSVGDocument, DOML2DeprecatedMarginStyle_HTMLObjectElement, MSDataBindingExtensions, MSDataBindingRecordSetExtensions, DOML2DeprecatedAlignmentStyle_HTMLObjectElement, DOML2DeprecatedBorderStyle_HTMLObjectElement { + width: string; + codeType: string; + archive: string; + standby: string; + name: string; + useMap: string; + form: HTMLFormElement; + data: string; + height: string; + contentDocument: Document; + codeBase: string; + declare: bool; + type: string; + code: string; +} +declare var HTMLObjectElement: { + prototype: HTMLObjectElement; + new(): HTMLObjectElement; +} + +interface MSHTMLMenuElementExtensions { +} + +interface DocumentView { + defaultView: AbstractView; + elementFromPoint(x: number, y: number): Element; +} + +interface StorageEvent extends Event { + oldValue: any; + newValue: any; + url: string; + storageArea: Storage; + key: string; + initStorageEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, keyArg: string, oldValueArg: any, newValueArg: any, urlArg: string, storageAreaArg: Storage): void; +} +declare var StorageEvent: { + prototype: StorageEvent; + new(): StorageEvent; +} + +interface HTMLEmbedElement extends HTMLElement, GetSVGDocument, MSHTMLEmbedElementExtensions { + width: string; + src: string; + name: string; + height: string; +} +declare var HTMLEmbedElement: { + prototype: HTMLEmbedElement; + new(): HTMLEmbedElement; +} + +interface CharacterData extends Node { + length: number; + data: string; + deleteData(offset: number, count: number): void; + replaceData(offset: number, count: number, arg: string): void; + appendData(arg: string): void; + insertData(offset: number, arg: string): void; + substringData(offset: number, count: number): string; +} +declare var CharacterData: { + prototype: CharacterData; + new(): CharacterData; +} + +interface DOML2DeprecatedAlignmentStyle_HTMLTableSectionElement { + align: string; +} + +interface HTMLOptGroupElement extends HTMLElement, MSDataBindingExtensions, MSHTMLOptGroupElementExtensions { + label: string; +} +declare var HTMLOptGroupElement: { + prototype: HTMLOptGroupElement; + new(): HTMLOptGroupElement; +} + +interface HTMLIsIndexElement extends HTMLElement, MSHTMLIsIndexElementExtensions { + form: HTMLFormElement; + prompt: string; +} +declare var HTMLIsIndexElement: { + prototype: HTMLIsIndexElement; + new(): HTMLIsIndexElement; +} + +interface SVGPathSegLinetoRel extends SVGPathSeg { + y: number; + x: number; +} +declare var SVGPathSegLinetoRel: { + prototype: SVGPathSegLinetoRel; + new(): SVGPathSegLinetoRel; +} + +interface MSHTMLDocumentSelection { + selection: MSSelection; +} + +interface DOMException { + code: number; + message: string; + toString(): string; + HIERARCHY_REQUEST_ERR: number; + NO_MODIFICATION_ALLOWED_ERR: number; + INVALID_MODIFICATION_ERR: number; + NAMESPACE_ERR: number; + INVALID_CHARACTER_ERR: number; + TYPE_MISMATCH_ERR: number; + ABORT_ERR: number; + INVALID_STATE_ERR: number; + SECURITY_ERR: number; + NETWORK_ERR: number; + WRONG_DOCUMENT_ERR: number; + QUOTA_EXCEEDED_ERR: number; + INDEX_SIZE_ERR: number; + DOMSTRING_SIZE_ERR: number; + SYNTAX_ERR: number; + SERIALIZE_ERR: number; + VALIDATION_ERR: number; + NOT_FOUND_ERR: number; + URL_MISMATCH_ERR: number; + PARSE_ERR: number; + NO_DATA_ALLOWED_ERR: number; + NOT_SUPPORTED_ERR: number; + INVALID_ACCESS_ERR: number; + INUSE_ATTRIBUTE_ERR: number; +} +declare var DOMException: { + prototype: DOMException; + new(): DOMException; + HIERARCHY_REQUEST_ERR: number; + NO_MODIFICATION_ALLOWED_ERR: number; + INVALID_MODIFICATION_ERR: number; + NAMESPACE_ERR: number; + INVALID_CHARACTER_ERR: number; + TYPE_MISMATCH_ERR: number; + ABORT_ERR: number; + INVALID_STATE_ERR: number; + SECURITY_ERR: number; + NETWORK_ERR: number; + WRONG_DOCUMENT_ERR: number; + QUOTA_EXCEEDED_ERR: number; + INDEX_SIZE_ERR: number; + DOMSTRING_SIZE_ERR: number; + SYNTAX_ERR: number; + SERIALIZE_ERR: number; + VALIDATION_ERR: number; + NOT_FOUND_ERR: number; + URL_MISMATCH_ERR: number; + PARSE_ERR: number; + NO_DATA_ALLOWED_ERR: number; + NOT_SUPPORTED_ERR: number; + INVALID_ACCESS_ERR: number; + INUSE_ATTRIBUTE_ERR: number; +} + +interface MSCompatibleInfoCollection { + length: number; + item(index: number): MSCompatibleInfo; +} +declare var MSCompatibleInfoCollection: { + prototype: MSCompatibleInfoCollection; + new(): MSCompatibleInfoCollection; +} + +interface MSHTMLIsIndexElementExtensions { + action: string; +} + +interface SVGAnimatedBoolean { + animVal: bool; + baseVal: bool; +} +declare var SVGAnimatedBoolean: { + prototype: SVGAnimatedBoolean; + new(): SVGAnimatedBoolean; +} + +interface SVGSwitchElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests { +} +declare var SVGSwitchElement: { + prototype: SVGSwitchElement; + new(): SVGSwitchElement; +} + +interface MSHTMLIFrameElementExtensions extends DOML2DeprecatedMarginStyle_MSHTMLIFrameElementExtensions, DOML2DeprecatedBorderStyle_MSHTMLIFrameElementExtensions { + onload: (ev: Event) => any; + frameSpacing: any; + noResize: bool; +} + +interface SVGPreserveAspectRatio { + align: number; + meetOrSlice: number; + SVG_PRESERVEASPECTRATIO_NONE: number; + SVG_PRESERVEASPECTRATIO_XMINYMID: number; + SVG_PRESERVEASPECTRATIO_XMAXYMIN: number; + SVG_PRESERVEASPECTRATIO_XMINYMAX: number; + SVG_PRESERVEASPECTRATIO_XMAXYMAX: number; + SVG_MEETORSLICE_UNKNOWN: number; + SVG_PRESERVEASPECTRATIO_XMAXYMID: number; + SVG_PRESERVEASPECTRATIO_XMIDYMAX: number; + SVG_PRESERVEASPECTRATIO_XMINYMIN: number; + SVG_MEETORSLICE_MEET: number; + SVG_PRESERVEASPECTRATIO_XMIDYMID: number; + SVG_PRESERVEASPECTRATIO_XMIDYMIN: number; + SVG_MEETORSLICE_SLICE: number; + SVG_PRESERVEASPECTRATIO_UNKNOWN: number; +} +declare var SVGPreserveAspectRatio: { + prototype: SVGPreserveAspectRatio; + new(): SVGPreserveAspectRatio; + SVG_PRESERVEASPECTRATIO_NONE: number; + SVG_PRESERVEASPECTRATIO_XMINYMID: number; + SVG_PRESERVEASPECTRATIO_XMAXYMIN: number; + SVG_PRESERVEASPECTRATIO_XMINYMAX: number; + SVG_PRESERVEASPECTRATIO_XMAXYMAX: number; + SVG_MEETORSLICE_UNKNOWN: number; + SVG_PRESERVEASPECTRATIO_XMAXYMID: number; + SVG_PRESERVEASPECTRATIO_XMIDYMAX: number; + SVG_PRESERVEASPECTRATIO_XMINYMIN: number; + SVG_MEETORSLICE_MEET: number; + SVG_PRESERVEASPECTRATIO_XMIDYMID: number; + SVG_PRESERVEASPECTRATIO_XMIDYMIN: number; + SVG_MEETORSLICE_SLICE: number; + SVG_PRESERVEASPECTRATIO_UNKNOWN: number; +} + +interface Attr extends Node, MSAttrExtensions { + specified: bool; + ownerElement: Element; + value: string; + name: string; +} +declare var Attr: { + prototype: Attr; + new(): Attr; +} + +interface MSBorderColorStyle_HTMLTableRowElement { + borderColor: any; +} + +interface DOML2DeprecatedAlignmentStyle_HTMLTableCaptionElement { + align: string; +} + +interface PerformanceNavigation { + redirectCount: number; + type: number; + toJSON(): any; + TYPE_RELOAD: number; + TYPE_RESERVED: number; + TYPE_BACK_FORWARD: number; + TYPE_NAVIGATE: number; +} +declare var PerformanceNavigation: { + prototype: PerformanceNavigation; + new(): PerformanceNavigation; + TYPE_RELOAD: number; + TYPE_RESERVED: number; + TYPE_BACK_FORWARD: number; + TYPE_NAVIGATE: number; +} + +interface HTMLBodyElementDOML2Deprecated { + link: any; + aLink: any; + text: any; + vLink: any; +} + +interface SVGStopElement extends SVGElement, SVGStylable { + offset: SVGAnimatedNumber; +} +declare var SVGStopElement: { + prototype: SVGStopElement; + new(): SVGStopElement; +} + +interface PositionCallback { + (position: Position): void; +} + +interface SVGSymbolElement extends SVGElement, SVGStylable, SVGLangSpace, SVGFitToViewBox { +} +declare var SVGSymbolElement: { + prototype: SVGSymbolElement; + new(): SVGSymbolElement; +} + +interface SVGElementInstanceList { + length: number; + item(index: number): SVGElementInstance; +} +declare var SVGElementInstanceList: { + prototype: SVGElementInstanceList; + new(): SVGElementInstanceList; +} + +interface MSDataBindingRecordSetExtensions { + recordset: Object; + namedRecordset(dataMember: string, hierarchy?: any): Object; +} + +interface CSSRuleList { + length: number; + item(index: number): CSSRule; + [index: number]: CSSRule; +} +declare var CSSRuleList: { + prototype: CSSRuleList; + new(): CSSRuleList; +} + +interface MSHTMLTableColElementExtensions { +} + +interface LinkStyle { + sheet: StyleSheet; +} + +interface MSHTMLMarqueeElementExtensions { +} + +interface HTMLVideoElement extends HTMLMediaElement { + width: number; + videoWidth: number; + videoHeight: number; + height: number; + poster: string; +} +declare var HTMLVideoElement: { + prototype: HTMLVideoElement; + new(): HTMLVideoElement; +} + +interface MSXMLHttpRequestExtensions { + responseBody: any; + timeout: number; + ontimeout: (ev: Event) => any; +} + +interface ClientRectList { + length: number; + item(index: number): ClientRect; + [index: number]: ClientRect; +} +declare var ClientRectList: { + prototype: ClientRectList; + new(): ClientRectList; +} + +interface DOML2DeprecatedAlignmentStyle_HTMLTableCellElement { + align: string; +} + +interface SVGMaskElement extends SVGElement, SVGUnitTypes, SVGStylable, SVGLangSpace, SVGTests { + y: SVGAnimatedLength; + width: SVGAnimatedLength; + maskUnits: SVGAnimatedEnumeration; + maskContentUnits: SVGAnimatedEnumeration; + x: SVGAnimatedLength; + height: SVGAnimatedLength; +} +declare var SVGMaskElement: { + prototype: SVGMaskElement; + new(): SVGMaskElement; +} + +declare var Audio: { new (src?: string): HTMLAudioElement; }; +declare var Option: { new (text?: string, value?: string, defaultSelected?: bool, selected?: bool): HTMLOptionElement; }; +declare var Image: { new (width?: number, height?: number): HTMLImageElement; }; + +declare var ondragend: (ev: DragEvent) => any; +declare var onkeydown: (ev: KeyboardEvent) => any; +declare var ondragover: (ev: DragEvent) => any; +declare var onkeyup: (ev: KeyboardEvent) => any; +declare var onreset: (ev: Event) => any; +declare var onmouseup: (ev: MouseEvent) => any; +declare var ondragstart: (ev: DragEvent) => any; +declare var ondrag: (ev: DragEvent) => any; +declare var onmouseover: (ev: MouseEvent) => any; +declare var ondragleave: (ev: DragEvent) => any; +declare var history: History; +declare var name: string; +declare var onafterprint: (ev: Event) => any; +declare var onpause: (ev: Event) => any; +declare var onbeforeprint: (ev: Event) => any; +declare var top: Window; +declare var onmousedown: (ev: MouseEvent) => any; +declare var onseeked: (ev: Event) => any; +declare var opener: Window; +declare var onclick: (ev: MouseEvent) => any; +declare var onwaiting: (ev: Event) => any; +declare var ononline: (ev: Event) => any; +declare var ondurationchange: (ev: Event) => any; +declare var frames: Window; +declare var onblur: (ev: FocusEvent) => any; +declare var onemptied: (ev: Event) => any; +declare var onseeking: (ev: Event) => any; +declare var oncanplay: (ev: Event) => any; +declare var onstalled: (ev: Event) => any; +declare var onmousemove: (ev: MouseEvent) => any; +declare var onoffline: (ev: Event) => any; +declare var length: number; +declare var onbeforeunload: (ev: BeforeUnloadEvent) => any; +declare var onratechange: (ev: Event) => any; +declare var onstorage: (ev: StorageEvent) => any; +declare var onloadstart: (ev: Event) => any; +declare var ondragenter: (ev: DragEvent) => any; +declare var onsubmit: (ev: Event) => any; +declare var self: Window; +declare var onprogress: (ev: any) => any; +declare var ondblclick: (ev: MouseEvent) => any; +declare var oncontextmenu: (ev: MouseEvent) => any; +declare var onchange: (ev: Event) => any; +declare var onloadedmetadata: (ev: Event) => any; +declare var onplay: (ev: Event) => any; +declare var onerror: ErrorFunction; +declare var onplaying: (ev: Event) => any; +declare var parent: Window; +declare var location: Location; +declare var oncanplaythrough: (ev: Event) => any; +declare var onabort: (ev: UIEvent) => any; +declare var onreadystatechange: (ev: Event) => any; +declare var onkeypress: (ev: KeyboardEvent) => any; +declare var frameElement: Element; +declare var onloadeddata: (ev: Event) => any; +declare var onsuspend: (ev: Event) => any; +declare var window: Window; +declare var onfocus: (ev: FocusEvent) => any; +declare var onmessage: (ev: MessageEvent) => any; +declare var ontimeupdate: (ev: Event) => any; +declare var onresize: (ev: UIEvent) => any; +declare var navigator: Navigator; +declare var onselect: (ev: UIEvent) => any; +declare var ondrop: (ev: DragEvent) => any; +declare var onmouseout: (ev: MouseEvent) => any; +declare var onended: (ev: Event) => any; +declare var onhashchange: (ev: Event) => any; +declare var onunload: (ev: Event) => any; +declare var onscroll: (ev: UIEvent) => any; +declare var onmousewheel: (ev: MouseWheelEvent) => any; +declare var onload: (ev: Event) => any; +declare var onvolumechange: (ev: Event) => any; +declare var oninput: (ev: Event) => any; +declare function alert(message?: string): void; +declare function focus(): void; +declare function print(): void; +declare function prompt(message?: string, defaul?: string): string; +declare function toString(): string; +declare function open(url?: string, target?: string, features?: string, replace?: bool): Window; +declare function close(): void; +declare function confirm(message?: string): bool; +declare function postMessage(message: any, targetOrigin: string, ports?: any): void; +declare function showModalDialog(url?: string, argument?: any, options?: any): any; +declare function blur(): void; +declare function getSelection(): Selection; +declare function getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; +declare function attachEvent(event: string, listener: EventListener): bool; +declare function detachEvent(event: string, listener: EventListener): void; +declare var status: string; +declare var onmouseleave: (ev: MouseEvent) => any; +declare var screenLeft: number; +declare var offscreenBuffering: any; +declare var maxConnectionsPerServer: number; +declare var onmouseenter: (ev: MouseEvent) => any; +declare var clipboardData: DataTransfer; +declare var defaultStatus: string; +declare var clientInformation: Navigator; +declare var closed: bool; +declare var onhelp: (ev: Event) => any; +declare var external: BrowserPublic; +declare var event: MSEventObj; +declare var onfocusout: (ev: FocusEvent) => any; +declare var screenTop: number; +declare var onfocusin: (ev: FocusEvent) => any; +declare function showModelessDialog(url?: string, argument?: any, options?: any): Window; +declare function navigate(url: string): void; +declare function resizeBy(x?: number, y?: number): void; +declare function item(index: any): any; +declare function resizeTo(x?: number, y?: number): void; +declare function createPopup(arguments?: any): MSPopupWindow; +declare function toStaticHTML(html: string): string; +declare function execScript(code: string, language?: string): any; +declare function msWriteProfilerMark(profilerMarkName: string): void; +declare function moveTo(x?: number, y?: number): void; +declare function moveBy(x?: number, y?: number): void; +declare function showHelp(url: string, helpArg?: any, features?: string): void; +declare var performance: any; +declare var outerWidth: number; +declare var pageXOffset: number; +declare var innerWidth: number; +declare var pageYOffset: number; +declare var screenY: number; +declare var outerHeight: number; +declare var screen: Screen; +declare var innerHeight: number; +declare var screenX: number; +declare function scroll(x?: number, y?: number): void; +declare function scrollBy(x?: number, y?: number): void; +declare function scrollTo(x?: number, y?: number): void; +declare var styleMedia: StyleMedia; +declare var document: Document; +declare function removeEventListener(type: string, listener: EventListener, useCapture?: bool): void; +declare function addEventListener(type: string, listener: EventListener, useCapture?: bool): void; +declare function dispatchEvent(evt: Event): bool; +declare var localStorage: Storage; +declare var sessionStorage: Storage; +declare function clearTimeout(handle: number): void; +declare function setTimeout(expression: any, msec?: number, language?: any): number; +declare function clearInterval(handle: number): void; +declare function setInterval(expression: any, msec?: number, language?: any): number; + + +///////////////////////////// +/// IE10 DOM APIs +///////////////////////////// + +interface HTMLBodyElement { + onpopstate: (ev: PopStateEvent) => any; +} + +interface MSGestureEvent extends UIEvent { + offsetY: number; + translationY: number; + velocityExpansion: number; + velocityY: number; + velocityAngular: number; + translationX: number; + velocityX: number; + hwTimestamp: number; + offsetX: number; + screenX: number; + rotation: number; + expansion: number; + clientY: number; + screenY: number; + scale: number; + gestureObject: any; + clientX: number; + initGestureEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, offsetXArg: number, offsetYArg: number, translationXArg: number, translationYArg: number, scaleArg: number, expansionArg: number, rotationArg: number, velocityXArg: number, velocityYArg: number, velocityExpansionArg: number, velocityAngularArg: number, hwTimestampArg: number): void; + MSGESTURE_FLAG_BEGIN: number; + MSGESTURE_FLAG_END: number; + MSGESTURE_FLAG_CANCEL: number; + MSGESTURE_FLAG_INERTIA: number; + MSGESTURE_FLAG_NONE: number; +} +declare var MSGestureEvent: { + prototype: MSGestureEvent; + new(): MSGestureEvent; + MSGESTURE_FLAG_BEGIN: number; + MSGESTURE_FLAG_END: number; + MSGESTURE_FLAG_CANCEL: number; + MSGESTURE_FLAG_INERTIA: number; + MSGESTURE_FLAG_NONE: number; +} + +interface HTMLAnchorElement { + text: string; +} + +interface HTMLInputElement { + validationMessage: string; + files: FileList; + max: string; + formTarget: string; + willValidate: bool; + step: string; + autofocus: bool; + required: bool; + formEnctype: string; + valueAsNumber: number; + placeholder: string; + formMethod: string; + list: HTMLElement; + autocomplete: string; + min: string; + formAction: string; + pattern: string; + validity: ValidityState; + formNoValidate: string; + multiple: bool; + checkValidity(): bool; + stepDown(n?: number): void; + stepUp(n?: number): void; + setCustomValidity(error: string): void; +} + +interface ErrorEvent extends Event { + colno: number; + filename: string; + lineno: number; + message: string; + initErrorEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, messageArg: string, filenameArg: string, linenoArg: number): void; +} +declare var ErrorEvent: { + prototype: ErrorEvent; + new(): ErrorEvent; +} + +interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGStylable, SVGLangSpace, SVGURIReference { + y: SVGAnimatedLength; + width: SVGAnimatedLength; + filterResX: SVGAnimatedInteger; + filterUnits: SVGAnimatedEnumeration; + primitiveUnits: SVGAnimatedEnumeration; + x: SVGAnimatedLength; + height: SVGAnimatedLength; + filterResY: SVGAnimatedInteger; + setFilterRes(filterResX: number, filterResY: number): void; +} +declare var SVGFilterElement: { + prototype: SVGFilterElement; + new(): SVGFilterElement; +} + +interface TrackEvent extends Event { + track: any; +} +declare var TrackEvent: { + prototype: TrackEvent; + new(): TrackEvent; +} + +interface SVGFEMergeNodeElement extends SVGElement { + in1: SVGAnimatedString; +} +declare var SVGFEMergeNodeElement: { + prototype: SVGFEMergeNodeElement; + new(): SVGFEMergeNodeElement; +} + +interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { +} +declare var SVGFEFloodElement: { + prototype: SVGFEFloodElement; + new(): SVGFEFloodElement; +} + +interface MSElementExtensions { + msRegionOverflow: string; + onmspointerdown: (ev: any) => any; + onmsgotpointercapture: (ev: any) => any; + onmsgesturedoubletap: (ev: any) => any; + onmspointerhover: (ev: any) => any; + onmsgesturehold: (ev: any) => any; + onmspointermove: (ev: any) => any; + onmsgesturechange: (ev: any) => any; + onmsgesturestart: (ev: any) => any; + onmspointercancel: (ev: any) => any; + onmsgestureend: (ev: any) => any; + onmsgesturetap: (ev: any) => any; + onmspointerout: (ev: any) => any; + onmsinertiastart: (ev: any) => any; + onmslostpointercapture: (ev: any) => any; + onmspointerover: (ev: any) => any; + msContentZoomFactor: number; + onmspointerup: (ev: any) => any; + msGetRegionContent(): MSRangeCollection; + msReleasePointerCapture(pointerId: number): void; + msSetPointerCapture(pointerId: number): void; +} +declare var MSElementExtensions: { + prototype: MSElementExtensions; + new(): MSElementExtensions; +} + +interface MSCSSScrollTranslationProperties { + msScrollTranslation: string; +} + +interface MSGesture { + target: Element; + addPointer(pointerId: number): void; + stop(): void; +} +declare var MSGesture: { + prototype: MSGesture; + new (): MSGesture; +} + +interface TextTrackCue extends EventTarget { + onenter: (ev: Event) => any; + track: TextTrack; + endTime: number; + text: string; + pauseOnExit: bool; + id: string; + startTime: number; + onexit: (ev: Event) => any; + getCueAsHTML(): DocumentFragment; +} +declare var TextTrackCue: { + prototype: TextTrackCue; + new(): TextTrackCue; +} + +interface MSHTMLDocumentViewExtensions { + msCSSOMElementFloatMetrics: bool; + msElementsFromPoint(x: number, y: number): NodeList; + msElementsFromRect(left: number, top: number, width: number, height: number): NodeList; +} +declare var MSHTMLDocumentViewExtensions: { + prototype: MSHTMLDocumentViewExtensions; + new(): MSHTMLDocumentViewExtensions; +} + +interface MSStreamReader extends MSBaseReader { + error: DOMError; + readAsArrayBuffer(stream: MSStream, size?: number): void; + readAsBlob(stream: MSStream, size?: number): void; + readAsDataURL(stream: MSStream, size?: number): void; + readAsText(stream: MSStream, encoding?: string, size?: number): void; +} +declare var MSStreamReader: { + prototype: MSStreamReader; + new (): MSStreamReader; +} + +interface CSSFlexibleBoxProperties { + msFlex: string; + msFlexDirection: string; + msFlexNegative: string; + msFlexPack: string; + msFlexWrap: string; + msFlexItemAlign: string; + msFlexOrder: string; + msFlexPositive: string; + msFlexAlign: string; + msFlexFlow: string; + msFlexPreferredSize: string; + msFlexLinePack: string; +} + +interface DOMTokenList { + length: number; + contains(token: string): bool; + remove(token: string): void; + toggle(token: string): bool; + add(token: string): void; + item(index: number): string; + [index: number]: string; + toString(): string; +} +declare var DOMTokenList: { + prototype: DOMTokenList; + new(): DOMTokenList; +} + +interface EventException { + name: string; +} + +interface SVGFEFuncAElement extends SVGComponentTransferFunctionElement { +} +declare var SVGFEFuncAElement: { + prototype: SVGFEFuncAElement; + new(): SVGFEFuncAElement; +} + +interface Performance { + now(): number; +} + +interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + in1: SVGAnimatedString; +} +declare var SVGFETileElement: { + prototype: SVGFETileElement; + new(): SVGFETileElement; +} + +interface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + in2: SVGAnimatedString; + mode: SVGAnimatedEnumeration; + in1: SVGAnimatedString; + SVG_FEBLEND_MODE_DARKEN: number; + SVG_FEBLEND_MODE_UNKNOWN: number; + SVG_FEBLEND_MODE_MULTIPLY: number; + SVG_FEBLEND_MODE_NORMAL: number; + SVG_FEBLEND_MODE_SCREEN: number; + SVG_FEBLEND_MODE_LIGHTEN: number; +} +declare var SVGFEBlendElement: { + prototype: SVGFEBlendElement; + new(): SVGFEBlendElement; + SVG_FEBLEND_MODE_DARKEN: number; + SVG_FEBLEND_MODE_UNKNOWN: number; + SVG_FEBLEND_MODE_MULTIPLY: number; + SVG_FEBLEND_MODE_NORMAL: number; + SVG_FEBLEND_MODE_SCREEN: number; + SVG_FEBLEND_MODE_LIGHTEN: number; +} + +interface WindowTimers extends WindowTimersExtension { +} +declare var WindowTimers: { + prototype: WindowTimers; + new(): WindowTimers; +} + +interface CSSStyleDeclaration extends CSS2DTransformsProperties, CSSTransitionsProperties, CSSFontsProperties, MSCSSHighContrastProperties, CSSGridProperties, CSSAnimationsProperties, MSCSSContentZoomProperties, MSCSSScrollTranslationProperties, MSCSSTouchManipulationProperties, CSSFlexibleBoxProperties, MSCSSPositionedFloatsProperties, MSCSSRegionProperties, MSCSSSelectionBoundaryProperties, CSSMultiColumnProperties, CSSTextProperties, CSS3DTransformsProperties { +} + +interface MessageChannel { + port2: MessagePort; + port1: MessagePort; +} +declare var MessageChannel: { + prototype: MessageChannel; + new (): MessageChannel; +} + +interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { +} +declare var SVGFEMergeElement: { + prototype: SVGFEMergeElement; + new(): SVGFEMergeElement; +} + +interface Navigator extends MSFileSaver { +} + +interface TransitionEvent extends Event { + propertyName: string; + elapsedTime: number; + initTransitionEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, propertyNameArg: string, elapsedTimeArg: number): void; +} +declare var TransitionEvent: { + prototype: TransitionEvent; + new(): TransitionEvent; +} + +interface MediaQueryList { + matches: bool; + media: string; + addListener(listener: MediaQueryListListener): void; + removeListener(listener: MediaQueryListListener): void; +} +declare var MediaQueryList: { + prototype: MediaQueryList; + new(): MediaQueryList; +} + +interface DOMError { + name: string; + toString(): string; +} +declare var DOMError: { + prototype: DOMError; + new(): DOMError; +} + +interface SVGFEPointLightElement extends SVGElement { + y: SVGAnimatedNumber; + x: SVGAnimatedNumber; + z: SVGAnimatedNumber; +} +declare var SVGFEPointLightElement: { + prototype: SVGFEPointLightElement; + new(): SVGFEPointLightElement; +} + +interface CSSFontsProperties { + msFontFeatureSettings: string; + fontFeatureSettings: string; +} + +interface CloseEvent extends Event { + wasClean: bool; + reason: string; + code: number; + initCloseEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, wasCleanArg: bool, codeArg: number, reasonArg: string): void; +} +declare var CloseEvent: { + prototype: CloseEvent; + new(): CloseEvent; +} + +interface WebSocket extends EventTarget { + protocol: string; + readyState: number; + bufferedAmount: number; + onopen: (ev: Event) => any; + extensions: string; + onmessage: (ev: any) => any; + onclose: (ev: CloseEvent) => any; + onerror: (ev: ErrorEvent) => any; + binaryType: string; + url: string; + close(code?: number, reason?: string): void; + send(data: any): void; + OPEN: number; + CLOSING: number; + CONNECTING: number; + CLOSED: number; +} +declare var WebSocket: { + prototype: WebSocket; + new (url: string): WebSocket; + new (url: string, prototcol: string): WebSocket; + new (url: string, prototcol: string[]): WebSocket; + OPEN: number; + CLOSING: number; + CONNECTING: number; + CLOSED: number; +} + +interface ProgressEvent extends Event { + loaded: number; + lengthComputable: bool; + total: number; + initProgressEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, lengthComputableArg: bool, loadedArg: number, totalArg: number): void; +} +declare var ProgressEvent: { + prototype: ProgressEvent; + new(): ProgressEvent; +} + +interface HTMLCanvasElement { + msToBlob(): Blob; +} + +interface IDBObjectStore { + indexNames: DOMStringList; + name: string; + transaction: IDBTransaction; + keyPath: string; + count(key?: any): IDBRequest; + add(value: any, key?: any): IDBRequest; + clear(): IDBRequest; + createIndex(name: string, keyPath: string, optionalParameters?: any): IDBIndex; + put(value: any, key?: any): IDBRequest; + openCursor(range?: any, direction?: string): IDBRequest; + deleteIndex(indexName: string): void; + index(name: string): IDBIndex; + get(key: any): IDBRequest; + delet(key: any): IDBRequest; +} +declare var IDBObjectStore: { + prototype: IDBObjectStore; + new(): IDBObjectStore; +} + +interface ObjectURLOptions { + oneTimeOnly?: bool; +} + +interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + stdDeviationX: SVGAnimatedNumber; + in1: SVGAnimatedString; + stdDeviationY: SVGAnimatedNumber; + setStdDeviation(stdDeviationX: number, stdDeviationY: number): void; +} +declare var SVGFEGaussianBlurElement: { + prototype: SVGFEGaussianBlurElement; + new(): SVGFEGaussianBlurElement; +} + +interface MSHTMLDocumentExtensions { + onmspointerdown: (ev: any) => any; + onmspointercancel: (ev: any) => any; + onmsgesturedoubletap: (ev: any) => any; + onmsgesturetap: (ev: any) => any; + onmsgestureend: (ev: any) => any; + onmspointerout: (ev: any) => any; + onmsmanipulationstatechanged: (ev: any) => any; + onmsinertiastart: (ev: any) => any; + onmspointerhover: (ev: any) => any; + onmscontentzoom: (ev: any) => any; + onmsgesturehold: (ev: any) => any; + onmspointermove: (ev: any) => any; + onmspointerover: (ev: any) => any; + onmsgesturechange: (ev: any) => any; + onmsgesturestart: (ev: any) => any; + onmspointerup: (ev: any) => any; +} +declare var MSHTMLDocumentExtensions: { + prototype: MSHTMLDocumentExtensions; + new(): MSHTMLDocumentExtensions; +} + +interface MSCSSSelectionBoundaryProperties { + msUserSelect: string; +} + +interface SVGFilterPrimitiveStandardAttributes extends SVGStylable { + y: SVGAnimatedLength; + width: SVGAnimatedLength; + x: SVGAnimatedLength; + height: SVGAnimatedLength; + result: SVGAnimatedString; +} + +interface IDBVersionChangeEvent extends Event { + newVersion: number; + oldVersion: number; +} +declare var IDBVersionChangeEvent: { + prototype: IDBVersionChangeEvent; + new(): IDBVersionChangeEvent; +} + +interface IDBIndex { + unique: bool; + name: string; + keyPath: string; + objectStore: IDBObjectStore; + count(key?: any): IDBRequest; + getKey(key: any): IDBRequest; + openKeyCursor(range?: IDBKeyRange, direction?: string): IDBRequest; + get(key: any): IDBRequest; + openCursor(range?: IDBKeyRange, direction?: string): IDBRequest; +} +declare var IDBIndex: { + prototype: IDBIndex; + new(): IDBIndex; +} + +interface FileList { + length: number; + item(index: number): File; + [index: number]: File; +} +declare var FileList: { + prototype: FileList; + new(): FileList; +} + +interface IDBCursor { + source: any; + direction: string; + key: any; + primaryKey: any; + advance(count: number): void; + delet(): IDBRequest; + continu(key?: any): void; + update(value: any): IDBRequest; +} +declare var IDBCursor: { + prototype: IDBCursor; + new(): IDBCursor; +} + +interface CSSAnimationsProperties { + animationFillMode: string; + msAnimationDirection: string; + msAnimationDelay: string; + msAnimationFillMode: string; + animationIterationCount: string; + msAnimationPlayState: string; + msAnimationIterationCount: string; + animationDelay: string; + animationTimingFunction: string; + msAnimation: string; + animation: string; + animationDirection: string; + animationDuration: string; + animationName: string; + animationPlayState: string; + msAnimationTimingFunction: string; + msAnimationName: string; + msAnimationDuration: string; +} + +interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + kernelUnitLengthY: SVGAnimatedNumber; + surfaceScale: SVGAnimatedNumber; + specularExponent: SVGAnimatedNumber; + in1: SVGAnimatedString; + kernelUnitLengthX: SVGAnimatedNumber; + specularConstant: SVGAnimatedNumber; +} +declare var SVGFESpecularLightingElement: { + prototype: SVGFESpecularLightingElement; + new(): SVGFESpecularLightingElement; +} + +interface File extends Blob { + lastModifiedDate: any; + name: string; +} +declare var File: { + prototype: File; + new(): File; +} + +interface URL { + revokeObjectURL(url: string): void; + createObjectURL(object: any, options?: ObjectURLOptions): string; +} +declare var URL: URL; + +interface RangeException { + name: string; +} + +interface IDBCursorWithValue extends IDBCursor { + value: any; +} +declare var IDBCursorWithValue: { + prototype: IDBCursorWithValue; + new(): IDBCursorWithValue; +} + +interface HTMLTextAreaElement { + validationMessage: string; + autofocus: bool; + validity: ValidityState; + required: bool; + maxLength: number; + willValidate: bool; + placeholder: string; + checkValidity(): bool; + setCustomValidity(error: string): void; +} + +interface XMLHttpRequestEventTarget extends EventTarget { + onprogress: (ev: ProgressEvent) => any; + onerror: (ev: ErrorEvent) => any; + onload: (ev: any) => any; + ontimeout: (ev: any) => any; + onabort: (ev: any) => any; + onloadstart: (ev: any) => any; + onloadend: (ev: ProgressEvent) => any; +} +declare var XMLHttpRequestEventTarget: { + prototype: XMLHttpRequestEventTarget; + new(): XMLHttpRequestEventTarget; +} + +interface IDBEnvironment { + msIndexedDB: IDBFactory; + indexedDB: IDBFactory; +} + +interface AudioTrackList extends EventTarget { + length: number; + onchange: (ev: any) => any; + onaddtrack: (ev: TrackEvent) => any; + getTrackById(id: string): AudioTrack; + item(index: number): AudioTrack; + [index: number]: AudioTrack; +} +declare var AudioTrackList: { + prototype: AudioTrackList; + new(): AudioTrackList; +} + +interface MSBaseReader extends EventTarget { + onprogress: (ev: ProgressEvent) => any; + readyState: number; + onabort: (ev: any) => any; + onloadend: (ev: ProgressEvent) => any; + onerror: (ev: ErrorEvent) => any; + onload: (ev: any) => any; + onloadstart: (ev: any) => any; + result: any; + abort(): void; + LOADING: number; + EMPTY: number; + DONE: number; +} + +interface History { + state: any; + replaceState(statedata: any, title: string, url?: string): void; + pushState(statedata: any, title: string, url?: string): void; +} + +interface MSProtocol { + protocol: string; +} +declare var MSProtocol: { + prototype: MSProtocol; + new(): MSProtocol; +} + +interface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + operator: SVGAnimatedEnumeration; + radiusX: SVGAnimatedNumber; + radiusY: SVGAnimatedNumber; + in1: SVGAnimatedString; + SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; + SVG_MORPHOLOGY_OPERATOR_ERODE: number; + SVG_MORPHOLOGY_OPERATOR_DILATE: number; +} +declare var SVGFEMorphologyElement: { + prototype: SVGFEMorphologyElement; + new(): SVGFEMorphologyElement; + SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; + SVG_MORPHOLOGY_OPERATOR_ERODE: number; + SVG_MORPHOLOGY_OPERATOR_DILATE: number; +} + +interface HTMLSelectElement { + validationMessage: string; + autofocus: bool; + validity: ValidityState; + required: bool; + willValidate: bool; + checkValidity(): bool; + setCustomValidity(error: string): void; +} + +interface CSSTransitionsProperties { + transition: string; + transitionDelay: string; + transitionDuration: string; + msTransitionTimingFunction: string; + msTransition: string; + msTransitionDuration: string; + transitionTimingFunction: string; + msTransitionDelay: string; + transitionProperty: string; + msTransitionProperty: string; +} + +interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { +} +declare var SVGFEFuncRElement: { + prototype: SVGFEFuncRElement; + new(): SVGFEFuncRElement; +} + +interface CSSRule { + KEYFRAMES_RULE: number; + KEYFRAME_RULE: number; + VIEWPORT_RULE: number; +} +//declare var CSSRule: { +// KEYFRAMES_RULE: number; +// KEYFRAME_RULE: number; +// VIEWPORT_RULE: number; +//} + +interface WindowTimersExtension { + msSetImmediate(expression: any, ...args: any[]): number; + clearImmediate(handle: number): void; + msClearImmediate(handle: number): void; + setImmediate(expression: any, ...args: any[]): number; +} + +interface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + in2: SVGAnimatedString; + xChannelSelector: SVGAnimatedEnumeration; + yChannelSelector: SVGAnimatedEnumeration; + scale: SVGAnimatedNumber; + in1: SVGAnimatedString; + SVG_CHANNEL_B: number; + SVG_CHANNEL_R: number; + SVG_CHANNEL_G: number; + SVG_CHANNEL_UNKNOWN: number; + SVG_CHANNEL_A: number; +} +declare var SVGFEDisplacementMapElement: { + prototype: SVGFEDisplacementMapElement; + new(): SVGFEDisplacementMapElement; + SVG_CHANNEL_B: number; + SVG_CHANNEL_R: number; + SVG_CHANNEL_G: number; + SVG_CHANNEL_UNKNOWN: number; + SVG_CHANNEL_A: number; +} + +interface MSCSSContentZoomProperties { + msContentZoomLimit: string; + msContentZooming: string; + msContentZoomSnapType: string; + msContentZoomLimitMax: any; + msContentZoomSnapPoints: string; + msContentZoomSnap: string; + msContentZoomLimitMin: any; + msContentZoomChaining: string; +} + +interface AnimationEvent extends Event { + animationName: string; + elapsedTime: number; + initAnimationEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, animationNameArg: string, elapsedTimeArg: number): void; +} +declare var AnimationEvent: { + prototype: AnimationEvent; + new(): AnimationEvent; +} + +interface SVGComponentTransferFunctionElement extends SVGElement { + tableValues: SVGAnimatedNumberList; + slope: SVGAnimatedNumber; + type: SVGAnimatedEnumeration; + exponent: SVGAnimatedNumber; + amplitude: SVGAnimatedNumber; + intercept: SVGAnimatedNumber; + offset: SVGAnimatedNumber; + SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; + SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; + SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY: number; + SVG_FECOMPONENTTRANSFER_TYPE_GAMMA: number; + SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE: number; + SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; +} +declare var SVGComponentTransferFunctionElement: { + prototype: SVGComponentTransferFunctionElement; + new(): SVGComponentTransferFunctionElement; + SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; + SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; + SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY: number; + SVG_FECOMPONENTTRANSFER_TYPE_GAMMA: number; + SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE: number; + SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; +} + +interface MSRangeCollection { + length: number; + item(index: number): Range; + [index: number]: Range; +} +declare var MSRangeCollection: { + prototype: MSRangeCollection; + new(): MSRangeCollection; +} + +interface MSHTMLElementExtensions { + onmscontentzoom: (ev: any) => any; + onmsmanipulationstatechanged: (ev: any) => any; +} +declare var MSHTMLElementExtensions: { + prototype: MSHTMLElementExtensions; + new(): MSHTMLElementExtensions; +} + +interface MSCSSPositionedFloatsProperties { + msWrapMargin: any; + msWrapFlow: string; +} + +interface SVGException { + name: string; +} + +interface SVGFEDistantLightElement extends SVGElement { + azimuth: SVGAnimatedNumber; + elevation: SVGAnimatedNumber; +} +declare var SVGFEDistantLightElement: { + prototype: SVGFEDistantLightElement; + new(): SVGFEDistantLightElement; +} + +interface MSCSSRegionProperties { + msFlowFrom: string; + msFlowInto: string; + msWrapThrough: string; +} + +interface SVGFEFuncBElement extends SVGComponentTransferFunctionElement { +} +declare var SVGFEFuncBElement: { + prototype: SVGFEFuncBElement; + new(): SVGFEFuncBElement; +} + +interface IDBKeyRange { + upper: any; + upperOpen: bool; + lower: any; + lowerOpen: bool; + bound(lower: any, upper: any, lowerOpen?: bool, upperOpen?: bool): IDBKeyRange; + only(value: any): IDBKeyRange; + lowerBound(bound: any, open?: bool): IDBKeyRange; + upperBound(bound: any, open?: bool): IDBKeyRange; +} +declare var IDBKeyRange: { + prototype: IDBKeyRange; + new(): IDBKeyRange; +} + +interface WindowConsole { + console: Console; +} + +interface SVG1_1Properties { + floodOpacity: string; + floodColor: string; + filter: string; + lightingColor: string; + enableBackground: string; + colorInterpolationFilters: string; +} +declare var SVG1_1Properties: { + prototype: SVG1_1Properties; + new(): SVG1_1Properties; +} + +interface IDBTransaction extends EventTarget { + oncomplete: (ev: Event) => any; + db: IDBDatabase; + mode: string; + error: DOMError; + onerror: (ev: ErrorEvent) => any; + onabort: (ev: any) => any; + abort(): void; + objectStore(name: string): IDBObjectStore; +} +declare var IDBTransaction: { + prototype: IDBTransaction; + new(): IDBTransaction; +} + +interface MSWindowExtensions { + onmspointerdown: (ev: any) => any; + onmspointercancel: (ev: any) => any; + onmsgesturedoubletap: (ev: any) => any; + onmsgestureend: (ev: any) => any; + onmsgesturetap: (ev: any) => any; + onmspointerout: (ev: any) => any; + onmspointerhover: (ev: any) => any; + onmsinertiastart: (ev: any) => any; + onmspointermove: (ev: any) => any; + onmsgesturehold: (ev: any) => any; + onmspointerover: (ev: any) => any; + onmsgesturechange: (ev: any) => any; + onmsgesturestart: (ev: any) => any; + onmspointerup: (ev: any) => any; + msIsStaticHTML(html: string): bool; +} +declare var MSWindowExtensions: { + prototype: MSWindowExtensions; + new(): MSWindowExtensions; +} + +interface AudioTrack { + kind: string; + language: string; + id: string; + label: string; + enabled: bool; +} +declare var AudioTrack: { + prototype: AudioTrack; + new(): AudioTrack; +} + +interface SVGFEConvolveMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + orderY: SVGAnimatedInteger; + kernelUnitLengthY: SVGAnimatedNumber; + orderX: SVGAnimatedInteger; + preserveAlpha: SVGAnimatedBoolean; + kernelMatrix: SVGAnimatedNumberList; + edgeMode: SVGAnimatedEnumeration; + kernelUnitLengthX: SVGAnimatedNumber; + bias: SVGAnimatedNumber; + targetX: SVGAnimatedInteger; + targetY: SVGAnimatedInteger; + divisor: SVGAnimatedNumber; + in1: SVGAnimatedString; + SVG_EDGEMODE_WRAP: number; + SVG_EDGEMODE_DUPLICATE: number; + SVG_EDGEMODE_UNKNOWN: number; + SVG_EDGEMODE_NONE: number; +} +declare var SVGFEConvolveMatrixElement: { + prototype: SVGFEConvolveMatrixElement; + new(): SVGFEConvolveMatrixElement; + SVG_EDGEMODE_WRAP: number; + SVG_EDGEMODE_DUPLICATE: number; + SVG_EDGEMODE_UNKNOWN: number; + SVG_EDGEMODE_NONE: number; +} + +interface TextTrackCueList { + length: number; + item(index: number): TextTrackCue; + [index: number]: TextTrackCue; + getCueById(id: string): TextTrackCue; +} +declare var TextTrackCueList: { + prototype: TextTrackCueList; + new(): TextTrackCueList; +} + +interface CSSKeyframesRule extends CSSRule { + name: string; + cssRules: CSSRuleList; + findRule(rule: string): CSSKeyframeRule; + deleteRule(rule: string): void; + appendRule(rule: string): void; +} +declare var CSSKeyframesRule: { + prototype: CSSKeyframesRule; + new(): CSSKeyframesRule; +} + +interface MSCSSTouchManipulationProperties { + msScrollSnapPointsY: string; + msOverflowStyle: string; + msScrollLimitXMax: any; + msScrollSnapType: string; + msScrollSnapPointsX: string; + msScrollLimitYMax: any; + msScrollSnapY: string; + msScrollLimitXMin: any; + msScrollLimitYMin: any; + msScrollChaining: string; + msTouchAction: string; + msScrollSnapX: string; + msScrollLimit: string; + msScrollRails: string; + msTouchSelect: string; +} + +interface Window extends WindowAnimationTiming, WindowBase64, IDBEnvironment, WindowConsole { + onpopstate: (ev: PopStateEvent) => any; + applicationCache: ApplicationCache; + matchMedia(mediaQuery: string): MediaQueryList; + msMatchMedia(mediaQuery: string): MediaQueryList; +} + +interface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + baseFrequencyX: SVGAnimatedNumber; + numOctaves: SVGAnimatedInteger; + type: SVGAnimatedEnumeration; + baseFrequencyY: SVGAnimatedNumber; + stitchTiles: SVGAnimatedEnumeration; + seed: SVGAnimatedNumber; + SVG_STITCHTYPE_UNKNOWN: number; + SVG_STITCHTYPE_NOSTITCH: number; + SVG_TURBULENCE_TYPE_UNKNOWN: number; + SVG_TURBULENCE_TYPE_TURBULENCE: number; + SVG_TURBULENCE_TYPE_FRACTALNOISE: number; + SVG_STITCHTYPE_STITCH: number; +} +declare var SVGFETurbulenceElement: { + prototype: SVGFETurbulenceElement; + new(): SVGFETurbulenceElement; + SVG_STITCHTYPE_UNKNOWN: number; + SVG_STITCHTYPE_NOSTITCH: number; + SVG_TURBULENCE_TYPE_UNKNOWN: number; + SVG_TURBULENCE_TYPE_TURBULENCE: number; + SVG_TURBULENCE_TYPE_FRACTALNOISE: number; + SVG_STITCHTYPE_STITCH: number; +} + +interface TextTrackList { + length: number; + item(index: number): TextTrack; + [index: number]: TextTrack; +} +declare var TextTrackList: { + prototype: TextTrackList; + new(): TextTrackList; +} + +interface WindowAnimationTiming { + animationStartTime: number; + msAnimationStartTime: number; + msCancelRequestAnimationFrame(handle: number): void; + cancelAnimationFrame(handle: number): void; + requestAnimationFrame(callback: FrameRequestCallback): number; + msRequestAnimationFrame(callback: FrameRequestCallback): number; +} + +interface SVGFEFuncGElement extends SVGComponentTransferFunctionElement { +} +declare var SVGFEFuncGElement: { + prototype: SVGFEFuncGElement; + new(): SVGFEFuncGElement; +} + +interface SVGFEColorMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + in1: SVGAnimatedString; + type: SVGAnimatedEnumeration; + values: SVGAnimatedNumberList; + SVG_FECOLORMATRIX_TYPE_SATURATE: number; + SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; + SVG_FECOLORMATRIX_TYPE_MATRIX: number; + SVG_FECOLORMATRIX_TYPE_HUEROTATE: number; + SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA: number; +} +declare var SVGFEColorMatrixElement: { + prototype: SVGFEColorMatrixElement; + new(): SVGFEColorMatrixElement; + SVG_FECOLORMATRIX_TYPE_SATURATE: number; + SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; + SVG_FECOLORMATRIX_TYPE_MATRIX: number; + SVG_FECOLORMATRIX_TYPE_HUEROTATE: number; + SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA: number; +} + +interface Console { + info(): void; + info(message: any, ...optionalParams: any[]): void; + profile(reportName?: string): bool; + assert(): void; + assert(test: bool): void; + assert(test: bool, message: any, ...optionalParams: any[]): void; + msIsIndependentlyComposed(element: Element): bool; + clear(): bool; + dir(): bool; + dir(value: any, ...optionalParams: any[]): bool; + warn(): void; + warn(message: any, ...optionalParams: any[]): void; + error(): void; + error(message: any, ...optionalParams: any[]): void; + log(): void; + log(message: any, ...optionalParams: any[]): void; + profileEnd(): bool; +} +declare var Console: { + prototype: Console; + new(): Console; +} + +interface SVGFESpotLightElement extends SVGElement { + pointsAtY: SVGAnimatedNumber; + y: SVGAnimatedNumber; + limitingConeAngle: SVGAnimatedNumber; + specularExponent: SVGAnimatedNumber; + x: SVGAnimatedNumber; + pointsAtZ: SVGAnimatedNumber; + z: SVGAnimatedNumber; + pointsAtX: SVGAnimatedNumber; +} +declare var SVGFESpotLightElement: { + prototype: SVGFESpotLightElement; + new(): SVGFESpotLightElement; +} + +interface DocumentVisibility { + msHidden: bool; + msVisibilityState: string; + visibilityState: string; + hidden: bool; +} + +interface WindowBase64 { + btoa(rawString: string): string; + atob(encodedString: string): string; +} + +interface IDBDatabase extends EventTarget { + version: string; + name: string; + objectStoreNames: DOMStringList; + onerror: (ev: ErrorEvent) => any; + onabort: (ev: any) => any; + createObjectStore(name: string, optionalParameters?: any): IDBObjectStore; + close(): void; + transaction(storeNames: any, mode?: string): IDBTransaction; + deleteObjectStore(name: string): void; +} +declare var IDBDatabase: { + prototype: IDBDatabase; + new(): IDBDatabase; +} + +interface MSProtocolsCollection { +} +declare var MSProtocolsCollection: { + prototype: MSProtocolsCollection; + new(): MSProtocolsCollection; +} + +interface DOMStringList { + length: number; + contains(str: string): bool; + item(index: number): string; + [index: number]: string; +} +declare var DOMStringList: { + prototype: DOMStringList; + new(): DOMStringList; +} + +interface CSSMultiColumnProperties { + breakAfter: string; + columnSpan: string; + columnRule: string; + columnFill: string; + columnRuleStyle: string; + breakBefore: string; + columnCount: any; + breakInside: string; + columnWidth: any; + columns: string; + columnRuleColor: any; + columnGap: any; + columnRuleWidth: any; +} + +interface IDBOpenDBRequest extends IDBRequest { + onupgradeneeded: (ev: IDBVersionChangeEvent) => any; + onblocked: (ev: Event) => any; +} +declare var IDBOpenDBRequest: { + prototype: IDBOpenDBRequest; + new(): IDBOpenDBRequest; +} + +interface HTMLButtonElement { + validationMessage: string; + formTarget: string; + willValidate: bool; + formAction: string; + autofocus: bool; + validity: ValidityState; + formNoValidate: string; + formEnctype: string; + formMethod: string; + checkValidity(): bool; + setCustomValidity(error: string): void; +} + +interface HTMLProgressElement extends HTMLElement { + value: number; + max: number; + position: number; + form: HTMLFormElement; +} +declare var HTMLProgressElement: { + prototype: HTMLProgressElement; + new(): HTMLProgressElement; +} + +interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + dy: SVGAnimatedNumber; + in1: SVGAnimatedString; + dx: SVGAnimatedNumber; +} +declare var SVGFEOffsetElement: { + prototype: SVGFEOffsetElement; + new(): SVGFEOffsetElement; +} + +interface HTMLFormElement { + autocomplete: string; + noValidate: bool; + checkValidity(): bool; +} + +interface MSUnsafeFunctionCallback { + (): any; +} + +interface Document extends DocumentVisibility { +} + +interface MessageEvent extends Event { + ports: any; +} + +interface HTMLScriptElement { + async: bool; +} + +interface HTMLMediaElement extends MSHTMLMediaElementExtensions { + textTracks: TextTrackList; + audioTracks: AudioTrackList; +} + +interface TextTrack extends EventTarget { + language: string; + mode: number; + readyState: string; + activeCues: TextTrackCueList; + cues: TextTrackCueList; + oncuechange: (ev: Event) => any; + kind: string; + onload: (ev: any) => any; + onerror: (ev: ErrorEvent) => any; + label: string; + ERROR: number; + SHOWING: number; + LOADING: number; + LOADED: number; + NONE: number; + HIDDEN: number; + DISABLED: number; +} +declare var TextTrack: { + prototype: TextTrack; + new(): TextTrack; + ERROR: number; + SHOWING: number; + LOADING: number; + LOADED: number; + NONE: number; + HIDDEN: number; + DISABLED: number; +} + +interface MediaQueryListListener { + (mql: MediaQueryList): void; +} + +interface IDBRequest extends EventTarget { + source: any; + onsuccess: (ev: Event) => any; + error: DOMError; + transaction: IDBTransaction; + onerror: (ev: ErrorEvent) => any; + readyState: string; + result: any; +} +declare var IDBRequest: { + prototype: IDBRequest; + new(): IDBRequest; +} + +interface MessagePort extends EventTarget { + onmessage: (ev: any) => any; + close(): void; + postMessage(message: any, ports?: any): void; + start(): void; +} +declare var MessagePort: { + prototype: MessagePort; + new(): MessagePort; +} + +interface FileReader extends MSBaseReader { + error: DOMError; + readAsArrayBuffer(blob: Blob): void; + readAsDataURL(blob: Blob): void; + readAsText(blob: Blob, encoding?: string): void; +} +declare var FileReader: { + prototype: FileReader; + new (): FileReader; +} + +interface Blob { + type: string; + size: number; + msDetachStream(): any; + slice(start?: number, end?: number, contentType?: string): Blob; + msClose(): void; +} +declare var Blob: { + prototype: Blob; + new (): Blob; +} + +interface ApplicationCache extends EventTarget { + status: number; + ondownloading: (ev: Event) => any; + onprogress: (ev: ProgressEvent) => any; + onupdateready: (ev: Event) => any; + oncached: (ev: Event) => any; + onobsolete: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; + onchecking: (ev: Event) => any; + onnoupdate: (ev: Event) => any; + swapCache(): void; + abort(): void; + update(): void; + CHECKING: number; + UNCACHED: number; + UPDATEREADY: number; + DOWNLOADING: number; + IDLE: number; + OBSOLETE: number; +} +declare var ApplicationCache: { + prototype: ApplicationCache; + new(): ApplicationCache; + CHECKING: number; + UNCACHED: number; + UPDATEREADY: number; + DOWNLOADING: number; + IDLE: number; + OBSOLETE: number; +} + +interface MSHTMLVideoElementExtensions { + msIsStereo3D: bool; + msStereo3DPackingMode: string; + onMSVideoOptimalLayoutChanged: (ev: any) => any; + onMSVideoFrameStepCompleted: (ev: any) => any; + msStereo3DRenderMode: string; + msIsLayoutOptimalForPlayback: bool; + msHorizontalMirror: bool; + onMSVideoFormatChanged: (ev: any) => any; + msZoom: bool; + msInsertVideoEffect(activatableClassId: string, effectRequired: bool, config?: any): void; + msSetVideoRectangle(left: number, top: number, right: number, bottom: number): void; + msFrameStep(forward: bool): void; +} + +interface FrameRequestCallback { + (time: number): void; +} + +interface CSS3DTransformsProperties { + perspective: string; + msBackfaceVisibility: string; + perspectiveOrigin: string; + transformStyle: string; + backfaceVisibility: string; + msPerspectiveOrigin: string; + msTransformStyle: string; + msPerspective: string; +} + +interface XMLHttpRequest { + withCredentials: bool; +} + +interface PopStateEvent extends Event { + state: any; + initPopStateEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, stateArg: any): void; +} +declare var PopStateEvent: { + prototype: PopStateEvent; + new(): PopStateEvent; +} + +interface CSSKeyframeRule extends CSSRule { + keyText: string; + style: CSSStyleDeclaration; +} +declare var CSSKeyframeRule: { + prototype: CSSKeyframeRule; + new(): CSSKeyframeRule; +} + +interface CSSGridProperties { + msGridRows: string; + msGridColumnSpan: any; + msGridRow: any; + msGridRowSpan: any; + msGridColumns: string; + msGridColumnAlign: string; + msGridRowAlign: string; + msGridColumn: any; +} + +interface MSFileSaver { + msSaveBlob(blob: any, defaultName?: string): bool; + msSaveOrOpenBlob(blob: any, defaultName?: string): bool; +} + +interface MSStream { + type: string; + msDetachStream(): any; + msClose(): void; +} +declare var MSStream: { + prototype: MSStream; + new(): MSStream; +} + +interface MediaError extends MSMediaErrorExtensions { +} + +interface HTMLFieldSetElement { + validationMessage: string; + validity: ValidityState; + willValidate: bool; + checkValidity(): bool; + setCustomValidity(error: string): void; +} + +interface MSBlobBuilder { + append(data: any, endings?: string): void; + getBlob(contentType?: string): Blob; +} +declare var MSBlobBuilder: { + prototype: MSBlobBuilder; + new (): MSBlobBuilder; +} + +interface MSRangeExtensions { + createContextualFragment(fragment: string): DocumentFragment; +} + +interface HTMLElement { + oncuechange: (ev: Event) => any; + spellcheck: bool; + classList: DOMTokenList; + draggable: bool; +} + +interface DataTransfer { + types: DOMStringList; + files: FileList; +} + +interface DOMSettableTokenList extends DOMTokenList { + value: string; +} +declare var DOMSettableTokenList: { + prototype: DOMSettableTokenList; + new(): DOMSettableTokenList; +} + +interface IDBFactory { + open(name: string, version?: number): IDBOpenDBRequest; + cmp(first: any, second: any): number; + deleteDatabase(name: string): IDBOpenDBRequest; +} +declare var IDBFactory: { + prototype: IDBFactory; + new(): IDBFactory; +} + +interface Range extends MSRangeExtensions { +} + +interface HTMLObjectElement { + validationMessage: string; + validity: ValidityState; + willValidate: bool; + checkValidity(): bool; + setCustomValidity(error: string): void; +} + +interface MSPointerEvent extends MouseEvent { + width: number; + rotation: number; + pressure: number; + pointerType: number; + isPrimary: bool; + tiltY: number; + height: number; + intermediatePoints: any; + currentPoint: any; + tiltX: number; + hwTimestamp: number; + pointerId: number; + initPointerEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: bool, altKeyArg: bool, shiftKeyArg: bool, metaKeyArg: bool, buttonArg: number, relatedTargetArg: EventTarget, offsetXArg: number, offsetYArg: number, widthArg: number, heightArg: number, pressure: number, rotation: number, tiltX: number, tiltY: number, pointerIdArg: number, pointerType: number, hwTimestampArg: number, isPrimary: bool): void; + getCurrentPoint(element: Element): void; + getIntermediatePoints(element: Element): void; + MSPOINTER_TYPE_PEN: number; + MSPOINTER_TYPE_MOUSE: number; + MSPOINTER_TYPE_TOUCH: number; +} +declare var MSPointerEvent: { + prototype: MSPointerEvent; + new(): MSPointerEvent; + MSPOINTER_TYPE_PEN: number; + MSPOINTER_TYPE_MOUSE: number; + MSPOINTER_TYPE_TOUCH: number; +} + +interface CSSTextProperties { + textShadow: string; + msHyphenateLimitLines: any; + msHyphens: string; + msHyphenateLimitChars: string; + msHyphenateLimitZone: any; +} + +interface CSS2DTransformsProperties { + transform: string; + transformOrigin: string; +} + +interface DOMException { + name: string; + INVALID_NODE_TYPE_ERR: number; + DATA_CLONE_ERR: number; + TIMEOUT_ERR: number; +} +//declare var DOMException: { +// INVALID_NODE_TYPE_ERR: number; +// DATA_CLONE_ERR: number; +// TIMEOUT_ERR: number; +//} + +interface MSCSSHighContrastProperties { + msHighContrastAdjust: string; +} + +interface MSManipulationEvent extends UIEvent { + lastState: number; + currentState: number; + initMSManipulationEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, detailArg: number, lastState: number, currentState: number): void; + MS_MANIPULATION_STATE_STOPPED: number; + MS_MANIPULATION_STATE_ACTIVE: number; + MS_MANIPULATION_STATE_INERTIA: number; +} +declare var MSManipulationEvent: { + prototype: MSManipulationEvent; + new(): MSManipulationEvent; + MS_MANIPULATION_STATE_STOPPED: number; + MS_MANIPULATION_STATE_ACTIVE: number; + MS_MANIPULATION_STATE_INERTIA: number; +} + +interface FormData { + append(name: any, value: any, blobName?: string): void; +} +declare var FormData: { + prototype: FormData; + new (): FormData; +} + +interface MSHTMLImageElementExtensions { + msPlayToPrimary: bool; + msPlayToDisabled: bool; + msPlayToSource: any; +} +declare var MSHTMLImageElementExtensions: { + prototype: MSHTMLImageElementExtensions; + new(): MSHTMLImageElementExtensions; +} + +interface MSHTMLMediaElementExtensions { + msAudioCategory: string; + msRealTime: bool; + msPlayToPrimary: bool; + msPlayToDisabled: bool; + msPlayToSource: any; + msAudioDeviceType: string; + msClearEffects(): void; + msSetMediaProtectionManager(mediaProtectionManager?: any): void; + msInsertAudioEffect(activatableClassId: string, effectRequired: bool, config?: any): void; +} + +interface SVGFEImageElement extends SVGElement, SVGLangSpace, SVGFilterPrimitiveStandardAttributes, SVGURIReference { + preserveAspectRatio: SVGAnimatedPreserveAspectRatio; +} +declare var SVGFEImageElement: { + prototype: SVGFEImageElement; + new(): SVGFEImageElement; +} + +interface HTMLDataListElement extends HTMLElement { + options: HTMLCollection; +} +declare var HTMLDataListElement: { + prototype: HTMLDataListElement; + new(): HTMLDataListElement; +} + +interface AbstractWorker extends EventTarget { + onerror: (ev: ErrorEvent) => any; +} + +interface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + operator: SVGAnimatedEnumeration; + in2: SVGAnimatedString; + k2: SVGAnimatedNumber; + k1: SVGAnimatedNumber; + k3: SVGAnimatedNumber; + in1: SVGAnimatedString; + k4: SVGAnimatedNumber; + SVG_FECOMPOSITE_OPERATOR_OUT: number; + SVG_FECOMPOSITE_OPERATOR_OVER: number; + SVG_FECOMPOSITE_OPERATOR_XOR: number; + SVG_FECOMPOSITE_OPERATOR_ARITHMETIC: number; + SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; + SVG_FECOMPOSITE_OPERATOR_IN: number; + SVG_FECOMPOSITE_OPERATOR_ATOP: number; +} +declare var SVGFECompositeElement: { + prototype: SVGFECompositeElement; + new(): SVGFECompositeElement; + SVG_FECOMPOSITE_OPERATOR_OUT: number; + SVG_FECOMPOSITE_OPERATOR_OVER: number; + SVG_FECOMPOSITE_OPERATOR_XOR: number; + SVG_FECOMPOSITE_OPERATOR_ARITHMETIC: number; + SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; + SVG_FECOMPOSITE_OPERATOR_IN: number; + SVG_FECOMPOSITE_OPERATOR_ATOP: number; +} + +interface ValidityState { + customError: bool; + valueMissing: bool; + stepMismatch: bool; + rangeUnderflow: bool; + rangeOverflow: bool; + typeMismatch: bool; + patternMismatch: bool; + tooLong: bool; + valid: bool; +} +declare var ValidityState: { + prototype: ValidityState; + new(): ValidityState; +} + +interface HTMLVideoElement extends MSHTMLVideoElementExtensions { +} + +interface HTMLTrackElement extends HTMLElement { + kind: string; + src: string; + srclang: string; + track: TextTrack; + label: string; + defaul: bool; +} +declare var HTMLTrackElement: { + prototype: HTMLTrackElement; + new(): HTMLTrackElement; +} + +interface MSApp { + createFileFromStorageFile(storageFile: any): File; + createBlobFromRandomAccessStream(type: string, seeker: any): Blob; + createStreamFromInputStream(type: string, inputStream: any): MSStream; + terminateApp(exceptionObject: any): void; + createDataPackage(object: any): any; + execUnsafeLocalFunction(unsafeFunction: MSUnsafeFunctionCallback): any; + getHtmlPrintDocumentSource(htmlDoc: any, printTemplate?: string): any; + addPublicLocalApplicationUri(uri: string): void; + createDataPackageFromSelection(): any; +} +declare var MSApp: MSApp; + +interface MSXMLHttpRequestExtensions { + response: any; + onprogress: (ev: ProgressEvent) => any; + onabort: (ev: any) => any; + responseType: string; + onloadend: (ev: ProgressEvent) => any; + upload: XMLHttpRequestEventTarget; + onerror: (ev: ErrorEvent) => any; + onloadstart: (ev: any) => any; +} +declare var MSXMLHttpRequestExtensions: { + prototype: MSXMLHttpRequestExtensions; + new(): MSXMLHttpRequestExtensions; +} + +interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + kernelUnitLengthY: SVGAnimatedNumber; + surfaceScale: SVGAnimatedNumber; + in1: SVGAnimatedString; + kernelUnitLengthX: SVGAnimatedNumber; + diffuseConstant: SVGAnimatedNumber; +} +declare var SVGFEDiffuseLightingElement: { + prototype: SVGFEDiffuseLightingElement; + new(): SVGFEDiffuseLightingElement; +} + +interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + in1: SVGAnimatedString; +} +declare var SVGFEComponentTransferElement: { + prototype: SVGFEComponentTransferElement; + new(): SVGFEComponentTransferElement; +} + +interface MSCSSMatrix { + m24: number; + m34: number; + a: number; + d: number; + m32: number; + m41: number; + m11: number; + f: number; + e: number; + m23: number; + m14: number; + m33: number; + m22: number; + m21: number; + c: number; + m12: number; + b: number; + m42: number; + m31: number; + m43: number; + m13: number; + m44: number; + multiply(secondMatrix: MSCSSMatrix): MSCSSMatrix; + skewY(angle: number): MSCSSMatrix; + setMatrixValue(value: string): void; + inverse(): MSCSSMatrix; + rotateAxisAngle(x: number, y: number, z: number, angle: number): MSCSSMatrix; + toString(): string; + rotate(angleX: number, angleY?: number, angleZ?: number): MSCSSMatrix; + translate(x: number, y: number, z?: number): MSCSSMatrix; + scale(scaleX: number, scaleY?: number, scaleZ?: number): MSCSSMatrix; + skewX(angle: number): MSCSSMatrix; +} +declare var MSCSSMatrix: { + prototype: MSCSSMatrix; + new (text?: string): MSCSSMatrix; +} + +interface Worker extends AbstractWorker { + onmessage: (ev: any) => any; + postMessage(message: any, ports?: any): void; + terminate(): void; +} +declare var Worker: { + prototype: Worker; + new (stringUrl: string): Worker; +} + +interface HTMLIFrameElement { + sandbox: DOMSettableTokenList; +} + +interface MSMediaErrorExtensions { + msExtendedCode: number; +} + +interface MSNavigatorAbilities { + msProtocols: MSProtocolsCollection; + msMaxTouchPoints: number; + msPointerEnabled: bool; + msManipulationViewsEnabled: bool; +} +declare var MSNavigatorAbilities: { + prototype: MSNavigatorAbilities; + new(): MSNavigatorAbilities; +} + +declare var onpopstate: (ev: PopStateEvent) => any; +declare var applicationCache: ApplicationCache; +declare function matchMedia(mediaQuery: string): MediaQueryList; +declare function msMatchMedia(mediaQuery: string): MediaQueryList; +declare var animationStartTime: number; +declare var msAnimationStartTime: number; +declare function msCancelRequestAnimationFrame(handle: number): void; +declare function cancelAnimationFrame(handle: number): void; +declare function requestAnimationFrame(callback: FrameRequestCallback): number; +declare function msRequestAnimationFrame(callback: FrameRequestCallback): number; +declare function btoa(rawString: string): string; +declare function atob(encodedString: string): string; +declare var msIndexedDB: IDBFactory; +declare var indexedDB: IDBFactory; +declare var console: Console; + + +///////////////////////////// +/// WorkerGlobalScope APIs +///////////////////////////// +// TODO: These are only available in a Web Worker - should be in a seperate lib file +declare function importScripts(...urls: string[]): void; + + +///////////////////////////// +/// Windows Script Host APIS +///////////////////////////// +declare var ActiveXObject: { new (s: string): any; }; + +interface ITextWriter { + Write(s: string): void; + WriteLine(s: string): void; + Close(): void; +} + +declare var WScript : { + Echo(s); + StdErr: ITextWriter; + StdOut: ITextWriter; + Arguments: { length: number; Item(n: number): string; }; + ScriptFullName: string; + Quit(exitCode?: number); +} + diff --git a/_infrastructure/tests/typescript_0.8.2/tsc b/_infrastructure/tests/typescript_0.8.2/tsc new file mode 100644 index 0000000000..3c0dab574f --- /dev/null +++ b/_infrastructure/tests/typescript_0.8.2/tsc @@ -0,0 +1,2 @@ +#!/usr/bin/env node +require('./tsc.js') diff --git a/_infrastructure/tests/typescript_0.8.2/tsc.js b/_infrastructure/tests/typescript_0.8.2/tsc.js new file mode 100644 index 0000000000..371ce6338f --- /dev/null +++ b/_infrastructure/tests/typescript_0.8.2/tsc.js @@ -0,0 +1,25756 @@ +/* ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + +var TypeScript; +(function (TypeScript) { + function hasFlag(val, flag) { + return (val & flag) != 0; + } + TypeScript.hasFlag = hasFlag; + (function (ErrorRecoverySet) { + ErrorRecoverySet._map = []; + ErrorRecoverySet.None = 0; + ErrorRecoverySet.Comma = 1; + ErrorRecoverySet.SColon = 1 << 1; + ErrorRecoverySet.Asg = 1 << 2; + ErrorRecoverySet.BinOp = 1 << 3; + ErrorRecoverySet.RBrack = 1 << 4; + ErrorRecoverySet.RCurly = 1 << 5; + ErrorRecoverySet.RParen = 1 << 6; + ErrorRecoverySet.Dot = 1 << 7; + ErrorRecoverySet.Colon = 1 << 8; + ErrorRecoverySet.PrimType = 1 << 9; + ErrorRecoverySet.AddOp = 1 << 10; + ErrorRecoverySet.LCurly = 1 << 11; + ErrorRecoverySet.PreOp = 1 << 12; + ErrorRecoverySet.RegExp = 1 << 13; + ErrorRecoverySet.LParen = 1 << 14; + ErrorRecoverySet.LBrack = 1 << 15; + ErrorRecoverySet.Scope = 1 << 16; + ErrorRecoverySet.In = 1 << 17; + ErrorRecoverySet.SCase = 1 << 18; + ErrorRecoverySet.Else = 1 << 19; + ErrorRecoverySet.Catch = 1 << 20; + ErrorRecoverySet.Var = 1 << 21; + ErrorRecoverySet.Stmt = 1 << 22; + ErrorRecoverySet.While = 1 << 23; + ErrorRecoverySet.ID = 1 << 24; + ErrorRecoverySet.Prefix = 1 << 25; + ErrorRecoverySet.Literal = 1 << 26; + ErrorRecoverySet.RLit = 1 << 27; + ErrorRecoverySet.Func = 1 << 28; + ErrorRecoverySet.EOF = 1 << 29; + ErrorRecoverySet.TypeScriptS = 1 << 30; + ErrorRecoverySet.ExprStart = ErrorRecoverySet.SColon | ErrorRecoverySet.AddOp | ErrorRecoverySet.LCurly | ErrorRecoverySet.PreOp | ErrorRecoverySet.RegExp | ErrorRecoverySet.LParen | ErrorRecoverySet.LBrack | ErrorRecoverySet.ID | ErrorRecoverySet.Prefix | ErrorRecoverySet.RLit | ErrorRecoverySet.Func | ErrorRecoverySet.Literal; + ErrorRecoverySet.StmtStart = ErrorRecoverySet.ExprStart | ErrorRecoverySet.SColon | ErrorRecoverySet.Var | ErrorRecoverySet.Stmt | ErrorRecoverySet.While | ErrorRecoverySet.TypeScriptS; + ErrorRecoverySet.Postfix = ErrorRecoverySet.Dot | ErrorRecoverySet.LParen | ErrorRecoverySet.LBrack; + })(TypeScript.ErrorRecoverySet || (TypeScript.ErrorRecoverySet = {})); + var ErrorRecoverySet = TypeScript.ErrorRecoverySet; + (function (AllowedElements) { + AllowedElements._map = []; + AllowedElements.None = 0; + AllowedElements.ModuleDeclarations = 1 << 2; + AllowedElements.ClassDeclarations = 1 << 3; + AllowedElements.InterfaceDeclarations = 1 << 4; + AllowedElements.AmbientDeclarations = 1 << 10; + AllowedElements.Properties = 1 << 11; + AllowedElements.Global = AllowedElements.ModuleDeclarations | AllowedElements.ClassDeclarations | AllowedElements.InterfaceDeclarations | AllowedElements.AmbientDeclarations; + AllowedElements.QuickParse = AllowedElements.Global | AllowedElements.Properties; + })(TypeScript.AllowedElements || (TypeScript.AllowedElements = {})); + var AllowedElements = TypeScript.AllowedElements; + (function (Modifiers) { + Modifiers._map = []; + Modifiers.None = 0; + Modifiers.Private = 1; + Modifiers.Public = 1 << 1; + Modifiers.Readonly = 1 << 2; + Modifiers.Ambient = 1 << 3; + Modifiers.Exported = 1 << 4; + Modifiers.Getter = 1 << 5; + Modifiers.Setter = 1 << 6; + Modifiers.Static = 1 << 7; + })(TypeScript.Modifiers || (TypeScript.Modifiers = {})); + var Modifiers = TypeScript.Modifiers; + (function (ASTFlags) { + ASTFlags._map = []; + ASTFlags.None = 0; + ASTFlags.ExplicitSemicolon = 1; + ASTFlags.AutomaticSemicolon = 1 << 1; + ASTFlags.Writeable = 1 << 2; + ASTFlags.Error = 1 << 3; + ASTFlags.DotLHSPartial = 1 << 4; + ASTFlags.DotLHS = 1 << 5; + ASTFlags.IsStatement = 1 << 6; + ASTFlags.StrictMode = 1 << 7; + ASTFlags.PossibleOptionalParameter = 1 << 8; + ASTFlags.ClassBaseConstructorCall = 1 << 9; + ASTFlags.OptionalName = 1 << 10; + ASTFlags.SkipNextRParen = 1 << 11; + })(TypeScript.ASTFlags || (TypeScript.ASTFlags = {})); + var ASTFlags = TypeScript.ASTFlags; + (function (DeclFlags) { + DeclFlags._map = []; + DeclFlags.None = 0; + DeclFlags.Exported = 1; + DeclFlags.Private = 1 << 1; + DeclFlags.Public = 1 << 2; + DeclFlags.Ambient = 1 << 3; + DeclFlags.Static = 1 << 4; + DeclFlags.LocalStatic = 1 << 5; + DeclFlags.GetAccessor = 1 << 6; + DeclFlags.SetAccessor = 1 << 7; + })(TypeScript.DeclFlags || (TypeScript.DeclFlags = {})); + var DeclFlags = TypeScript.DeclFlags; + (function (ModuleFlags) { + ModuleFlags._map = []; + ModuleFlags.None = 0; + ModuleFlags.Exported = 1; + ModuleFlags.Private = 1 << 1; + ModuleFlags.Public = 1 << 2; + ModuleFlags.Ambient = 1 << 3; + ModuleFlags.Static = 1 << 4; + ModuleFlags.LocalStatic = 1 << 5; + ModuleFlags.GetAccessor = 1 << 6; + ModuleFlags.SetAccessor = 1 << 7; + ModuleFlags.IsEnum = 1 << 8; + ModuleFlags.ShouldEmitModuleDecl = 1 << 9; + ModuleFlags.IsWholeFile = 1 << 10; + ModuleFlags.IsDynamic = 1 << 11; + ModuleFlags.MustCaptureThis = 1 << 12; + })(TypeScript.ModuleFlags || (TypeScript.ModuleFlags = {})); + var ModuleFlags = TypeScript.ModuleFlags; + (function (SymbolFlags) { + SymbolFlags._map = []; + SymbolFlags.None = 0; + SymbolFlags.Exported = 1; + SymbolFlags.Private = 1 << 1; + SymbolFlags.Public = 1 << 2; + SymbolFlags.Ambient = 1 << 3; + SymbolFlags.Static = 1 << 4; + SymbolFlags.LocalStatic = 1 << 5; + SymbolFlags.GetAccessor = 1 << 6; + SymbolFlags.SetAccessor = 1 << 7; + SymbolFlags.Property = 1 << 8; + SymbolFlags.Readonly = 1 << 9; + SymbolFlags.ModuleMember = 1 << 10; + SymbolFlags.InterfaceMember = 1 << 11; + SymbolFlags.ClassMember = 1 << 12; + SymbolFlags.BuiltIn = 1 << 13; + SymbolFlags.TypeSetDuringScopeAssignment = 1 << 14; + SymbolFlags.Constant = 1 << 15; + SymbolFlags.Optional = 1 << 16; + SymbolFlags.RecursivelyReferenced = 1 << 17; + SymbolFlags.Bound = 1 << 18; + SymbolFlags.CompilerGenerated = 1 << 19; + })(TypeScript.SymbolFlags || (TypeScript.SymbolFlags = {})); + var SymbolFlags = TypeScript.SymbolFlags; + (function (VarFlags) { + VarFlags._map = []; + VarFlags.None = 0; + VarFlags.Exported = 1; + VarFlags.Private = 1 << 1; + VarFlags.Public = 1 << 2; + VarFlags.Ambient = 1 << 3; + VarFlags.Static = 1 << 4; + VarFlags.LocalStatic = 1 << 5; + VarFlags.GetAccessor = 1 << 6; + VarFlags.SetAccessor = 1 << 7; + VarFlags.AutoInit = 1 << 8; + VarFlags.Property = 1 << 9; + VarFlags.Readonly = 1 << 10; + VarFlags.Class = 1 << 11; + VarFlags.ClassProperty = 1 << 12; + VarFlags.ClassBodyProperty = 1 << 13; + VarFlags.ClassConstructorProperty = 1 << 14; + VarFlags.ClassSuperMustBeFirstCallInConstructor = 1 << 15; + VarFlags.Constant = 1 << 16; + VarFlags.MustCaptureThis = 1 << 17; + })(TypeScript.VarFlags || (TypeScript.VarFlags = {})); + var VarFlags = TypeScript.VarFlags; + (function (FncFlags) { + FncFlags._map = []; + FncFlags.None = 0; + FncFlags.Exported = 1; + FncFlags.Private = 1 << 1; + FncFlags.Public = 1 << 2; + FncFlags.Ambient = 1 << 3; + FncFlags.Static = 1 << 4; + FncFlags.LocalStatic = 1 << 5; + FncFlags.GetAccessor = 1 << 6; + FncFlags.SetAccessor = 1 << 7; + FncFlags.Definition = 1 << 8; + FncFlags.Signature = 1 << 9; + FncFlags.Method = 1 << 10; + FncFlags.HasReturnExpression = 1 << 11; + FncFlags.CallMember = 1 << 12; + FncFlags.ConstructMember = 1 << 13; + FncFlags.HasSelfReference = 1 << 14; + FncFlags.IsFatArrowFunction = 1 << 15; + FncFlags.IndexerMember = 1 << 16; + FncFlags.IsFunctionExpression = 1 << 17; + FncFlags.ClassMethod = 1 << 18; + FncFlags.ClassPropertyMethodExported = 1 << 19; + FncFlags.HasSuperReferenceInFatArrowFunction = 1 << 20; + FncFlags.IsPropertyBound = 1 << 21; + })(TypeScript.FncFlags || (TypeScript.FncFlags = {})); + var FncFlags = TypeScript.FncFlags; + (function (SignatureFlags) { + SignatureFlags._map = []; + SignatureFlags.None = 0; + SignatureFlags.IsIndexer = 1; + SignatureFlags.IsStringIndexer = 1 << 1; + SignatureFlags.IsNumberIndexer = 1 << 2; + })(TypeScript.SignatureFlags || (TypeScript.SignatureFlags = {})); + var SignatureFlags = TypeScript.SignatureFlags; + function ToDeclFlags(fncOrVarOrSymbolOrModuleFlags) { + return fncOrVarOrSymbolOrModuleFlags; + } + TypeScript.ToDeclFlags = ToDeclFlags; + (function (TypeFlags) { + TypeFlags._map = []; + TypeFlags.None = 0; + TypeFlags.HasImplementation = 1; + TypeFlags.HasSelfReference = 1 << 1; + TypeFlags.MergeResult = 1 << 2; + TypeFlags.IsEnum = 1 << 3; + TypeFlags.BuildingName = 1 << 4; + TypeFlags.HasBaseType = 1 << 5; + TypeFlags.HasBaseTypeOfObject = 1 << 6; + TypeFlags.IsClass = 1 << 7; + })(TypeScript.TypeFlags || (TypeScript.TypeFlags = {})); + var TypeFlags = TypeScript.TypeFlags; + (function (TypeRelationshipFlags) { + TypeRelationshipFlags._map = []; + TypeRelationshipFlags.SuccessfulComparison = 0; + TypeRelationshipFlags.SourceIsNullTargetIsVoidOrUndefined = 1; + TypeRelationshipFlags.RequiredPropertyIsMissing = 1 << 1; + TypeRelationshipFlags.IncompatibleSignatures = 1 << 2; + TypeRelationshipFlags.SourceSignatureHasTooManyParameters = 3; + TypeRelationshipFlags.IncompatibleReturnTypes = 1 << 4; + TypeRelationshipFlags.IncompatiblePropertyTypes = 1 << 5; + TypeRelationshipFlags.IncompatibleParameterTypes = 1 << 6; + })(TypeScript.TypeRelationshipFlags || (TypeScript.TypeRelationshipFlags = {})); + var TypeRelationshipFlags = TypeScript.TypeRelationshipFlags; + (function (CodeGenTarget) { + CodeGenTarget._map = []; + CodeGenTarget.ES3 = 0; + CodeGenTarget.ES5 = 1; + })(TypeScript.CodeGenTarget || (TypeScript.CodeGenTarget = {})); + var CodeGenTarget = TypeScript.CodeGenTarget; + (function (ModuleGenTarget) { + ModuleGenTarget._map = []; + ModuleGenTarget.Synchronous = 0; + ModuleGenTarget.Asynchronous = 1; + ModuleGenTarget.Local = 1 << 1; + })(TypeScript.ModuleGenTarget || (TypeScript.ModuleGenTarget = {})); + var ModuleGenTarget = TypeScript.ModuleGenTarget; + TypeScript.codeGenTarget = CodeGenTarget.ES3; + TypeScript.moduleGenTarget = ModuleGenTarget.Synchronous; + TypeScript.optimizeModuleCodeGen = true; + function flagsToString(e, flags) { + var builder = ""; + for(var i = 1; i < (1 << 31); i = i << 1) { + if((flags & i) != 0) { + for(var k in e) { + if(e[k] == i) { + if(builder.length > 0) { + builder += "|"; + } + builder += k; + break; + } + } + } + } + return builder; + } + TypeScript.flagsToString = flagsToString; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (NodeType) { + NodeType._map = []; + NodeType._map[0] = "None"; + NodeType.None = 0; + NodeType._map[1] = "Empty"; + NodeType.Empty = 1; + NodeType._map[2] = "EmptyExpr"; + NodeType.EmptyExpr = 2; + NodeType._map[3] = "True"; + NodeType.True = 3; + NodeType._map[4] = "False"; + NodeType.False = 4; + NodeType._map[5] = "This"; + NodeType.This = 5; + NodeType._map[6] = "Super"; + NodeType.Super = 6; + NodeType._map[7] = "QString"; + NodeType.QString = 7; + NodeType._map[8] = "Regex"; + NodeType.Regex = 8; + NodeType._map[9] = "Null"; + NodeType.Null = 9; + NodeType._map[10] = "ArrayLit"; + NodeType.ArrayLit = 10; + NodeType._map[11] = "ObjectLit"; + NodeType.ObjectLit = 11; + NodeType._map[12] = "Void"; + NodeType.Void = 12; + NodeType._map[13] = "Comma"; + NodeType.Comma = 13; + NodeType._map[14] = "Pos"; + NodeType.Pos = 14; + NodeType._map[15] = "Neg"; + NodeType.Neg = 15; + NodeType._map[16] = "Delete"; + NodeType.Delete = 16; + NodeType._map[17] = "Await"; + NodeType.Await = 17; + NodeType._map[18] = "In"; + NodeType.In = 18; + NodeType._map[19] = "Dot"; + NodeType.Dot = 19; + NodeType._map[20] = "From"; + NodeType.From = 20; + NodeType._map[21] = "Is"; + NodeType.Is = 21; + NodeType._map[22] = "InstOf"; + NodeType.InstOf = 22; + NodeType._map[23] = "Typeof"; + NodeType.Typeof = 23; + NodeType._map[24] = "NumberLit"; + NodeType.NumberLit = 24; + NodeType._map[25] = "Name"; + NodeType.Name = 25; + NodeType._map[26] = "TypeRef"; + NodeType.TypeRef = 26; + NodeType._map[27] = "Index"; + NodeType.Index = 27; + NodeType._map[28] = "Call"; + NodeType.Call = 28; + NodeType._map[29] = "New"; + NodeType.New = 29; + NodeType._map[30] = "Asg"; + NodeType.Asg = 30; + NodeType._map[31] = "AsgAdd"; + NodeType.AsgAdd = 31; + NodeType._map[32] = "AsgSub"; + NodeType.AsgSub = 32; + NodeType._map[33] = "AsgDiv"; + NodeType.AsgDiv = 33; + NodeType._map[34] = "AsgMul"; + NodeType.AsgMul = 34; + NodeType._map[35] = "AsgMod"; + NodeType.AsgMod = 35; + NodeType._map[36] = "AsgAnd"; + NodeType.AsgAnd = 36; + NodeType._map[37] = "AsgXor"; + NodeType.AsgXor = 37; + NodeType._map[38] = "AsgOr"; + NodeType.AsgOr = 38; + NodeType._map[39] = "AsgLsh"; + NodeType.AsgLsh = 39; + NodeType._map[40] = "AsgRsh"; + NodeType.AsgRsh = 40; + NodeType._map[41] = "AsgRs2"; + NodeType.AsgRs2 = 41; + NodeType._map[42] = "ConditionalExpression"; + NodeType.ConditionalExpression = 42; + NodeType._map[43] = "LogOr"; + NodeType.LogOr = 43; + NodeType._map[44] = "LogAnd"; + NodeType.LogAnd = 44; + NodeType._map[45] = "Or"; + NodeType.Or = 45; + NodeType._map[46] = "Xor"; + NodeType.Xor = 46; + NodeType._map[47] = "And"; + NodeType.And = 47; + NodeType._map[48] = "Eq"; + NodeType.Eq = 48; + NodeType._map[49] = "Ne"; + NodeType.Ne = 49; + NodeType._map[50] = "Eqv"; + NodeType.Eqv = 50; + NodeType._map[51] = "NEqv"; + NodeType.NEqv = 51; + NodeType._map[52] = "Lt"; + NodeType.Lt = 52; + NodeType._map[53] = "Le"; + NodeType.Le = 53; + NodeType._map[54] = "Gt"; + NodeType.Gt = 54; + NodeType._map[55] = "Ge"; + NodeType.Ge = 55; + NodeType._map[56] = "Add"; + NodeType.Add = 56; + NodeType._map[57] = "Sub"; + NodeType.Sub = 57; + NodeType._map[58] = "Mul"; + NodeType.Mul = 58; + NodeType._map[59] = "Div"; + NodeType.Div = 59; + NodeType._map[60] = "Mod"; + NodeType.Mod = 60; + NodeType._map[61] = "Lsh"; + NodeType.Lsh = 61; + NodeType._map[62] = "Rsh"; + NodeType.Rsh = 62; + NodeType._map[63] = "Rs2"; + NodeType.Rs2 = 63; + NodeType._map[64] = "Not"; + NodeType.Not = 64; + NodeType._map[65] = "LogNot"; + NodeType.LogNot = 65; + NodeType._map[66] = "IncPre"; + NodeType.IncPre = 66; + NodeType._map[67] = "DecPre"; + NodeType.DecPre = 67; + NodeType._map[68] = "IncPost"; + NodeType.IncPost = 68; + NodeType._map[69] = "DecPost"; + NodeType.DecPost = 69; + NodeType._map[70] = "TypeAssertion"; + NodeType.TypeAssertion = 70; + NodeType._map[71] = "FuncDecl"; + NodeType.FuncDecl = 71; + NodeType._map[72] = "Member"; + NodeType.Member = 72; + NodeType._map[73] = "VarDecl"; + NodeType.VarDecl = 73; + NodeType._map[74] = "ArgDecl"; + NodeType.ArgDecl = 74; + NodeType._map[75] = "Return"; + NodeType.Return = 75; + NodeType._map[76] = "Break"; + NodeType.Break = 76; + NodeType._map[77] = "Continue"; + NodeType.Continue = 77; + NodeType._map[78] = "Throw"; + NodeType.Throw = 78; + NodeType._map[79] = "For"; + NodeType.For = 79; + NodeType._map[80] = "ForIn"; + NodeType.ForIn = 80; + NodeType._map[81] = "If"; + NodeType.If = 81; + NodeType._map[82] = "While"; + NodeType.While = 82; + NodeType._map[83] = "DoWhile"; + NodeType.DoWhile = 83; + NodeType._map[84] = "Block"; + NodeType.Block = 84; + NodeType._map[85] = "Case"; + NodeType.Case = 85; + NodeType._map[86] = "Switch"; + NodeType.Switch = 86; + NodeType._map[87] = "Try"; + NodeType.Try = 87; + NodeType._map[88] = "TryCatch"; + NodeType.TryCatch = 88; + NodeType._map[89] = "TryFinally"; + NodeType.TryFinally = 89; + NodeType._map[90] = "Finally"; + NodeType.Finally = 90; + NodeType._map[91] = "Catch"; + NodeType.Catch = 91; + NodeType._map[92] = "List"; + NodeType.List = 92; + NodeType._map[93] = "Script"; + NodeType.Script = 93; + NodeType._map[94] = "ClassDeclaration"; + NodeType.ClassDeclaration = 94; + NodeType._map[95] = "InterfaceDeclaration"; + NodeType.InterfaceDeclaration = 95; + NodeType._map[96] = "ModuleDeclaration"; + NodeType.ModuleDeclaration = 96; + NodeType._map[97] = "ImportDeclaration"; + NodeType.ImportDeclaration = 97; + NodeType._map[98] = "With"; + NodeType.With = 98; + NodeType._map[99] = "Label"; + NodeType.Label = 99; + NodeType._map[100] = "LabeledStatement"; + NodeType.LabeledStatement = 100; + NodeType._map[101] = "EBStart"; + NodeType.EBStart = 101; + NodeType._map[102] = "GotoEB"; + NodeType.GotoEB = 102; + NodeType._map[103] = "EndCode"; + NodeType.EndCode = 103; + NodeType._map[104] = "Error"; + NodeType.Error = 104; + NodeType._map[105] = "Comment"; + NodeType.Comment = 105; + NodeType._map[106] = "Debugger"; + NodeType.Debugger = 106; + NodeType.GeneralNode = NodeType.FuncDecl; + NodeType.LastAsg = NodeType.AsgRs2; + })(TypeScript.NodeType || (TypeScript.NodeType = {})); + var NodeType = TypeScript.NodeType; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var BlockIntrinsics = (function () { + function BlockIntrinsics() { + this.prototype = undefined; + this.toString = undefined; + this.toLocaleString = undefined; + this.valueOf = undefined; + this.hasOwnProperty = undefined; + this.propertyIsEnumerable = undefined; + this.isPrototypeOf = undefined; + this["constructor"] = undefined; + } + return BlockIntrinsics; + })(); + TypeScript.BlockIntrinsics = BlockIntrinsics; + var StringHashTable = (function () { + function StringHashTable() { + this.itemCount = 0; + this.table = (new BlockIntrinsics()); + } + StringHashTable.prototype.getAllKeys = function () { + var result = []; + for(var k in this.table) { + if(this.table[k] != undefined) { + result[result.length] = k; + } + } + return result; + }; + StringHashTable.prototype.add = function (key, data) { + if(this.table[key] != undefined) { + return false; + } + this.table[key] = data; + this.itemCount++; + return true; + }; + StringHashTable.prototype.addOrUpdate = function (key, data) { + if(this.table[key] != undefined) { + this.table[key] = data; + return false; + } + this.table[key] = data; + this.itemCount++; + return true; + }; + StringHashTable.prototype.map = function (fn, context) { + for(var k in this.table) { + var data = this.table[k]; + if(data != undefined) { + fn(k, this.table[k], context); + } + } + }; + StringHashTable.prototype.every = function (fn, context) { + for(var k in this.table) { + var data = this.table[k]; + if(data != undefined) { + if(!fn(k, this.table[k], context)) { + return false; + } + } + } + return true; + }; + StringHashTable.prototype.some = function (fn, context) { + for(var k in this.table) { + var data = this.table[k]; + if(data != undefined) { + if(fn(k, this.table[k], context)) { + return true; + } + } + } + return false; + }; + StringHashTable.prototype.count = function () { + return this.itemCount; + }; + StringHashTable.prototype.lookup = function (key) { + var data = this.table[key]; + if(data != undefined) { + return data; + } else { + return (null); + } + }; + return StringHashTable; + })(); + TypeScript.StringHashTable = StringHashTable; + var DualStringHashTable = (function () { + function DualStringHashTable(primaryTable, secondaryTable) { + this.primaryTable = primaryTable; + this.secondaryTable = secondaryTable; + this.insertPrimary = true; + } + DualStringHashTable.prototype.getAllKeys = function () { + return this.primaryTable.getAllKeys().concat(this.secondaryTable.getAllKeys()); + }; + DualStringHashTable.prototype.add = function (key, data) { + if(this.insertPrimary) { + return this.primaryTable.add(key, data); + } else { + return this.secondaryTable.add(key, data); + } + }; + DualStringHashTable.prototype.addOrUpdate = function (key, data) { + if(this.insertPrimary) { + return this.primaryTable.addOrUpdate(key, data); + } else { + return this.secondaryTable.addOrUpdate(key, data); + } + }; + DualStringHashTable.prototype.map = function (fn, context) { + this.primaryTable.map(fn, context); + this.secondaryTable.map(fn, context); + }; + DualStringHashTable.prototype.every = function (fn, context) { + return this.primaryTable.every(fn, context) && this.secondaryTable.every(fn, context); + }; + DualStringHashTable.prototype.some = function (fn, context) { + return this.primaryTable.some(fn, context) || this.secondaryTable.some(fn, context); + }; + DualStringHashTable.prototype.count = function () { + return this.primaryTable.count() + this.secondaryTable.count(); + }; + DualStringHashTable.prototype.lookup = function (key) { + var data = this.primaryTable.lookup(key); + if(data != undefined) { + return data; + } else { + return this.secondaryTable.lookup(key); + } + }; + return DualStringHashTable; + })(); + TypeScript.DualStringHashTable = DualStringHashTable; + function numberHashFn(key) { + var c2 = 668265261; + key = (key ^ 61) ^ (key >>> 16); + key = key + (key << 3); + key = key ^ (key >>> 4); + key = key * c2; + key = key ^ (key >>> 15); + return key; + } + TypeScript.numberHashFn = numberHashFn; + function combineHashes(key1, key2) { + return key2 ^ ((key1 >> 5) + key1); + } + TypeScript.combineHashes = combineHashes; + var HashEntry = (function () { + function HashEntry(key, data) { + this.key = key; + this.data = data; + } + return HashEntry; + })(); + TypeScript.HashEntry = HashEntry; + var HashTable = (function () { + function HashTable(size, hashFn, equalsFn) { + this.size = size; + this.hashFn = hashFn; + this.equalsFn = equalsFn; + this.itemCount = 0; + this.table = new Array(); + for(var i = 0; i < this.size; i++) { + this.table[i] = null; + } + } + HashTable.prototype.add = function (key, data) { + var current; + var entry = new HashEntry(key, data); + var val = this.hashFn(key); + val = val % this.size; + for(current = this.table[val]; current != null; current = current.next) { + if(this.equalsFn(key, current.key)) { + return false; + } + } + entry.next = this.table[val]; + this.table[val] = entry; + this.itemCount++; + return true; + }; + HashTable.prototype.remove = function (key) { + var current; + var val = this.hashFn(key); + val = val % this.size; + var result = null; + var prevEntry = null; + for(current = this.table[val]; current != null; current = current.next) { + if(this.equalsFn(key, current.key)) { + result = current.data; + this.itemCount--; + if(prevEntry) { + prevEntry.next = current.next; + } else { + this.table[val] = current.next; + } + break; + } + prevEntry = current; + } + return result; + }; + HashTable.prototype.count = function () { + return this.itemCount; + }; + HashTable.prototype.lookup = function (key) { + var current; + var val = this.hashFn(key); + val = val % this.size; + for(current = this.table[val]; current != null; current = current.next) { + if(this.equalsFn(key, current.key)) { + return (current.data); + } + } + return (null); + }; + return HashTable; + })(); + TypeScript.HashTable = HashTable; + var SimpleHashTable = (function () { + function SimpleHashTable() { + this.keys = []; + this.values = []; + } + SimpleHashTable.prototype.lookup = function (key, findValue) { + var searchArray = this.keys; + if(findValue) { + searchArray = this.values; + } + for(var i = 0; i < searchArray.length; i++) { + if(searchArray[i] == key) { + return { + key: this.keys[i], + data: this.values[i] + }; + } + } + return null; + }; + SimpleHashTable.prototype.add = function (key, data) { + var lookupData = this.lookup(key); + if(lookupData) { + return false; + } + this.keys[this.keys.length] = key; + this.values[this.values.length] = data; + return true; + }; + return SimpleHashTable; + })(); + TypeScript.SimpleHashTable = SimpleHashTable; +})(TypeScript || (TypeScript = {})); +var __extends = this.__extends || function (d, b) { + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var TypeScript; +(function (TypeScript) { + var ASTSpan = (function () { + function ASTSpan() { + this.minChar = -1; + this.limChar = -1; + } + return ASTSpan; + })(); + TypeScript.ASTSpan = ASTSpan; + var AST = (function (_super) { + __extends(AST, _super); + function AST(nodeType) { + _super.call(this); + this.nodeType = nodeType; + this.type = null; + this.flags = TypeScript.ASTFlags.Writeable; + this.passCreated = TypeScript.CompilerDiagnostics.analysisPass; + this.preComments = null; + this.postComments = null; + this.docComments = null; + this.isParenthesized = false; + } + AST.prototype.isExpression = function () { + return false; + }; + AST.prototype.isStatementOrExpression = function () { + return false; + }; + AST.prototype.isCompoundStatement = function () { + return false; + }; + AST.prototype.isLeaf = function () { + return this.isStatementOrExpression() && (!this.isCompoundStatement()); + }; + AST.prototype.isDeclaration = function () { + return false; + }; + AST.prototype.typeCheck = function (typeFlow) { + switch(this.nodeType) { + case TypeScript.NodeType.Error: + case TypeScript.NodeType.EmptyExpr: { + this.type = typeFlow.anyType; + break; + + } + case TypeScript.NodeType.This: { + return typeFlow.typeCheckThis(this); + + } + case TypeScript.NodeType.Null: { + this.type = typeFlow.nullType; + break; + + } + case TypeScript.NodeType.False: + case TypeScript.NodeType.True: { + this.type = typeFlow.booleanType; + break; + + } + case TypeScript.NodeType.Super: { + return typeFlow.typeCheckSuper(this); + + } + case TypeScript.NodeType.EndCode: + case TypeScript.NodeType.Empty: + case TypeScript.NodeType.Void: { + this.type = typeFlow.voidType; + break; + + } + default: { + throw new Error("please implement in derived class"); + + } + } + return this; + }; + AST.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + switch(this.nodeType) { + case TypeScript.NodeType.This: { + emitter.recordSourceMappingStart(this); + if(emitter.thisFnc && (TypeScript.hasFlag(emitter.thisFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction))) { + emitter.writeToOutput("_this"); + } else { + emitter.writeToOutput("this"); + } + emitter.recordSourceMappingEnd(this); + break; + + } + case TypeScript.NodeType.Null: { + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("null"); + emitter.recordSourceMappingEnd(this); + break; + + } + case TypeScript.NodeType.False: { + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("false"); + emitter.recordSourceMappingEnd(this); + break; + + } + case TypeScript.NodeType.True: { + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("true"); + emitter.recordSourceMappingEnd(this); + break; + + } + case TypeScript.NodeType.Super: { + emitter.recordSourceMappingStart(this); + emitter.emitSuperReference(); + emitter.recordSourceMappingEnd(this); + break; + + } + case TypeScript.NodeType.EndCode: + case TypeScript.NodeType.Error: + case TypeScript.NodeType.EmptyExpr: { + break; + + } + case TypeScript.NodeType.Empty: { + emitter.recordSourceMappingStart(this); + emitter.recordSourceMappingEnd(this); + break; + + } + case TypeScript.NodeType.Void: { + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("void "); + emitter.recordSourceMappingEnd(this); + break; + + } + default: { + throw new Error("please implement in derived class"); + + } + } + emitter.emitParensAndCommentsInPlace(this, false); + }; + AST.prototype.print = function (context) { + context.startLine(); + var lineCol = { + line: -1, + col: -1 + }; + var limLineCol = { + line: -1, + col: -1 + }; + if(context.parser !== null) { + context.parser.getSourceLineCol(lineCol, this.minChar); + context.parser.getSourceLineCol(limLineCol, this.limChar); + context.write("(" + lineCol.line + "," + lineCol.col + ")--" + "(" + limLineCol.line + "," + limLineCol.col + "): "); + } + var lab = this.printLabel(); + if(TypeScript.hasFlag(this.flags, TypeScript.ASTFlags.Error)) { + lab += " (Error)"; + } + context.writeLine(lab); + }; + AST.prototype.printLabel = function () { + if(TypeScript.nodeTypeTable[this.nodeType] !== undefined) { + return TypeScript.nodeTypeTable[this.nodeType]; + } else { + return (TypeScript.NodeType)._map[this.nodeType]; + } + }; + AST.prototype.addToControlFlow = function (context) { + context.walker.options.goChildren = false; + context.addContent(this); + }; + AST.prototype.netFreeUses = function (container, freeUses) { + }; + AST.prototype.treeViewLabel = function () { + return (TypeScript.NodeType)._map[this.nodeType]; + }; + AST.getResolvedIdentifierName = function getResolvedIdentifierName(name) { + if(!name) { + return ""; + } + var resolved = ""; + var start = 0; + var i = 0; + while(i <= name.length - 6) { + if(name.charAt(i) == '\\' && name.charAt(i + 1) == 'u') { + var charCode = parseInt(name.substr(i + 2, 4), 16); + resolved += name.substr(start, i - start); + resolved += String.fromCharCode(charCode); + i += 6; + start = i; + continue; + } + i++; + } + resolved += name.substring(start); + return resolved; + } + AST.prototype.getDocComments = function () { + if(!this.isDeclaration() || !this.preComments || this.preComments.length == 0) { + return []; + } + if(!this.docComments) { + var preCommentsLength = this.preComments.length; + var docComments = []; + for(var i = preCommentsLength - 1; i >= 0; i--) { + if(this.preComments[i].isDocComment()) { + var prevDocComment = docComments.length > 0 ? docComments[docComments.length - 1] : null; + if(prevDocComment == null || (this.preComments[i].limLine == prevDocComment.minLine || this.preComments[i].limLine + 1 == prevDocComment.minLine)) { + docComments.push(this.preComments[i]); + continue; + } + } + break; + } + this.docComments = docComments.reverse(); + } + return this.docComments; + }; + return AST; + })(ASTSpan); + TypeScript.AST = AST; + var IncompleteAST = (function (_super) { + __extends(IncompleteAST, _super); + function IncompleteAST(min, lim) { + _super.call(this, TypeScript.NodeType.Error); + this.minChar = min; + this.limChar = lim; + } + return IncompleteAST; + })(AST); + TypeScript.IncompleteAST = IncompleteAST; + var ASTList = (function (_super) { + __extends(ASTList, _super); + function ASTList() { + _super.call(this, TypeScript.NodeType.List); + this.enclosingScope = null; + this.members = new Array(); + } + ASTList.prototype.addToControlFlow = function (context) { + var len = this.members.length; + for(var i = 0; i < len; i++) { + if(context.noContinuation) { + context.addUnreachable(this.members[i]); + break; + } else { + this.members[i] = context.walk(this.members[i], this); + } + } + context.walker.options.goChildren = false; + }; + ASTList.prototype.append = function (ast) { + this.members[this.members.length] = ast; + return this; + }; + ASTList.prototype.appendAll = function (ast) { + if(ast.nodeType == TypeScript.NodeType.List) { + var list = ast; + for(var i = 0, len = list.members.length; i < len; i++) { + this.append(list.members[i]); + } + } else { + this.append(ast); + } + return this; + }; + ASTList.prototype.emit = function (emitter, tokenId, startLine) { + emitter.recordSourceMappingStart(this); + emitter.emitJavascriptList(this, null, TypeScript.TokenID.Semicolon, startLine, false, false); + emitter.recordSourceMappingEnd(this); + }; + ASTList.prototype.typeCheck = function (typeFlow) { + var len = this.members.length; + typeFlow.nestingLevel++; + for(var i = 0; i < len; i++) { + if(this.members[i]) { + this.members[i] = this.members[i].typeCheck(typeFlow); + } + } + typeFlow.nestingLevel--; + return this; + }; + return ASTList; + })(AST); + TypeScript.ASTList = ASTList; + var Identifier = (function (_super) { + __extends(Identifier, _super); + function Identifier(actualText, hasEscapeSequence) { + _super.call(this, TypeScript.NodeType.Name); + this.actualText = actualText; + this.hasEscapeSequence = hasEscapeSequence; + this.sym = null; + this.cloId = -1; + this.setText(actualText, hasEscapeSequence); + } + Identifier.prototype.setText = function (actualText, hasEscapeSequence) { + this.actualText = actualText; + if(hasEscapeSequence) { + this.text = AST.getResolvedIdentifierName(actualText); + } else { + this.text = actualText; + } + }; + Identifier.prototype.isMissing = function () { + return false; + }; + Identifier.prototype.isLeaf = function () { + return true; + }; + Identifier.prototype.treeViewLabel = function () { + return "id: " + this.actualText; + }; + Identifier.prototype.printLabel = function () { + if(this.actualText) { + return "id: " + this.actualText; + } else { + return "name node"; + } + }; + Identifier.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckName(this); + }; + Identifier.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitJavascriptName(this, true); + }; + Identifier.fromToken = function fromToken(token) { + return new Identifier(token.getText(), (token).hasEscapeSequence); + } + return Identifier; + })(AST); + TypeScript.Identifier = Identifier; + var MissingIdentifier = (function (_super) { + __extends(MissingIdentifier, _super); + function MissingIdentifier() { + _super.call(this, "__missing"); + } + MissingIdentifier.prototype.isMissing = function () { + return true; + }; + MissingIdentifier.prototype.emit = function (emitter, tokenId, startLine) { + }; + return MissingIdentifier; + })(Identifier); + TypeScript.MissingIdentifier = MissingIdentifier; + var Label = (function (_super) { + __extends(Label, _super); + function Label(id) { + _super.call(this, TypeScript.NodeType.Label); + this.id = id; + } + Label.prototype.printLabel = function () { + return this.id.actualText + ":"; + }; + Label.prototype.typeCheck = function (typeFlow) { + this.type = typeFlow.voidType; + return this; + }; + Label.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.recordSourceMappingStart(this.id); + emitter.writeToOutput(this.id.actualText); + emitter.recordSourceMappingEnd(this.id); + emitter.writeLineToOutput(":"); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return Label; + })(AST); + TypeScript.Label = Label; + var Expression = (function (_super) { + __extends(Expression, _super); + function Expression(nodeType) { + _super.call(this, nodeType); + } + Expression.prototype.isExpression = function () { + return true; + }; + Expression.prototype.isStatementOrExpression = function () { + return true; + }; + return Expression; + })(AST); + TypeScript.Expression = Expression; + var UnaryExpression = (function (_super) { + __extends(UnaryExpression, _super); + function UnaryExpression(nodeType, operand) { + _super.call(this, nodeType); + this.operand = operand; + this.targetType = null; + this.castTerm = null; + } + UnaryExpression.prototype.addToControlFlow = function (context) { + _super.prototype.addToControlFlow.call(this, context); + if(this.nodeType == TypeScript.NodeType.Throw) { + context.returnStmt(); + } + }; + UnaryExpression.prototype.typeCheck = function (typeFlow) { + switch(this.nodeType) { + case TypeScript.NodeType.Not: { + return typeFlow.typeCheckBitNot(this); + + } + case TypeScript.NodeType.LogNot: { + return typeFlow.typeCheckLogNot(this); + + } + case TypeScript.NodeType.Pos: + case TypeScript.NodeType.Neg: { + return typeFlow.typeCheckUnaryNumberOperator(this); + + } + case TypeScript.NodeType.IncPost: + case TypeScript.NodeType.IncPre: + case TypeScript.NodeType.DecPost: + case TypeScript.NodeType.DecPre: { + return typeFlow.typeCheckIncOrDec(this); + + } + case TypeScript.NodeType.ArrayLit: { + typeFlow.typeCheckArrayLit(this); + return this; + + } + case TypeScript.NodeType.ObjectLit: { + typeFlow.typeCheckObjectLit(this); + return this; + + } + case TypeScript.NodeType.Throw: { + this.operand = typeFlow.typeCheck(this.operand); + this.type = typeFlow.voidType; + return this; + + } + case TypeScript.NodeType.Typeof: { + this.operand = typeFlow.typeCheck(this.operand); + this.type = typeFlow.stringType; + return this; + + } + case TypeScript.NodeType.Delete: { + this.operand = typeFlow.typeCheck(this.operand); + this.type = typeFlow.booleanType; + break; + + } + case TypeScript.NodeType.TypeAssertion: { + this.castTerm = typeFlow.typeCheck(this.castTerm); + var applyTargetType = !this.operand.isParenthesized; + var targetType = applyTargetType ? this.castTerm.type : null; + typeFlow.checker.typeCheckWithContextualType(targetType, typeFlow.checker.inProvisionalTypecheckMode(), true, this.operand); + typeFlow.castWithCoercion(this.operand, this.castTerm.type, false, true); + this.type = this.castTerm.type; + return this; + + } + case TypeScript.NodeType.Void: { + this.operand = typeFlow.typeCheck(this.operand); + this.type = typeFlow.checker.undefinedType; + break; + + } + default: { + throw new Error("please implement in derived class"); + + } + } + return this; + }; + UnaryExpression.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + switch(this.nodeType) { + case TypeScript.NodeType.IncPost: { + emitter.emitJavascript(this.operand, TypeScript.TokenID.PlusPlus, false); + emitter.writeToOutput("++"); + break; + + } + case TypeScript.NodeType.LogNot: { + emitter.writeToOutput("!"); + emitter.emitJavascript(this.operand, TypeScript.TokenID.Exclamation, false); + break; + + } + case TypeScript.NodeType.DecPost: { + emitter.emitJavascript(this.operand, TypeScript.TokenID.MinusMinus, false); + emitter.writeToOutput("--"); + break; + + } + case TypeScript.NodeType.ObjectLit: { + emitter.emitObjectLiteral(this.operand); + break; + + } + case TypeScript.NodeType.ArrayLit: { + emitter.emitArrayLiteral(this.operand); + break; + + } + case TypeScript.NodeType.Not: { + emitter.writeToOutput("~"); + emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); + break; + + } + case TypeScript.NodeType.Neg: { + emitter.writeToOutput("-"); + if(this.operand.nodeType == TypeScript.NodeType.Neg) { + this.operand.isParenthesized = true; + } + emitter.emitJavascript(this.operand, TypeScript.TokenID.Minus, false); + break; + + } + case TypeScript.NodeType.Pos: { + emitter.writeToOutput("+"); + if(this.operand.nodeType == TypeScript.NodeType.Pos) { + this.operand.isParenthesized = true; + } + emitter.emitJavascript(this.operand, TypeScript.TokenID.Plus, false); + break; + + } + case TypeScript.NodeType.IncPre: { + emitter.writeToOutput("++"); + emitter.emitJavascript(this.operand, TypeScript.TokenID.PlusPlus, false); + break; + + } + case TypeScript.NodeType.DecPre: { + emitter.writeToOutput("--"); + emitter.emitJavascript(this.operand, TypeScript.TokenID.MinusMinus, false); + break; + + } + case TypeScript.NodeType.Throw: { + emitter.writeToOutput("throw "); + emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); + emitter.writeToOutput(";"); + break; + + } + case TypeScript.NodeType.Typeof: { + emitter.writeToOutput("typeof "); + emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); + break; + + } + case TypeScript.NodeType.Delete: { + emitter.writeToOutput("delete "); + emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); + break; + + } + case TypeScript.NodeType.Void: { + emitter.writeToOutput("void "); + emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); + break; + + } + case TypeScript.NodeType.TypeAssertion: { + emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); + break; + + } + default: { + throw new Error("please implement in derived class"); + + } + } + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return UnaryExpression; + })(Expression); + TypeScript.UnaryExpression = UnaryExpression; + var CallExpression = (function (_super) { + __extends(CallExpression, _super); + function CallExpression(nodeType, target, arguments) { + _super.call(this, nodeType); + this.target = target; + this.arguments = arguments; + this.signature = null; + this.minChar = this.target.minChar; + } + CallExpression.prototype.typeCheck = function (typeFlow) { + if(this.nodeType == TypeScript.NodeType.New) { + return typeFlow.typeCheckNew(this); + } else { + return typeFlow.typeCheckCall(this); + } + }; + CallExpression.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + if(this.nodeType == TypeScript.NodeType.New) { + emitter.emitNew(this.target, this.arguments); + } else { + emitter.emitCall(this, this.target, this.arguments); + } + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return CallExpression; + })(Expression); + TypeScript.CallExpression = CallExpression; + var BinaryExpression = (function (_super) { + __extends(BinaryExpression, _super); + function BinaryExpression(nodeType, operand1, operand2) { + _super.call(this, nodeType); + this.operand1 = operand1; + this.operand2 = operand2; + } + BinaryExpression.prototype.typeCheck = function (typeFlow) { + switch(this.nodeType) { + case TypeScript.NodeType.Dot: { + return typeFlow.typeCheckDotOperator(this); + + } + case TypeScript.NodeType.Asg: { + return typeFlow.typeCheckAsgOperator(this); + + } + case TypeScript.NodeType.Add: + case TypeScript.NodeType.Sub: + case TypeScript.NodeType.Mul: + case TypeScript.NodeType.Div: + case TypeScript.NodeType.Mod: + case TypeScript.NodeType.Or: + case TypeScript.NodeType.And: { + return typeFlow.typeCheckArithmeticOperator(this, false); + + } + case TypeScript.NodeType.Xor: { + return typeFlow.typeCheckBitwiseOperator(this, false); + + } + case TypeScript.NodeType.Ne: + case TypeScript.NodeType.Eq: { + var text; + if(typeFlow.checker.styleSettings.eqeqeq) { + text = TypeScript.nodeTypeTable[this.nodeType]; + typeFlow.checker.errorReporter.styleError(this, "use of " + text); + } else { + if(typeFlow.checker.styleSettings.eqnull) { + text = TypeScript.nodeTypeTable[this.nodeType]; + if((this.operand2 !== null) && (this.operand2.nodeType == TypeScript.NodeType.Null)) { + typeFlow.checker.errorReporter.styleError(this, "use of " + text + " to compare with null"); + } + } + } + + } + case TypeScript.NodeType.Eqv: + case TypeScript.NodeType.NEqv: + case TypeScript.NodeType.Lt: + case TypeScript.NodeType.Le: + case TypeScript.NodeType.Ge: + case TypeScript.NodeType.Gt: { + return typeFlow.typeCheckBooleanOperator(this); + + } + case TypeScript.NodeType.Index: { + return typeFlow.typeCheckIndex(this); + + } + case TypeScript.NodeType.Member: { + this.type = typeFlow.voidType; + return this; + + } + case TypeScript.NodeType.LogOr: { + return typeFlow.typeCheckLogOr(this); + + } + case TypeScript.NodeType.LogAnd: { + return typeFlow.typeCheckLogAnd(this); + + } + case TypeScript.NodeType.AsgAdd: + case TypeScript.NodeType.AsgSub: + case TypeScript.NodeType.AsgMul: + case TypeScript.NodeType.AsgDiv: + case TypeScript.NodeType.AsgMod: + case TypeScript.NodeType.AsgOr: + case TypeScript.NodeType.AsgAnd: { + return typeFlow.typeCheckArithmeticOperator(this, true); + + } + case TypeScript.NodeType.AsgXor: { + return typeFlow.typeCheckBitwiseOperator(this, true); + + } + case TypeScript.NodeType.Lsh: + case TypeScript.NodeType.Rsh: + case TypeScript.NodeType.Rs2: { + return typeFlow.typeCheckShift(this, false); + + } + case TypeScript.NodeType.AsgLsh: + case TypeScript.NodeType.AsgRsh: + case TypeScript.NodeType.AsgRs2: { + return typeFlow.typeCheckShift(this, true); + + } + case TypeScript.NodeType.Comma: { + return typeFlow.typeCheckCommaOperator(this); + + } + case TypeScript.NodeType.InstOf: { + return typeFlow.typeCheckInstOf(this); + + } + case TypeScript.NodeType.In: { + return typeFlow.typeCheckInOperator(this); + + } + case TypeScript.NodeType.From: { + typeFlow.checker.errorReporter.simpleError(this, "Illegal use of 'from' keyword in binary expression"); + break; + + } + default: { + throw new Error("please implement in derived class"); + + } + } + return this; + }; + BinaryExpression.prototype.emit = function (emitter, tokenId, startLine) { + var binTokenId = TypeScript.nodeTypeToTokTable[this.nodeType]; + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + if(binTokenId != undefined) { + emitter.emitJavascript(this.operand1, binTokenId, false); + if(TypeScript.tokenTable[binTokenId].text == "instanceof") { + emitter.writeToOutput(" instanceof "); + } else { + if(TypeScript.tokenTable[binTokenId].text == "in") { + emitter.writeToOutput(" in "); + } else { + emitter.writeToOutputTrimmable(" " + TypeScript.tokenTable[binTokenId].text + " "); + } + } + emitter.emitJavascript(this.operand2, binTokenId, false); + } else { + switch(this.nodeType) { + case TypeScript.NodeType.Dot: { + if(!emitter.tryEmitConstant(this)) { + emitter.emitJavascript(this.operand1, TypeScript.TokenID.Dot, false); + emitter.writeToOutput("."); + emitter.emitJavascriptName(this.operand2, false); + } + break; + + } + case TypeScript.NodeType.Index: { + emitter.emitIndex(this.operand1, this.operand2); + break; + + } + case TypeScript.NodeType.Member: { + if(this.operand2.nodeType == TypeScript.NodeType.FuncDecl && (this.operand2).isAccessor()) { + var funcDecl = this.operand2; + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { + emitter.writeToOutput("get "); + } else { + emitter.writeToOutput("set "); + } + emitter.emitJavascript(this.operand1, TypeScript.TokenID.Colon, false); + } else { + emitter.emitJavascript(this.operand1, TypeScript.TokenID.Colon, false); + emitter.writeToOutputTrimmable(": "); + } + emitter.emitJavascript(this.operand2, TypeScript.TokenID.Comma, false); + break; + + } + case TypeScript.NodeType.Comma: { + emitter.emitJavascript(this.operand1, TypeScript.TokenID.Comma, false); + if(emitter.emitState.inObjectLiteral) { + emitter.writeLineToOutput(", "); + } else { + emitter.writeToOutput(","); + } + emitter.emitJavascript(this.operand2, TypeScript.TokenID.Comma, false); + break; + + } + case TypeScript.NodeType.Is: { + throw new Error("should be de-sugared during type check"); + + } + default: { + throw new Error("please implement in derived class"); + + } + } + } + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return BinaryExpression; + })(Expression); + TypeScript.BinaryExpression = BinaryExpression; + var ConditionalExpression = (function (_super) { + __extends(ConditionalExpression, _super); + function ConditionalExpression(operand1, operand2, operand3) { + _super.call(this, TypeScript.NodeType.ConditionalExpression); + this.operand1 = operand1; + this.operand2 = operand2; + this.operand3 = operand3; + } + ConditionalExpression.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckQMark(this); + }; + ConditionalExpression.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.emitJavascript(this.operand1, TypeScript.TokenID.Question, false); + emitter.writeToOutput(" ? "); + emitter.emitJavascript(this.operand2, TypeScript.TokenID.Question, false); + emitter.writeToOutput(" : "); + emitter.emitJavascript(this.operand3, TypeScript.TokenID.Question, false); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return ConditionalExpression; + })(Expression); + TypeScript.ConditionalExpression = ConditionalExpression; + var NumberLiteral = (function (_super) { + __extends(NumberLiteral, _super); + function NumberLiteral(value, hasEmptyFraction) { + _super.call(this, TypeScript.NodeType.NumberLit); + this.value = value; + this.hasEmptyFraction = hasEmptyFraction; + this.isNegativeZero = false; + } + NumberLiteral.prototype.typeCheck = function (typeFlow) { + this.type = typeFlow.doubleType; + return this; + }; + NumberLiteral.prototype.treeViewLabel = function () { + return "num: " + this.printLabel(); + }; + NumberLiteral.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + if(this.isNegativeZero) { + emitter.writeToOutput("-"); + } + emitter.writeToOutput(this.value.toString()); + if(this.hasEmptyFraction) { + emitter.writeToOutput(".0"); + } + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + NumberLiteral.prototype.printLabel = function () { + if(Math.floor(this.value) != this.value) { + return this.value.toFixed(2).toString(); + } else { + if(this.hasEmptyFraction) { + return this.value.toString() + ".0"; + } else { + return this.value.toString(); + } + } + }; + return NumberLiteral; + })(Expression); + TypeScript.NumberLiteral = NumberLiteral; + var RegexLiteral = (function (_super) { + __extends(RegexLiteral, _super); + function RegexLiteral(regex) { + _super.call(this, TypeScript.NodeType.Regex); + this.regex = regex; + } + RegexLiteral.prototype.typeCheck = function (typeFlow) { + this.type = typeFlow.regexType; + return this; + }; + RegexLiteral.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput(this.regex.toString()); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return RegexLiteral; + })(Expression); + TypeScript.RegexLiteral = RegexLiteral; + var StringLiteral = (function (_super) { + __extends(StringLiteral, _super); + function StringLiteral(text) { + _super.call(this, TypeScript.NodeType.QString); + this.text = text; + } + StringLiteral.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.emitStringLiteral(this.text); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + StringLiteral.prototype.typeCheck = function (typeFlow) { + this.type = typeFlow.stringType; + return this; + }; + StringLiteral.prototype.treeViewLabel = function () { + return "st: " + this.text; + }; + StringLiteral.prototype.printLabel = function () { + return this.text; + }; + return StringLiteral; + })(Expression); + TypeScript.StringLiteral = StringLiteral; + var ModuleElement = (function (_super) { + __extends(ModuleElement, _super); + function ModuleElement(nodeType) { + _super.call(this, nodeType); + } + return ModuleElement; + })(AST); + TypeScript.ModuleElement = ModuleElement; + var ImportDeclaration = (function (_super) { + __extends(ImportDeclaration, _super); + function ImportDeclaration(id, alias) { + _super.call(this, TypeScript.NodeType.ImportDeclaration); + this.id = id; + this.alias = alias; + this.varFlags = TypeScript.VarFlags.None; + this.isDynamicImport = false; + } + ImportDeclaration.prototype.isStatementOrExpression = function () { + return true; + }; + ImportDeclaration.prototype.isDeclaration = function () { + return true; + }; + ImportDeclaration.prototype.emit = function (emitter, tokenId, startLine) { + var mod = this.alias.type; + if(!this.isDynamicImport || (this.id.sym && !(this.id.sym).onlyReferencedAsTypeRef)) { + var prevModAliasId = emitter.modAliasId; + var prevFirstModAlias = emitter.firstModAlias; + emitter.recordSourceMappingStart(this); + emitter.emitParensAndCommentsInPlace(this, true); + emitter.writeToOutput("var " + this.id.actualText + " = "); + emitter.modAliasId = this.id.actualText; + emitter.firstModAlias = this.firstAliasedModToString(); + emitter.emitJavascript(this.alias, TypeScript.TokenID.Tilde, false); + if(!this.isDynamicImport) { + emitter.writeToOutput(";"); + } + emitter.emitParensAndCommentsInPlace(this, false); + emitter.recordSourceMappingEnd(this); + emitter.modAliasId = prevModAliasId; + emitter.firstModAlias = prevFirstModAlias; + } + }; + ImportDeclaration.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckImportDecl(this); + }; + ImportDeclaration.prototype.getAliasName = function (aliasAST) { + if (typeof aliasAST === "undefined") { aliasAST = this.alias; } + if(aliasAST.nodeType == TypeScript.NodeType.Name) { + return (aliasAST).actualText; + } else { + var dotExpr = aliasAST; + return this.getAliasName(dotExpr.operand1) + "." + this.getAliasName(dotExpr.operand2); + } + }; + ImportDeclaration.prototype.firstAliasedModToString = function () { + if(this.alias.nodeType == TypeScript.NodeType.Name) { + return (this.alias).actualText; + } else { + var dotExpr = this.alias; + var firstMod = dotExpr.operand1; + return firstMod.actualText; + } + }; + return ImportDeclaration; + })(ModuleElement); + TypeScript.ImportDeclaration = ImportDeclaration; + var BoundDecl = (function (_super) { + __extends(BoundDecl, _super); + function BoundDecl(id, nodeType, nestingLevel) { + _super.call(this, nodeType); + this.id = id; + this.nestingLevel = nestingLevel; + this.init = null; + this.typeExpr = null; + this.varFlags = TypeScript.VarFlags.None; + this.sym = null; + } + BoundDecl.prototype.isDeclaration = function () { + return true; + }; + BoundDecl.prototype.isStatementOrExpression = function () { + return true; + }; + BoundDecl.prototype.isPrivate = function () { + return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Private); + }; + BoundDecl.prototype.isPublic = function () { + return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Public); + }; + BoundDecl.prototype.isProperty = function () { + return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Property); + }; + BoundDecl.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckBoundDecl(this); + }; + BoundDecl.prototype.printLabel = function () { + return this.treeViewLabel(); + }; + return BoundDecl; + })(AST); + TypeScript.BoundDecl = BoundDecl; + var VarDecl = (function (_super) { + __extends(VarDecl, _super); + function VarDecl(id, nest) { + _super.call(this, id, TypeScript.NodeType.VarDecl, nest); + } + VarDecl.prototype.isAmbient = function () { + return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Ambient); + }; + VarDecl.prototype.isExported = function () { + return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Exported); + }; + VarDecl.prototype.isStatic = function () { + return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Static); + }; + VarDecl.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitJavascriptVarDecl(this, tokenId); + }; + VarDecl.prototype.treeViewLabel = function () { + return "var " + this.id.actualText; + }; + return VarDecl; + })(BoundDecl); + TypeScript.VarDecl = VarDecl; + var ArgDecl = (function (_super) { + __extends(ArgDecl, _super); + function ArgDecl(id) { + _super.call(this, id, TypeScript.NodeType.ArgDecl, 0); + this.isOptional = false; + this.parameterPropertySym = null; + } + ArgDecl.prototype.isOptionalArg = function () { + return this.isOptional || this.init; + }; + ArgDecl.prototype.treeViewLabel = function () { + return "arg: " + this.id.actualText; + }; + ArgDecl.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput(this.id.actualText); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return ArgDecl; + })(BoundDecl); + TypeScript.ArgDecl = ArgDecl; + var internalId = 0; + var FuncDecl = (function (_super) { + __extends(FuncDecl, _super); + function FuncDecl(name, bod, isConstructor, arguments, vars, scopes, statics, nodeType) { + _super.call(this, nodeType); + this.name = name; + this.bod = bod; + this.isConstructor = isConstructor; + this.arguments = arguments; + this.vars = vars; + this.scopes = scopes; + this.statics = statics; + this.hint = null; + this.fncFlags = TypeScript.FncFlags.None; + this.returnTypeAnnotation = null; + this.variableArgList = false; + this.jumpRefs = null; + this.internalNameCache = null; + this.tmp1Declared = false; + this.enclosingFnc = null; + this.freeVariables = []; + this.unitIndex = -1; + this.classDecl = null; + this.boundToProperty = null; + this.isOverload = false; + this.innerStaticFuncs = []; + this.isTargetTypedAsMethod = false; + this.isInlineCallLiteral = false; + this.accessorSymbol = null; + this.leftCurlyCount = 0; + this.rightCurlyCount = 0; + this.returnStatementsWithExpressions = []; + this.scopeType = null; + this.endingToken = null; + } + FuncDecl.prototype.isDeclaration = function () { + return true; + }; + FuncDecl.prototype.internalName = function () { + if(this.internalNameCache == null) { + var extName = this.getNameText(); + if(extName) { + this.internalNameCache = "_internal_" + extName; + } else { + this.internalNameCache = "_internal_" + internalId++; + } + } + return this.internalNameCache; + }; + FuncDecl.prototype.hasSelfReference = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.HasSelfReference); + }; + FuncDecl.prototype.setHasSelfReference = function () { + this.fncFlags |= TypeScript.FncFlags.HasSelfReference; + }; + FuncDecl.prototype.hasSuperReferenceInFatArrowFunction = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.HasSuperReferenceInFatArrowFunction); + }; + FuncDecl.prototype.setHasSuperReferenceInFatArrowFunction = function () { + this.fncFlags |= TypeScript.FncFlags.HasSuperReferenceInFatArrowFunction; + }; + FuncDecl.prototype.addCloRef = function (id, sym) { + if(this.envids == null) { + this.envids = new Array(); + } + this.envids[this.envids.length] = id; + var outerFnc = this.enclosingFnc; + if(sym) { + while(outerFnc && (outerFnc.type.symbol != sym.container)) { + outerFnc.addJumpRef(sym); + outerFnc = outerFnc.enclosingFnc; + } + } + return this.envids.length - 1; + }; + FuncDecl.prototype.addJumpRef = function (sym) { + if(this.jumpRefs == null) { + this.jumpRefs = new Array(); + } + var id = new Identifier(sym.name); + this.jumpRefs[this.jumpRefs.length] = id; + id.sym = sym; + id.cloId = this.addCloRef(id, null); + }; + FuncDecl.prototype.buildControlFlow = function () { + var entry = new TypeScript.BasicBlock(); + var exit = new TypeScript.BasicBlock(); + var context = new TypeScript.ControlFlowContext(entry, exit); + var controlFlowPrefix = function (ast, parent, walker) { + ast.addToControlFlow(walker.state); + return ast; + }; + var walker = TypeScript.getAstWalkerFactory().getWalker(controlFlowPrefix, null, null, context); + context.walker = walker; + walker.walk(this.bod, this); + return context; + }; + FuncDecl.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckFunction(this); + }; + FuncDecl.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitJavascriptFunction(this); + }; + FuncDecl.prototype.getNameText = function () { + if(this.name) { + return this.name.actualText; + } else { + return this.hint; + } + }; + FuncDecl.prototype.isMethod = function () { + return (this.fncFlags & TypeScript.FncFlags.Method) != TypeScript.FncFlags.None; + }; + FuncDecl.prototype.isCallMember = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.CallMember); + }; + FuncDecl.prototype.isConstructMember = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.ConstructMember); + }; + FuncDecl.prototype.isIndexerMember = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.IndexerMember); + }; + FuncDecl.prototype.isSpecialFn = function () { + return this.isCallMember() || this.isIndexerMember() || this.isConstructMember(); + }; + FuncDecl.prototype.isAnonymousFn = function () { + return this.name === null; + }; + FuncDecl.prototype.isAccessor = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.GetAccessor) || TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.SetAccessor); + }; + FuncDecl.prototype.isGetAccessor = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.GetAccessor); + }; + FuncDecl.prototype.isSetAccessor = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.SetAccessor); + }; + FuncDecl.prototype.isAmbient = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Ambient); + }; + FuncDecl.prototype.isExported = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Exported); + }; + FuncDecl.prototype.isPrivate = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Private); + }; + FuncDecl.prototype.isPublic = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Public); + }; + FuncDecl.prototype.isStatic = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Static); + }; + FuncDecl.prototype.treeViewLabel = function () { + if(this.name == null) { + return "funcExpr"; + } else { + return "func: " + this.name.actualText; + } + }; + FuncDecl.prototype.ClearFlags = function () { + this.fncFlags = TypeScript.FncFlags.None; + }; + FuncDecl.prototype.isSignature = function () { + return (this.fncFlags & TypeScript.FncFlags.Signature) != TypeScript.FncFlags.None; + }; + return FuncDecl; + })(AST); + TypeScript.FuncDecl = FuncDecl; + var LocationInfo = (function () { + function LocationInfo(filename, lineMap, unitIndex) { + this.filename = filename; + this.lineMap = lineMap; + this.unitIndex = unitIndex; + } + return LocationInfo; + })(); + TypeScript.LocationInfo = LocationInfo; + TypeScript.unknownLocationInfo = new LocationInfo("unknown", null, -1); + var Script = (function (_super) { + __extends(Script, _super); + function Script(vars, scopes) { + _super.call(this, new Identifier("script"), null, false, null, vars, scopes, null, TypeScript.NodeType.Script); + this.locationInfo = null; + this.referencedFiles = []; + this.requiresGlobal = false; + this.requiresExtendsBlock = false; + this.isResident = false; + this.isDeclareFile = false; + this.hasBeenTypeChecked = false; + this.topLevelMod = null; + this.leftCurlyCount = 0; + this.rightCurlyCount = 0; + this.containsUnicodeChar = false; + this.containsUnicodeCharInComment = false; + this.externallyVisibleImportedSymbols = []; + this.vars = vars; + this.scopes = scopes; + } + Script.prototype.setCachedEmitRequired = function (value) { + this.cachedEmitRequired = value; + return this.cachedEmitRequired; + }; + Script.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckScript(this); + }; + Script.prototype.treeViewLabel = function () { + return "Script"; + }; + Script.prototype.emitRequired = function (emitOptions) { + if(this.cachedEmitRequired != undefined) { + return this.cachedEmitRequired; + } + if(!this.isDeclareFile && !this.isResident && this.bod) { + for(var i = 0, len = this.bod.members.length; i < len; i++) { + var stmt = this.bod.members[i]; + if(stmt.nodeType == TypeScript.NodeType.ModuleDeclaration) { + if(!TypeScript.hasFlag((stmt).modFlags, TypeScript.ModuleFlags.ShouldEmitModuleDecl | TypeScript.ModuleFlags.Ambient)) { + return this.setCachedEmitRequired(true); + } + } else { + if(stmt.nodeType == TypeScript.NodeType.ClassDeclaration) { + if(!TypeScript.hasFlag((stmt).varFlags, TypeScript.VarFlags.Ambient)) { + return this.setCachedEmitRequired(true); + } + } else { + if(stmt.nodeType == TypeScript.NodeType.VarDecl) { + if(!TypeScript.hasFlag((stmt).varFlags, TypeScript.VarFlags.Ambient)) { + return this.setCachedEmitRequired(true); + } + } else { + if(stmt.nodeType == TypeScript.NodeType.FuncDecl) { + if(!(stmt).isSignature()) { + return this.setCachedEmitRequired(true); + } + } else { + if(stmt.nodeType != TypeScript.NodeType.InterfaceDeclaration && stmt.nodeType != TypeScript.NodeType.Empty) { + return this.setCachedEmitRequired(true); + } + } + } + } + } + } + if(emitOptions.emitComments && ((this.bod.preComments && this.bod.preComments.length > 0) || (this.bod.postComments && this.bod.postComments.length > 0))) { + return this.setCachedEmitRequired(true); + } + } + return this.setCachedEmitRequired(false); + }; + Script.prototype.emit = function (emitter, tokenId, startLine) { + if(this.emitRequired(emitter.emitOptions)) { + emitter.emitParensAndCommentsInPlace(this.bod, true); + emitter.emitJavascriptList(this.bod, null, TypeScript.TokenID.Semicolon, true, false, false, true, this.requiresExtendsBlock); + emitter.emitParensAndCommentsInPlace(this.bod, false); + } + }; + Script.prototype.AddExternallyVisibleImportedSymbol = function (symbol, checker) { + if(this.isExternallyVisibleSymbol(symbol)) { + return; + } + if(!symbol.getType().symbol.isExternallyVisible(checker)) { + var quotes = ""; + var moduleName = symbol.getType().symbol.prettyName; + if(!TypeScript.isQuoted(moduleName)) { + quotes = "'"; + } + checker.errorReporter.simpleError(symbol.declAST, "Externally visible import statement uses non exported module " + quotes + moduleName + quotes); + } + this.externallyVisibleImportedSymbols.push(symbol); + }; + Script.prototype.isExternallyVisibleSymbol = function (symbol) { + for(var i = 0; i < this.externallyVisibleImportedSymbols.length; i++) { + if(this.externallyVisibleImportedSymbols[i] == symbol) { + return true; + } + } + return false; + }; + return Script; + })(FuncDecl); + TypeScript.Script = Script; + var NamedDeclaration = (function (_super) { + __extends(NamedDeclaration, _super); + function NamedDeclaration(nodeType, name, members) { + _super.call(this, nodeType); + this.name = name; + this.members = members; + this.leftCurlyCount = 0; + this.rightCurlyCount = 0; + } + NamedDeclaration.prototype.isDeclaration = function () { + return true; + }; + return NamedDeclaration; + })(ModuleElement); + TypeScript.NamedDeclaration = NamedDeclaration; + var ModuleDeclaration = (function (_super) { + __extends(ModuleDeclaration, _super); + function ModuleDeclaration(name, members, vars, scopes, endingToken) { + _super.call(this, TypeScript.NodeType.ModuleDeclaration, name, members); + this.endingToken = endingToken; + this.modFlags = TypeScript.ModuleFlags.ShouldEmitModuleDecl; + this.amdDependencies = []; + this.containsUnicodeChar = false; + this.containsUnicodeCharInComment = false; + this.vars = vars; + this.scopes = scopes; + this.prettyName = this.name.actualText; + } + ModuleDeclaration.prototype.isExported = function () { + return TypeScript.hasFlag(this.modFlags, TypeScript.ModuleFlags.Exported); + }; + ModuleDeclaration.prototype.isAmbient = function () { + return TypeScript.hasFlag(this.modFlags, TypeScript.ModuleFlags.Ambient); + }; + ModuleDeclaration.prototype.isEnum = function () { + return TypeScript.hasFlag(this.modFlags, TypeScript.ModuleFlags.IsEnum); + }; + ModuleDeclaration.prototype.recordNonInterface = function () { + this.modFlags &= ~TypeScript.ModuleFlags.ShouldEmitModuleDecl; + }; + ModuleDeclaration.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckModule(this); + }; + ModuleDeclaration.prototype.emit = function (emitter, tokenId, startLine) { + if(!TypeScript.hasFlag(this.modFlags, TypeScript.ModuleFlags.ShouldEmitModuleDecl)) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.emitJavascriptModule(this); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + } + }; + return ModuleDeclaration; + })(NamedDeclaration); + TypeScript.ModuleDeclaration = ModuleDeclaration; + var TypeDeclaration = (function (_super) { + __extends(TypeDeclaration, _super); + function TypeDeclaration(nodeType, name, extendsList, implementsList, members) { + _super.call(this, nodeType, name, members); + this.extendsList = extendsList; + this.implementsList = implementsList; + this.varFlags = TypeScript.VarFlags.None; + } + TypeDeclaration.prototype.isExported = function () { + return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Exported); + }; + TypeDeclaration.prototype.isAmbient = function () { + return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Ambient); + }; + return TypeDeclaration; + })(NamedDeclaration); + TypeScript.TypeDeclaration = TypeDeclaration; + var ClassDeclaration = (function (_super) { + __extends(ClassDeclaration, _super); + function ClassDeclaration(name, members, extendsList, implementsList) { + _super.call(this, TypeScript.NodeType.ClassDeclaration, name, extendsList, implementsList, members); + this.knownMemberNames = { + }; + this.constructorDecl = null; + this.constructorNestingLevel = 0; + this.endingToken = null; + } + ClassDeclaration.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckClass(this); + }; + ClassDeclaration.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitJavascriptClass(this); + }; + return ClassDeclaration; + })(TypeDeclaration); + TypeScript.ClassDeclaration = ClassDeclaration; + var InterfaceDeclaration = (function (_super) { + __extends(InterfaceDeclaration, _super); + function InterfaceDeclaration(name, members, extendsList, implementsList) { + _super.call(this, TypeScript.NodeType.InterfaceDeclaration, name, extendsList, implementsList, members); + } + InterfaceDeclaration.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckInterface(this); + }; + InterfaceDeclaration.prototype.emit = function (emitter, tokenId, startLine) { + }; + return InterfaceDeclaration; + })(TypeDeclaration); + TypeScript.InterfaceDeclaration = InterfaceDeclaration; + var Statement = (function (_super) { + __extends(Statement, _super); + function Statement(nodeType) { + _super.call(this, nodeType); + this.flags |= TypeScript.ASTFlags.IsStatement; + } + Statement.prototype.isLoop = function () { + return false; + }; + Statement.prototype.isStatementOrExpression = function () { + return true; + }; + Statement.prototype.isCompoundStatement = function () { + return this.isLoop(); + }; + Statement.prototype.typeCheck = function (typeFlow) { + this.type = typeFlow.voidType; + return this; + }; + return Statement; + })(ModuleElement); + TypeScript.Statement = Statement; + var LabeledStatement = (function (_super) { + __extends(LabeledStatement, _super); + function LabeledStatement(labels, stmt) { + _super.call(this, TypeScript.NodeType.LabeledStatement); + this.labels = labels; + this.stmt = stmt; + } + LabeledStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + if(this.labels) { + var labelsLen = this.labels.members.length; + for(var i = 0; i < labelsLen; i++) { + this.labels.members[i].emit(emitter, tokenId, startLine); + } + } + this.stmt.emit(emitter, tokenId, true); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + LabeledStatement.prototype.typeCheck = function (typeFlow) { + typeFlow.typeCheck(this.labels); + this.stmt = this.stmt.typeCheck(typeFlow); + return this; + }; + LabeledStatement.prototype.addToControlFlow = function (context) { + var beforeBB = context.current; + var bb = new TypeScript.BasicBlock(); + context.current = bb; + beforeBB.addSuccessor(bb); + }; + return LabeledStatement; + })(Statement); + TypeScript.LabeledStatement = LabeledStatement; + var Block = (function (_super) { + __extends(Block, _super); + function Block(statements, isStatementBlock) { + _super.call(this, TypeScript.NodeType.Block); + this.statements = statements; + this.isStatementBlock = isStatementBlock; + } + Block.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + if(this.isStatementBlock) { + emitter.writeLineToOutput(" {"); + emitter.indenter.increaseIndent(); + } else { + emitter.setInVarBlock(this.statements.members.length); + } + var temp = emitter.setInObjectLiteral(false); + if(this.statements) { + emitter.emitJavascriptList(this.statements, null, TypeScript.TokenID.Semicolon, true, false, false); + } + if(this.isStatementBlock) { + emitter.indenter.decreaseIndent(); + emitter.emitIndent(); + emitter.writeToOutput("}"); + } + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + Block.prototype.addToControlFlow = function (context) { + var afterIfNeeded = new TypeScript.BasicBlock(); + context.pushStatement(this, context.current, afterIfNeeded); + if(this.statements) { + context.walk(this.statements, this); + } + context.walker.options.goChildren = false; + context.popStatement(); + if(afterIfNeeded.predecessors.length > 0) { + context.current.addSuccessor(afterIfNeeded); + context.current = afterIfNeeded; + } + }; + Block.prototype.typeCheck = function (typeFlow) { + if(!typeFlow.checker.styleSettings.emptyBlocks) { + if((this.statements === null) || (this.statements.members.length == 0)) { + typeFlow.checker.errorReporter.styleError(this, "empty block"); + } + } + typeFlow.typeCheck(this.statements); + return this; + }; + return Block; + })(Statement); + TypeScript.Block = Block; + var Jump = (function (_super) { + __extends(Jump, _super); + function Jump(nodeType) { + _super.call(this, nodeType); + this.target = null; + this.resolvedTarget = null; + } + Jump.prototype.hasExplicitTarget = function () { + return (this.target); + }; + Jump.prototype.setResolvedTarget = function (parser, stmt) { + if(stmt.isLoop()) { + this.resolvedTarget = stmt; + return true; + } + if(this.nodeType === TypeScript.NodeType.Continue) { + parser.reportParseError("continue statement applies only to loops"); + return false; + } else { + if((stmt.nodeType == TypeScript.NodeType.Switch) || this.hasExplicitTarget()) { + this.resolvedTarget = stmt; + return true; + } else { + parser.reportParseError("break statement with no label can apply only to a loop or switch statement"); + return false; + } + } + }; + Jump.prototype.addToControlFlow = function (context) { + _super.prototype.addToControlFlow.call(this, context); + context.unconditionalBranch(this.resolvedTarget, (this.nodeType == TypeScript.NodeType.Continue)); + }; + Jump.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + if(this.nodeType == TypeScript.NodeType.Break) { + emitter.writeToOutput("break"); + } else { + emitter.writeToOutput("continue"); + } + if(this.hasExplicitTarget()) { + emitter.writeToOutput(" " + this.target); + } + emitter.recordSourceMappingEnd(this); + emitter.writeToOutput(";"); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return Jump; + })(Statement); + TypeScript.Jump = Jump; + var WhileStatement = (function (_super) { + __extends(WhileStatement, _super); + function WhileStatement(cond) { + _super.call(this, TypeScript.NodeType.While); + this.cond = cond; + this.body = null; + } + WhileStatement.prototype.isLoop = function () { + return true; + }; + WhileStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + emitter.writeToOutput("while("); + emitter.emitJavascript(this.cond, TypeScript.TokenID.While, false); + emitter.writeToOutput(")"); + emitter.emitJavascriptStatements(this.body, false); + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + WhileStatement.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckWhile(this); + }; + WhileStatement.prototype.addToControlFlow = function (context) { + var loopHeader = context.current; + var loopStart = new TypeScript.BasicBlock(); + var afterLoop = new TypeScript.BasicBlock(); + loopHeader.addSuccessor(loopStart); + context.current = loopStart; + context.addContent(this.cond); + var condBlock = context.current; + var targetInfo = null; + if(this.body) { + context.current = new TypeScript.BasicBlock(); + condBlock.addSuccessor(context.current); + context.pushStatement(this, loopStart, afterLoop); + context.walk(this.body, this); + targetInfo = context.popStatement(); + } + if(!(context.noContinuation)) { + var loopEnd = context.current; + loopEnd.addSuccessor(loopStart); + } + context.current = afterLoop; + condBlock.addSuccessor(afterLoop); + context.noContinuation = false; + context.walker.options.goChildren = false; + }; + return WhileStatement; + })(Statement); + TypeScript.WhileStatement = WhileStatement; + var DoWhileStatement = (function (_super) { + __extends(DoWhileStatement, _super); + function DoWhileStatement() { + _super.call(this, TypeScript.NodeType.DoWhile); + this.body = null; + this.whileAST = null; + this.cond = null; + } + DoWhileStatement.prototype.isLoop = function () { + return true; + }; + DoWhileStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + emitter.writeToOutput("do"); + emitter.emitJavascriptStatements(this.body, true); + emitter.recordSourceMappingStart(this.whileAST); + emitter.writeToOutput("while"); + emitter.recordSourceMappingEnd(this.whileAST); + emitter.writeToOutput('('); + emitter.emitJavascript(this.cond, TypeScript.TokenID.CloseParen, false); + emitter.writeToOutput(")"); + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.writeToOutput(";"); + emitter.emitParensAndCommentsInPlace(this, false); + }; + DoWhileStatement.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckDoWhile(this); + }; + DoWhileStatement.prototype.addToControlFlow = function (context) { + var loopHeader = context.current; + var loopStart = new TypeScript.BasicBlock(); + var afterLoop = new TypeScript.BasicBlock(); + loopHeader.addSuccessor(loopStart); + context.current = loopStart; + var targetInfo = null; + if(this.body) { + context.pushStatement(this, loopStart, afterLoop); + context.walk(this.body, this); + targetInfo = context.popStatement(); + } + if(!(context.noContinuation)) { + var loopEnd = context.current; + loopEnd.addSuccessor(loopStart); + context.addContent(this.cond); + context.current = afterLoop; + loopEnd.addSuccessor(afterLoop); + } else { + context.addUnreachable(this.cond); + } + context.walker.options.goChildren = false; + }; + return DoWhileStatement; + })(Statement); + TypeScript.DoWhileStatement = DoWhileStatement; + var IfStatement = (function (_super) { + __extends(IfStatement, _super); + function IfStatement(cond) { + _super.call(this, TypeScript.NodeType.If); + this.cond = cond; + this.elseBod = null; + this.statement = new ASTSpan(); + } + IfStatement.prototype.isCompoundStatement = function () { + return true; + }; + IfStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + emitter.recordSourceMappingStart(this.statement); + emitter.writeToOutput("if("); + emitter.emitJavascript(this.cond, TypeScript.TokenID.If, false); + emitter.writeToOutput(")"); + emitter.recordSourceMappingEnd(this.statement); + emitter.emitJavascriptStatements(this.thenBod, true); + if(this.elseBod) { + if(this.elseBod.nodeType === TypeScript.NodeType.If) { + emitter.writeToOutput(" else "); + this.elseBod.emit(emitter, tokenId, false); + } else { + emitter.writeToOutput(" else"); + emitter.emitJavascriptStatements(this.elseBod, true); + } + } + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + IfStatement.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckIf(this); + }; + IfStatement.prototype.addToControlFlow = function (context) { + this.cond.addToControlFlow(context); + var afterIf = new TypeScript.BasicBlock(); + var beforeIf = context.current; + context.pushStatement(this, beforeIf, afterIf); + var hasContinuation = false; + context.current = new TypeScript.BasicBlock(); + beforeIf.addSuccessor(context.current); + context.walk(this.thenBod, this); + if(!context.noContinuation) { + hasContinuation = true; + context.current.addSuccessor(afterIf); + } + if(this.elseBod) { + context.current = new TypeScript.BasicBlock(); + context.noContinuation = false; + beforeIf.addSuccessor(context.current); + context.walk(this.elseBod, this); + if(!context.noContinuation) { + hasContinuation = true; + context.current.addSuccessor(afterIf); + } else { + if(hasContinuation) { + context.noContinuation = false; + } + } + } else { + beforeIf.addSuccessor(afterIf); + context.noContinuation = false; + hasContinuation = true; + } + var targetInfo = context.popStatement(); + if(afterIf.predecessors.length > 0) { + context.noContinuation = false; + hasContinuation = true; + } + if(hasContinuation) { + context.current = afterIf; + } + context.walker.options.goChildren = false; + }; + return IfStatement; + })(Statement); + TypeScript.IfStatement = IfStatement; + var ReturnStatement = (function (_super) { + __extends(ReturnStatement, _super); + function ReturnStatement() { + _super.call(this, TypeScript.NodeType.Return); + this.returnExpression = null; + } + ReturnStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + if(this.returnExpression) { + emitter.writeToOutput("return "); + emitter.emitJavascript(this.returnExpression, TypeScript.TokenID.Semicolon, false); + if(this.returnExpression.nodeType === TypeScript.NodeType.FuncDecl) { + emitter.writeToOutput(";"); + } + } else { + emitter.writeToOutput("return;"); + } + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + ReturnStatement.prototype.addToControlFlow = function (context) { + _super.prototype.addToControlFlow.call(this, context); + context.returnStmt(); + }; + ReturnStatement.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckReturn(this); + }; + return ReturnStatement; + })(Statement); + TypeScript.ReturnStatement = ReturnStatement; + var EndCode = (function (_super) { + __extends(EndCode, _super); + function EndCode() { + _super.call(this, TypeScript.NodeType.EndCode); + } + return EndCode; + })(AST); + TypeScript.EndCode = EndCode; + var ForInStatement = (function (_super) { + __extends(ForInStatement, _super); + function ForInStatement(lval, obj) { + _super.call(this, TypeScript.NodeType.ForIn); + this.lval = lval; + this.obj = obj; + this.statement = new ASTSpan(); + if(this.lval && (this.lval.nodeType == TypeScript.NodeType.VarDecl)) { + (this.lval).varFlags |= TypeScript.VarFlags.AutoInit; + } + } + ForInStatement.prototype.isLoop = function () { + return true; + }; + ForInStatement.prototype.isFiltered = function () { + if(this.body) { + var singleItem = null; + if(this.body.nodeType == TypeScript.NodeType.List) { + var stmts = this.body; + if(stmts.members.length == 1) { + singleItem = stmts.members[0]; + } + } else { + singleItem = this.body; + } + if(singleItem !== null) { + if(singleItem.nodeType == TypeScript.NodeType.Block) { + var block = singleItem; + if((block.statements !== null) && (block.statements.members.length == 1)) { + singleItem = block.statements.members[0]; + } + } + if(singleItem.nodeType == TypeScript.NodeType.If) { + var cond = (singleItem).cond; + if(cond.nodeType == TypeScript.NodeType.Call) { + var target = (cond).target; + if(target.nodeType == TypeScript.NodeType.Dot) { + var binex = target; + if((binex.operand1.nodeType == TypeScript.NodeType.Name) && (this.obj.nodeType == TypeScript.NodeType.Name) && ((binex.operand1).actualText == (this.obj).actualText)) { + var prop = binex.operand2; + if(prop.actualText == "hasOwnProperty") { + var args = (cond).arguments; + if((args !== null) && (args.members.length == 1)) { + var arg = args.members[0]; + if((arg.nodeType == TypeScript.NodeType.Name) && (this.lval.nodeType == TypeScript.NodeType.Name)) { + if(((this.lval).actualText) == (arg).actualText) { + return true; + } + } + } + } + } + } + } + } + } + } + return false; + }; + ForInStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + emitter.recordSourceMappingStart(this.statement); + emitter.writeToOutput("for("); + emitter.emitJavascript(this.lval, TypeScript.TokenID.For, false); + emitter.writeToOutput(" in "); + emitter.emitJavascript(this.obj, TypeScript.TokenID.For, false); + emitter.writeToOutput(")"); + emitter.recordSourceMappingEnd(this.statement); + emitter.emitJavascriptStatements(this.body, true); + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + ForInStatement.prototype.typeCheck = function (typeFlow) { + if(typeFlow.checker.styleSettings.forin) { + if(!this.isFiltered()) { + typeFlow.checker.errorReporter.styleError(this, "no hasOwnProperty filter"); + } + } + return typeFlow.typeCheckForIn(this); + }; + ForInStatement.prototype.addToControlFlow = function (context) { + if(this.lval) { + context.addContent(this.lval); + } + if(this.obj) { + context.addContent(this.obj); + } + var loopHeader = context.current; + var loopStart = new TypeScript.BasicBlock(); + var afterLoop = new TypeScript.BasicBlock(); + loopHeader.addSuccessor(loopStart); + context.current = loopStart; + if(this.body) { + context.pushStatement(this, loopStart, afterLoop); + context.walk(this.body, this); + context.popStatement(); + } + if(!(context.noContinuation)) { + var loopEnd = context.current; + loopEnd.addSuccessor(loopStart); + } + context.current = afterLoop; + context.noContinuation = false; + loopHeader.addSuccessor(afterLoop); + context.walker.options.goChildren = false; + }; + return ForInStatement; + })(Statement); + TypeScript.ForInStatement = ForInStatement; + var ForStatement = (function (_super) { + __extends(ForStatement, _super); + function ForStatement(init) { + _super.call(this, TypeScript.NodeType.For); + this.init = init; + } + ForStatement.prototype.isLoop = function () { + return true; + }; + ForStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + emitter.writeToOutput("for("); + if(this.init) { + if(this.init.nodeType != TypeScript.NodeType.List) { + emitter.emitJavascript(this.init, TypeScript.TokenID.For, false); + } else { + emitter.setInVarBlock((this.init).members.length); + emitter.emitJavascriptList(this.init, null, TypeScript.TokenID.For, false, false, false); + } + } + emitter.writeToOutput("; "); + emitter.emitJavascript(this.cond, TypeScript.TokenID.For, false); + emitter.writeToOutput("; "); + emitter.emitJavascript(this.incr, TypeScript.TokenID.For, false); + emitter.writeToOutput(")"); + emitter.emitJavascriptStatements(this.body, true); + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + ForStatement.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckFor(this); + }; + ForStatement.prototype.addToControlFlow = function (context) { + if(this.init) { + context.addContent(this.init); + } + var loopHeader = context.current; + var loopStart = new TypeScript.BasicBlock(); + var afterLoop = new TypeScript.BasicBlock(); + loopHeader.addSuccessor(loopStart); + context.current = loopStart; + var condBlock = null; + var continueTarget = loopStart; + var incrBB = null; + if(this.incr) { + incrBB = new TypeScript.BasicBlock(); + continueTarget = incrBB; + } + if(this.cond) { + condBlock = context.current; + context.addContent(this.cond); + context.current = new TypeScript.BasicBlock(); + condBlock.addSuccessor(context.current); + } + var targetInfo = null; + if(this.body) { + context.pushStatement(this, continueTarget, afterLoop); + context.walk(this.body, this); + targetInfo = context.popStatement(); + } + if(this.incr) { + if(context.noContinuation) { + if(incrBB.predecessors.length == 0) { + context.addUnreachable(this.incr); + } + } else { + context.current.addSuccessor(incrBB); + context.current = incrBB; + context.addContent(this.incr); + } + } + var loopEnd = context.current; + if(!(context.noContinuation)) { + loopEnd.addSuccessor(loopStart); + } + if(condBlock) { + condBlock.addSuccessor(afterLoop); + context.noContinuation = false; + } + if(afterLoop.predecessors.length > 0) { + context.noContinuation = false; + context.current = afterLoop; + } + context.walker.options.goChildren = false; + }; + return ForStatement; + })(Statement); + TypeScript.ForStatement = ForStatement; + var WithStatement = (function (_super) { + __extends(WithStatement, _super); + function WithStatement(expr) { + _super.call(this, TypeScript.NodeType.With); + this.expr = expr; + this.withSym = null; + } + WithStatement.prototype.isCompoundStatement = function () { + return true; + }; + WithStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("with ("); + if(this.expr) { + emitter.emitJavascript(this.expr, TypeScript.TokenID.With, false); + } + emitter.writeToOutput(")"); + emitter.emitJavascriptStatements(this.body, true); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + WithStatement.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckWith(this); + }; + return WithStatement; + })(Statement); + TypeScript.WithStatement = WithStatement; + var SwitchStatement = (function (_super) { + __extends(SwitchStatement, _super); + function SwitchStatement(val) { + _super.call(this, TypeScript.NodeType.Switch); + this.val = val; + this.defaultCase = null; + this.statement = new ASTSpan(); + } + SwitchStatement.prototype.isCompoundStatement = function () { + return true; + }; + SwitchStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + emitter.recordSourceMappingStart(this.statement); + emitter.writeToOutput("switch("); + emitter.emitJavascript(this.val, TypeScript.TokenID.Identifier, false); + emitter.writeToOutput(")"); + emitter.recordSourceMappingEnd(this.statement); + emitter.writeLineToOutput(" {"); + emitter.indenter.increaseIndent(); + var casesLen = this.caseList.members.length; + for(var i = 0; i < casesLen; i++) { + var caseExpr = this.caseList.members[i]; + emitter.emitJavascript(caseExpr, TypeScript.TokenID.Case, true); + } + emitter.indenter.decreaseIndent(); + emitter.emitIndent(); + emitter.writeToOutput("}"); + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + SwitchStatement.prototype.typeCheck = function (typeFlow) { + var len = this.caseList.members.length; + this.val = typeFlow.typeCheck(this.val); + for(var i = 0; i < len; i++) { + this.caseList.members[i] = typeFlow.typeCheck(this.caseList.members[i]); + } + this.defaultCase = typeFlow.typeCheck(this.defaultCase); + this.type = typeFlow.voidType; + return this; + }; + SwitchStatement.prototype.addToControlFlow = function (context) { + var condBlock = context.current; + context.addContent(this.val); + var execBlock = new TypeScript.BasicBlock(); + var afterSwitch = new TypeScript.BasicBlock(); + condBlock.addSuccessor(execBlock); + context.pushSwitch(execBlock); + context.current = execBlock; + context.pushStatement(this, execBlock, afterSwitch); + context.walk(this.caseList, this); + context.popSwitch(); + var targetInfo = context.popStatement(); + var hasCondContinuation = (this.defaultCase == null); + if(this.defaultCase == null) { + condBlock.addSuccessor(afterSwitch); + } + if(afterSwitch.predecessors.length > 0) { + context.noContinuation = false; + context.current = afterSwitch; + } else { + context.noContinuation = true; + } + context.walker.options.goChildren = false; + }; + return SwitchStatement; + })(Statement); + TypeScript.SwitchStatement = SwitchStatement; + var CaseStatement = (function (_super) { + __extends(CaseStatement, _super); + function CaseStatement() { + _super.call(this, TypeScript.NodeType.Case); + this.expr = null; + } + CaseStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + if(this.expr) { + emitter.writeToOutput("case "); + emitter.emitJavascript(this.expr, TypeScript.TokenID.Identifier, false); + } else { + emitter.writeToOutput("default"); + } + emitter.writeToOutput(":"); + if(this.body.members.length == 1 && this.body.members[0].nodeType == TypeScript.NodeType.Block) { + emitter.emitJavascriptStatements(this.body, false); + } else { + emitter.writeLineToOutput(""); + emitter.indenter.increaseIndent(); + emitter.emitBareJavascriptStatements(this.body); + emitter.indenter.decreaseIndent(); + } + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + CaseStatement.prototype.typeCheck = function (typeFlow) { + this.expr = typeFlow.typeCheck(this.expr); + typeFlow.typeCheck(this.body); + this.type = typeFlow.voidType; + return this; + }; + CaseStatement.prototype.addToControlFlow = function (context) { + var execBlock = new TypeScript.BasicBlock(); + var sw = context.currentSwitch[context.currentSwitch.length - 1]; + if(this.expr) { + var exprBlock = new TypeScript.BasicBlock(); + context.current = exprBlock; + sw.addSuccessor(exprBlock); + context.addContent(this.expr); + exprBlock.addSuccessor(execBlock); + } else { + sw.addSuccessor(execBlock); + } + context.current = execBlock; + if(this.body) { + context.walk(this.body, this); + } + context.noContinuation = false; + context.walker.options.goChildren = false; + }; + return CaseStatement; + })(Statement); + TypeScript.CaseStatement = CaseStatement; + var TypeReference = (function (_super) { + __extends(TypeReference, _super); + function TypeReference(term, arrayCount) { + _super.call(this, TypeScript.NodeType.TypeRef); + this.term = term; + this.arrayCount = arrayCount; + } + TypeReference.prototype.emit = function (emitter, tokenId, startLine) { + throw new Error("should not emit a type ref"); + }; + TypeReference.prototype.typeCheck = function (typeFlow) { + var prevInTCTR = typeFlow.inTypeRefTypeCheck; + typeFlow.inTypeRefTypeCheck = true; + var typeLink = TypeScript.getTypeLink(this, typeFlow.checker, true); + typeFlow.checker.resolveTypeLink(typeFlow.scope, typeLink, false); + if(this.term) { + typeFlow.typeCheck(this.term); + } + typeFlow.checkForVoidConstructor(typeLink.type, this); + this.type = typeLink.type; + if(this.term) { + this.term.type = this.type; + } + typeFlow.inTypeRefTypeCheck = prevInTCTR; + return this; + }; + return TypeReference; + })(AST); + TypeScript.TypeReference = TypeReference; + var TryFinally = (function (_super) { + __extends(TryFinally, _super); + function TryFinally(tryNode, finallyNode) { + _super.call(this, TypeScript.NodeType.TryFinally); + this.tryNode = tryNode; + this.finallyNode = finallyNode; + } + TryFinally.prototype.isCompoundStatement = function () { + return true; + }; + TryFinally.prototype.emit = function (emitter, tokenId, startLine) { + emitter.recordSourceMappingStart(this); + emitter.emitJavascript(this.tryNode, TypeScript.TokenID.Try, false); + emitter.emitJavascript(this.finallyNode, TypeScript.TokenID.Finally, false); + emitter.recordSourceMappingEnd(this); + }; + TryFinally.prototype.typeCheck = function (typeFlow) { + this.tryNode = typeFlow.typeCheck(this.tryNode); + this.finallyNode = typeFlow.typeCheck(this.finallyNode); + this.type = typeFlow.voidType; + return this; + }; + TryFinally.prototype.addToControlFlow = function (context) { + var afterFinally = new TypeScript.BasicBlock(); + context.walk(this.tryNode, this); + var finBlock = new TypeScript.BasicBlock(); + if(context.current) { + context.current.addSuccessor(finBlock); + } + context.current = finBlock; + context.pushStatement(this, null, afterFinally); + context.walk(this.finallyNode, this); + if(!context.noContinuation && context.current) { + context.current.addSuccessor(afterFinally); + } + if(afterFinally.predecessors.length > 0) { + context.current = afterFinally; + } else { + context.noContinuation = true; + } + context.popStatement(); + context.walker.options.goChildren = false; + }; + return TryFinally; + })(Statement); + TypeScript.TryFinally = TryFinally; + var TryCatch = (function (_super) { + __extends(TryCatch, _super); + function TryCatch(tryNode, catchNode) { + _super.call(this, TypeScript.NodeType.TryCatch); + this.tryNode = tryNode; + this.catchNode = catchNode; + } + TryCatch.prototype.isCompoundStatement = function () { + return true; + }; + TryCatch.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.emitJavascript(this.tryNode, TypeScript.TokenID.Try, false); + emitter.emitJavascript(this.catchNode, TypeScript.TokenID.Catch, false); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + TryCatch.prototype.addToControlFlow = function (context) { + var beforeTry = context.current; + var tryBlock = new TypeScript.BasicBlock(); + beforeTry.addSuccessor(tryBlock); + context.current = tryBlock; + var afterTryCatch = new TypeScript.BasicBlock(); + context.pushStatement(this, null, afterTryCatch); + context.walk(this.tryNode, this); + if(!context.noContinuation) { + if(context.current) { + context.current.addSuccessor(afterTryCatch); + } + } + context.current = new TypeScript.BasicBlock(); + beforeTry.addSuccessor(context.current); + context.walk(this.catchNode, this); + context.popStatement(); + if(!context.noContinuation) { + if(context.current) { + context.current.addSuccessor(afterTryCatch); + } + } + context.current = afterTryCatch; + context.walker.options.goChildren = false; + }; + TryCatch.prototype.typeCheck = function (typeFlow) { + this.tryNode = typeFlow.typeCheck(this.tryNode); + this.catchNode = typeFlow.typeCheck(this.catchNode); + this.type = typeFlow.voidType; + return this; + }; + return TryCatch; + })(Statement); + TypeScript.TryCatch = TryCatch; + var Try = (function (_super) { + __extends(Try, _super); + function Try(body) { + _super.call(this, TypeScript.NodeType.Try); + this.body = body; + } + Try.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("try "); + emitter.emitJavascript(this.body, TypeScript.TokenID.Try, false); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + Try.prototype.typeCheck = function (typeFlow) { + this.body = typeFlow.typeCheck(this.body); + return this; + }; + Try.prototype.addToControlFlow = function (context) { + if(this.body) { + context.walk(this.body, this); + } + context.walker.options.goChildren = false; + context.noContinuation = false; + }; + return Try; + })(Statement); + TypeScript.Try = Try; + var Catch = (function (_super) { + __extends(Catch, _super); + function Catch(param, body) { + _super.call(this, TypeScript.NodeType.Catch); + this.param = param; + this.body = body; + this.statement = new ASTSpan(); + this.containedScope = null; + if(this.param) { + this.param.varFlags |= TypeScript.VarFlags.AutoInit; + } + } + Catch.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput(" "); + emitter.recordSourceMappingStart(this.statement); + emitter.writeToOutput("catch ("); + emitter.emitJavascript(this.param, TypeScript.TokenID.OpenParen, false); + emitter.writeToOutput(")"); + emitter.recordSourceMappingEnd(this.statement); + emitter.emitJavascript(this.body, TypeScript.TokenID.Catch, false); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + Catch.prototype.addToControlFlow = function (context) { + if(this.param) { + context.addContent(this.param); + var bodBlock = new TypeScript.BasicBlock(); + context.current.addSuccessor(bodBlock); + context.current = bodBlock; + } + if(this.body) { + context.walk(this.body, this); + } + context.noContinuation = false; + context.walker.options.goChildren = false; + }; + Catch.prototype.typeCheck = function (typeFlow) { + var prevScope = typeFlow.scope; + typeFlow.scope = this.containedScope; + this.param = typeFlow.typeCheck(this.param); + var exceptVar = new TypeScript.ValueLocation(); + var varSym = new TypeScript.VariableSymbol((this.param).id.text, this.param.minChar, typeFlow.checker.locationInfo.unitIndex, exceptVar); + exceptVar.symbol = varSym; + exceptVar.typeLink = new TypeScript.TypeLink(); + exceptVar.typeLink.type = typeFlow.anyType; + var thisFnc = typeFlow.thisFnc; + if(thisFnc && thisFnc.type) { + exceptVar.symbol.container = thisFnc.type.symbol; + } else { + exceptVar.symbol.container = null; + } + this.param.sym = exceptVar.symbol; + typeFlow.scope.enter(exceptVar.symbol.container, this.param, exceptVar.symbol, typeFlow.checker.errorReporter, false, false, false); + this.body = typeFlow.typeCheck(this.body); + if(typeFlow.checker.inProvisionalTypecheckMode()) { + var table = typeFlow.scope.getTable(); + (table).secondaryTable.table[exceptVar.symbol.name] = undefined; + } + this.type = typeFlow.voidType; + typeFlow.scope = prevScope; + return this; + }; + return Catch; + })(Statement); + TypeScript.Catch = Catch; + var Finally = (function (_super) { + __extends(Finally, _super); + function Finally(body) { + _super.call(this, TypeScript.NodeType.Finally); + this.body = body; + } + Finally.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("finally"); + emitter.emitJavascript(this.body, TypeScript.TokenID.Finally, false); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + Finally.prototype.addToControlFlow = function (context) { + if(this.body) { + context.walk(this.body, this); + } + context.walker.options.goChildren = false; + context.noContinuation = false; + }; + Finally.prototype.typeCheck = function (typeFlow) { + this.body = typeFlow.typeCheck(this.body); + return this; + }; + return Finally; + })(Statement); + TypeScript.Finally = Finally; + var Comment = (function (_super) { + __extends(Comment, _super); + function Comment(content, isBlockComment, endsLine) { + _super.call(this, TypeScript.NodeType.Comment); + this.content = content; + this.isBlockComment = isBlockComment; + this.endsLine = endsLine; + this.text = null; + this.docCommentText = null; + } + Comment.prototype.getText = function () { + if(this.text == null) { + if(this.isBlockComment) { + this.text = this.content.split("\n"); + for(var i = 0; i < this.text.length; i++) { + this.text[i] = this.text[i].replace(/^\s+|\s+$/g, ''); + } + } else { + this.text = [ + (this.content.replace(/^\s+|\s+$/g, '')) + ]; + } + } + return this.text; + }; + Comment.prototype.isDocComment = function () { + if(this.isBlockComment) { + return this.content.charAt(2) == "*"; + } + return false; + }; + Comment.prototype.getDocCommentText = function () { + if(this.docCommentText == null) { + this.docCommentText = Comment.cleanJSDocComment(this.content); + } + return this.docCommentText; + }; + Comment.consumeLeadingSpace = function consumeLeadingSpace(line, startIndex, maxSpacesToRemove) { + var endIndex = line.length; + if(maxSpacesToRemove != undefined) { + endIndex = TypeScript.min(startIndex + maxSpacesToRemove, endIndex); + } + for(; startIndex < endIndex; startIndex++) { + var charCode = line.charCodeAt(startIndex); + if(charCode != TypeScript.LexCodeSpace && charCode != TypeScript.LexCodeTAB) { + return startIndex; + } + } + if(endIndex != line.length) { + return endIndex; + } + return -1; + } + Comment.isSpaceChar = function isSpaceChar(line, index) { + var length = line.length; + if(index < length) { + var charCode = line.charCodeAt(index); + return charCode == TypeScript.LexCodeSpace || charCode == TypeScript.LexCodeTAB; + } + return index == length; + } + Comment.cleanDocCommentLine = function cleanDocCommentLine(line, jsDocStyleComment, jsDocLineSpaceToRemove) { + var nonSpaceIndex = Comment.consumeLeadingSpace(line, 0); + if(nonSpaceIndex != -1) { + var jsDocSpacesRemoved = nonSpaceIndex; + if(jsDocStyleComment && line.charAt(nonSpaceIndex) == '*') { + var startIndex = nonSpaceIndex + 1; + nonSpaceIndex = Comment.consumeLeadingSpace(line, startIndex, jsDocLineSpaceToRemove); + if(nonSpaceIndex != -1) { + jsDocSpacesRemoved = nonSpaceIndex - startIndex; + } else { + return null; + } + } + return { + minChar: nonSpaceIndex, + limChar: line.charAt(line.length - 1) == "\r" ? line.length - 1 : line.length, + jsDocSpacesRemoved: jsDocSpacesRemoved + }; + } + return null; + } + Comment.cleanJSDocComment = function cleanJSDocComment(content, spacesToRemove) { + var docCommentLines = []; + content = content.replace("/**", ""); + if(content.length >= 2 && content.charAt(content.length - 1) == "/" && content.charAt(content.length - 2) == "*") { + content = content.substring(0, content.length - 2); + } + var lines = content.split("\n"); + var inParamTag = false; + for(var l = 0; l < lines.length; l++) { + var line = lines[l]; + var cleanLinePos = Comment.cleanDocCommentLine(line, true, spacesToRemove); + if(!cleanLinePos) { + continue; + } + var docCommentText = ""; + var prevPos = cleanLinePos.minChar; + for(var i = line.indexOf("@", cleanLinePos.minChar); 0 <= i && i < cleanLinePos.limChar; i = line.indexOf("@", i + 1)) { + var wasInParamtag = inParamTag; + if(line.indexOf("param", i + 1) == i + 1 && Comment.isSpaceChar(line, i + 6)) { + if(!wasInParamtag) { + docCommentText += line.substring(prevPos, i); + } + prevPos = i; + inParamTag = true; + } else { + if(wasInParamtag) { + prevPos = i; + inParamTag = false; + } + } + } + if(!inParamTag) { + docCommentText += line.substring(prevPos, cleanLinePos.limChar); + } + var newCleanPos = Comment.cleanDocCommentLine(docCommentText, false); + if(newCleanPos) { + if(spacesToRemove == undefined) { + spacesToRemove = cleanLinePos.jsDocSpacesRemoved; + } + docCommentLines.push(docCommentText); + } + } + return docCommentLines.join("\n"); + } + Comment.getDocCommentText = function getDocCommentText(comments) { + var docCommentText = []; + for(var c = 0; c < comments.length; c++) { + var commentText = comments[c].getDocCommentText(); + if(commentText != "") { + docCommentText.push(commentText); + } + } + return docCommentText.join("\n"); + } + Comment.getParameterDocCommentText = function getParameterDocCommentText(param, fncDocComments) { + if(fncDocComments.length == 0 || !fncDocComments[0].isBlockComment) { + return ""; + } + for(var i = 0; i < fncDocComments.length; i++) { + var commentContents = fncDocComments[i].content; + for(var j = commentContents.indexOf("@param", 0); 0 <= j; j = commentContents.indexOf("@param", j)) { + j += 6; + if(!Comment.isSpaceChar(commentContents, j)) { + continue; + } + j = Comment.consumeLeadingSpace(commentContents, j); + if(j == -1) { + break; + } + if(commentContents.charCodeAt(j) == TypeScript.LexCodeLC) { + j++; + var charCode = 0; + for(var curlies = 1; j < commentContents.length; j++) { + charCode = commentContents.charCodeAt(j); + if(charCode == TypeScript.LexCodeLC) { + curlies++; + continue; + } + if(charCode == TypeScript.LexCodeRC) { + curlies--; + if(curlies == 0) { + break; + } else { + continue; + } + } + if(charCode == TypeScript.LexCodeAtSign) { + break; + } + } + if(j == commentContents.length) { + break; + } + if(charCode == TypeScript.LexCodeAtSign) { + continue; + } + j = Comment.consumeLeadingSpace(commentContents, j + 1); + if(j == -1) { + break; + } + } + if(param != commentContents.substr(j, param.length) || !Comment.isSpaceChar(commentContents, j + param.length)) { + continue; + } + j = Comment.consumeLeadingSpace(commentContents, j + param.length); + if(j == -1) { + return ""; + } + var endOfParam = commentContents.indexOf("@", j); + var paramHelpString = commentContents.substring(j, endOfParam < 0 ? commentContents.length : endOfParam); + var paramSpacesToRemove = undefined; + var paramLineIndex = commentContents.substring(0, j).lastIndexOf("\n") + 1; + if(paramLineIndex != 0) { + if(paramLineIndex < j && commentContents.charAt(paramLineIndex + 1) == "\r") { + paramLineIndex++; + } + } + var startSpaceRemovalIndex = Comment.consumeLeadingSpace(commentContents, paramLineIndex); + if(startSpaceRemovalIndex != j && commentContents.charAt(startSpaceRemovalIndex) == "*") { + paramSpacesToRemove = j - startSpaceRemovalIndex - 1; + } + return Comment.cleanJSDocComment(paramHelpString, paramSpacesToRemove); + } + } + return ""; + } + Comment.getDocCommentTextOfSignatures = function getDocCommentTextOfSignatures(signatures) { + var comments = []; + for(var i = 0; i < signatures.length; i++) { + var signatureDocComment = TypeScript.Comment.getDocCommentText(signatures[i].declAST.getDocComments()); + if(signatureDocComment != "") { + comments.push(signatureDocComment); + } + } + return comments.join("\n"); + } + return Comment; + })(AST); + TypeScript.Comment = Comment; + var DebuggerStatement = (function (_super) { + __extends(DebuggerStatement, _super); + function DebuggerStatement() { + _super.call(this, TypeScript.NodeType.Debugger); + } + DebuggerStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeLineToOutput("debugger;"); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return DebuggerStatement; + })(Statement); + TypeScript.DebuggerStatement = DebuggerStatement; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var AstWalkOptions = (function () { + function AstWalkOptions() { + this.goChildren = true; + this.goNextSibling = true; + this.reverseSiblings = false; + } + AstWalkOptions.prototype.stopWalk = function (stop) { + if (typeof stop === "undefined") { stop = true; } + this.goChildren = !stop; + this.goNextSibling = !stop; + }; + return AstWalkOptions; + })(); + TypeScript.AstWalkOptions = AstWalkOptions; + var AstWalker = (function () { + function AstWalker(childrenWalkers, pre, post, options, state) { + this.childrenWalkers = childrenWalkers; + this.pre = pre; + this.post = post; + this.options = options; + this.state = state; + } + AstWalker.prototype.walk = function (ast, parent) { + var preAst = this.pre(ast, parent, this); + if(preAst === undefined) { + preAst = ast; + } + if(this.options.goChildren) { + var svGoSib = this.options.goNextSibling; + this.options.goNextSibling = true; + this.childrenWalkers[ast.nodeType](ast, parent, this); + this.options.goNextSibling = svGoSib; + } else { + this.options.goChildren = true; + } + if(this.post) { + var postAst = this.post(preAst, parent, this); + if(postAst === undefined) { + postAst = preAst; + } + return postAst; + } else { + return preAst; + } + }; + return AstWalker; + })(); + var AstWalkerFactory = (function () { + function AstWalkerFactory() { + this.childrenWalkers = []; + this.initChildrenWalkers(); + } + AstWalkerFactory.prototype.walk = function (ast, pre, post, options, state) { + return this.getWalker(pre, post, options, state).walk(ast, null); + }; + AstWalkerFactory.prototype.getWalker = function (pre, post, options, state) { + return this.getSlowWalker(pre, post, options, state); + }; + AstWalkerFactory.prototype.getSlowWalker = function (pre, post, options, state) { + if(!options) { + options = new AstWalkOptions(); + } + return new AstWalker(this.childrenWalkers, pre, post, options, state); + }; + AstWalkerFactory.prototype.initChildrenWalkers = function () { + this.childrenWalkers[TypeScript.NodeType.None] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Empty] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.EmptyExpr] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.True] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.False] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.This] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Super] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.QString] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Regex] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Null] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.ArrayLit] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.ObjectLit] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Void] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Comma] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Pos] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Neg] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Delete] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Await] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.In] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Dot] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.From] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Is] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.InstOf] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Typeof] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.NumberLit] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Name] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.TypeRef] = ChildrenWalkers.walkTypeReferenceChildren; + this.childrenWalkers[TypeScript.NodeType.Index] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Call] = ChildrenWalkers.walkCallExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.New] = ChildrenWalkers.walkCallExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Asg] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgAdd] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgSub] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgDiv] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgMul] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgMod] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgAnd] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgXor] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgOr] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgLsh] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgRsh] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgRs2] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.ConditionalExpression] = ChildrenWalkers.walkTrinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.LogOr] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.LogAnd] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Or] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Xor] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.And] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Eq] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Ne] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Eqv] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.NEqv] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Lt] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Le] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Gt] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Ge] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Add] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Sub] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Mul] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Div] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Mod] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Lsh] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Rsh] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Rs2] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Not] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.LogNot] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.IncPre] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.DecPre] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.IncPost] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.DecPost] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.TypeAssertion] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.FuncDecl] = ChildrenWalkers.walkFuncDeclChildren; + this.childrenWalkers[TypeScript.NodeType.Member] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.VarDecl] = ChildrenWalkers.walkBoundDeclChildren; + this.childrenWalkers[TypeScript.NodeType.ArgDecl] = ChildrenWalkers.walkBoundDeclChildren; + this.childrenWalkers[TypeScript.NodeType.Return] = ChildrenWalkers.walkReturnStatementChildren; + this.childrenWalkers[TypeScript.NodeType.Break] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Continue] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Throw] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.For] = ChildrenWalkers.walkForStatementChildren; + this.childrenWalkers[TypeScript.NodeType.ForIn] = ChildrenWalkers.walkForInStatementChildren; + this.childrenWalkers[TypeScript.NodeType.If] = ChildrenWalkers.walkIfStatementChildren; + this.childrenWalkers[TypeScript.NodeType.While] = ChildrenWalkers.walkWhileStatementChildren; + this.childrenWalkers[TypeScript.NodeType.DoWhile] = ChildrenWalkers.walkDoWhileStatementChildren; + this.childrenWalkers[TypeScript.NodeType.Block] = ChildrenWalkers.walkBlockChildren; + this.childrenWalkers[TypeScript.NodeType.Case] = ChildrenWalkers.walkCaseStatementChildren; + this.childrenWalkers[TypeScript.NodeType.Switch] = ChildrenWalkers.walkSwitchStatementChildren; + this.childrenWalkers[TypeScript.NodeType.Try] = ChildrenWalkers.walkTryChildren; + this.childrenWalkers[TypeScript.NodeType.TryCatch] = ChildrenWalkers.walkTryCatchChildren; + this.childrenWalkers[TypeScript.NodeType.TryFinally] = ChildrenWalkers.walkTryFinallyChildren; + this.childrenWalkers[TypeScript.NodeType.Finally] = ChildrenWalkers.walkFinallyChildren; + this.childrenWalkers[TypeScript.NodeType.Catch] = ChildrenWalkers.walkCatchChildren; + this.childrenWalkers[TypeScript.NodeType.List] = ChildrenWalkers.walkListChildren; + this.childrenWalkers[TypeScript.NodeType.Script] = ChildrenWalkers.walkScriptChildren; + this.childrenWalkers[TypeScript.NodeType.ClassDeclaration] = ChildrenWalkers.walkClassDeclChildren; + this.childrenWalkers[TypeScript.NodeType.InterfaceDeclaration] = ChildrenWalkers.walkTypeDeclChildren; + this.childrenWalkers[TypeScript.NodeType.ModuleDeclaration] = ChildrenWalkers.walkModuleDeclChildren; + this.childrenWalkers[TypeScript.NodeType.ImportDeclaration] = ChildrenWalkers.walkImportDeclChildren; + this.childrenWalkers[TypeScript.NodeType.With] = ChildrenWalkers.walkWithStatementChildren; + this.childrenWalkers[TypeScript.NodeType.Label] = ChildrenWalkers.walkLabelChildren; + this.childrenWalkers[TypeScript.NodeType.LabeledStatement] = ChildrenWalkers.walkLabeledStatementChildren; + this.childrenWalkers[TypeScript.NodeType.EBStart] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.GotoEB] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.EndCode] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Error] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Comment] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Debugger] = ChildrenWalkers.walkNone; + for(var e in (TypeScript.NodeType)._map) { + if((this.childrenWalkers)[e] === undefined) { + throw new Error("initWalkers function is not up to date with enum content!"); + } + } + }; + return AstWalkerFactory; + })(); + TypeScript.AstWalkerFactory = AstWalkerFactory; + var globalAstWalkerFactory; + function getAstWalkerFactory() { + if(!globalAstWalkerFactory) { + globalAstWalkerFactory = new AstWalkerFactory(); + } + return globalAstWalkerFactory; + } + TypeScript.getAstWalkerFactory = getAstWalkerFactory; + var ChildrenWalkers; + (function (ChildrenWalkers) { + function walkNone(preAst, parent, walker) { + } + ChildrenWalkers.walkNone = walkNone; + function walkListChildren(preAst, parent, walker) { + var len = preAst.members.length; + if(walker.options.reverseSiblings) { + for(var i = len - 1; i >= 0; i--) { + if(walker.options.goNextSibling) { + preAst.members[i] = walker.walk(preAst.members[i], preAst); + } + } + } else { + for(var i = 0; i < len; i++) { + if(walker.options.goNextSibling) { + preAst.members[i] = walker.walk(preAst.members[i], preAst); + } + } + } + } + ChildrenWalkers.walkListChildren = walkListChildren; + function walkUnaryExpressionChildren(preAst, parent, walker) { + if(preAst.castTerm) { + preAst.castTerm = walker.walk(preAst.castTerm, preAst); + } + if(preAst.operand) { + preAst.operand = walker.walk(preAst.operand, preAst); + } + } + ChildrenWalkers.walkUnaryExpressionChildren = walkUnaryExpressionChildren; + function walkBinaryExpressionChildren(preAst, parent, walker) { + if(walker.options.reverseSiblings) { + if(preAst.operand2) { + preAst.operand2 = walker.walk(preAst.operand2, preAst); + } + if((preAst.operand1) && (walker.options.goNextSibling)) { + preAst.operand1 = walker.walk(preAst.operand1, preAst); + } + } else { + if(preAst.operand1) { + preAst.operand1 = walker.walk(preAst.operand1, preAst); + } + if((preAst.operand2) && (walker.options.goNextSibling)) { + preAst.operand2 = walker.walk(preAst.operand2, preAst); + } + } + } + ChildrenWalkers.walkBinaryExpressionChildren = walkBinaryExpressionChildren; + function walkTypeReferenceChildren(preAst, parent, walker) { + if(preAst.term) { + preAst.term = walker.walk(preAst.term, preAst); + } + } + ChildrenWalkers.walkTypeReferenceChildren = walkTypeReferenceChildren; + function walkCallExpressionChildren(preAst, parent, walker) { + if(!walker.options.reverseSiblings) { + preAst.target = walker.walk(preAst.target, preAst); + } + if(preAst.arguments && (walker.options.goNextSibling)) { + preAst.arguments = walker.walk(preAst.arguments, preAst); + } + if((walker.options.reverseSiblings) && (walker.options.goNextSibling)) { + preAst.target = walker.walk(preAst.target, preAst); + } + } + ChildrenWalkers.walkCallExpressionChildren = walkCallExpressionChildren; + function walkTrinaryExpressionChildren(preAst, parent, walker) { + if(preAst.operand1) { + preAst.operand1 = walker.walk(preAst.operand1, preAst); + } + if(preAst.operand2 && (walker.options.goNextSibling)) { + preAst.operand2 = walker.walk(preAst.operand2, preAst); + } + if(preAst.operand3 && (walker.options.goNextSibling)) { + preAst.operand3 = walker.walk(preAst.operand3, preAst); + } + } + ChildrenWalkers.walkTrinaryExpressionChildren = walkTrinaryExpressionChildren; + function walkFuncDeclChildren(preAst, parent, walker) { + if(preAst.name) { + preAst.name = walker.walk(preAst.name, preAst); + } + if(preAst.arguments && (preAst.arguments.members.length > 0) && (walker.options.goNextSibling)) { + preAst.arguments = walker.walk(preAst.arguments, preAst); + } + if(preAst.returnTypeAnnotation && (walker.options.goNextSibling)) { + preAst.returnTypeAnnotation = walker.walk(preAst.returnTypeAnnotation, preAst); + } + if(preAst.bod && (preAst.bod.members.length > 0) && (walker.options.goNextSibling)) { + preAst.bod = walker.walk(preAst.bod, preAst); + } + } + ChildrenWalkers.walkFuncDeclChildren = walkFuncDeclChildren; + function walkBoundDeclChildren(preAst, parent, walker) { + if(preAst.id) { + preAst.id = walker.walk(preAst.id, preAst); + } + if(preAst.init) { + preAst.init = walker.walk(preAst.init, preAst); + } + if((preAst.typeExpr) && (walker.options.goNextSibling)) { + preAst.typeExpr = walker.walk(preAst.typeExpr, preAst); + } + } + ChildrenWalkers.walkBoundDeclChildren = walkBoundDeclChildren; + function walkReturnStatementChildren(preAst, parent, walker) { + if(preAst.returnExpression) { + preAst.returnExpression = walker.walk(preAst.returnExpression, preAst); + } + } + ChildrenWalkers.walkReturnStatementChildren = walkReturnStatementChildren; + function walkForStatementChildren(preAst, parent, walker) { + if(preAst.init) { + preAst.init = walker.walk(preAst.init, preAst); + } + if(preAst.cond && walker.options.goNextSibling) { + preAst.cond = walker.walk(preAst.cond, preAst); + } + if(preAst.incr && walker.options.goNextSibling) { + preAst.incr = walker.walk(preAst.incr, preAst); + } + if(preAst.body && walker.options.goNextSibling) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkForStatementChildren = walkForStatementChildren; + function walkForInStatementChildren(preAst, parent, walker) { + preAst.lval = walker.walk(preAst.lval, preAst); + if(walker.options.goNextSibling) { + preAst.obj = walker.walk(preAst.obj, preAst); + } + if(preAst.body && (walker.options.goNextSibling)) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkForInStatementChildren = walkForInStatementChildren; + function walkIfStatementChildren(preAst, parent, walker) { + preAst.cond = walker.walk(preAst.cond, preAst); + if(preAst.thenBod && (walker.options.goNextSibling)) { + preAst.thenBod = walker.walk(preAst.thenBod, preAst); + } + if(preAst.elseBod && (walker.options.goNextSibling)) { + preAst.elseBod = walker.walk(preAst.elseBod, preAst); + } + } + ChildrenWalkers.walkIfStatementChildren = walkIfStatementChildren; + function walkWhileStatementChildren(preAst, parent, walker) { + preAst.cond = walker.walk(preAst.cond, preAst); + if(preAst.body && (walker.options.goNextSibling)) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkWhileStatementChildren = walkWhileStatementChildren; + function walkDoWhileStatementChildren(preAst, parent, walker) { + preAst.cond = walker.walk(preAst.cond, preAst); + if(preAst.body && (walker.options.goNextSibling)) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkDoWhileStatementChildren = walkDoWhileStatementChildren; + function walkBlockChildren(preAst, parent, walker) { + if(preAst.statements) { + preAst.statements = walker.walk(preAst.statements, preAst); + } + } + ChildrenWalkers.walkBlockChildren = walkBlockChildren; + function walkCaseStatementChildren(preAst, parent, walker) { + if(preAst.expr) { + preAst.expr = walker.walk(preAst.expr, preAst); + } + if(preAst.body && walker.options.goNextSibling) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkCaseStatementChildren = walkCaseStatementChildren; + function walkSwitchStatementChildren(preAst, parent, walker) { + if(preAst.val) { + preAst.val = walker.walk(preAst.val, preAst); + } + if((preAst.caseList) && walker.options.goNextSibling) { + preAst.caseList = walker.walk(preAst.caseList, preAst); + } + } + ChildrenWalkers.walkSwitchStatementChildren = walkSwitchStatementChildren; + function walkTryChildren(preAst, parent, walker) { + if(preAst.body) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkTryChildren = walkTryChildren; + function walkTryCatchChildren(preAst, parent, walker) { + if(preAst.tryNode) { + preAst.tryNode = walker.walk(preAst.tryNode, preAst); + } + if((preAst.catchNode) && walker.options.goNextSibling) { + preAst.catchNode = walker.walk(preAst.catchNode, preAst); + } + } + ChildrenWalkers.walkTryCatchChildren = walkTryCatchChildren; + function walkTryFinallyChildren(preAst, parent, walker) { + if(preAst.tryNode) { + preAst.tryNode = walker.walk(preAst.tryNode, preAst); + } + if(preAst.finallyNode && walker.options.goNextSibling) { + preAst.finallyNode = walker.walk(preAst.finallyNode, preAst); + } + } + ChildrenWalkers.walkTryFinallyChildren = walkTryFinallyChildren; + function walkFinallyChildren(preAst, parent, walker) { + if(preAst.body) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkFinallyChildren = walkFinallyChildren; + function walkCatchChildren(preAst, parent, walker) { + if(preAst.param) { + preAst.param = walker.walk(preAst.param, preAst); + } + if((preAst.body) && walker.options.goNextSibling) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkCatchChildren = walkCatchChildren; + function walkRecordChildren(preAst, parent, walker) { + preAst.name = walker.walk(preAst.name, preAst); + if(walker.options.goNextSibling && preAst.members) { + preAst.members = walker.walk(preAst.members, preAst); + } + } + ChildrenWalkers.walkRecordChildren = walkRecordChildren; + function walkNamedTypeChildren(preAst, parent, walker) { + walkRecordChildren(preAst, parent, walker); + } + ChildrenWalkers.walkNamedTypeChildren = walkNamedTypeChildren; + function walkClassDeclChildren(preAst, parent, walker) { + walkNamedTypeChildren(preAst, parent, walker); + if(walker.options.goNextSibling && preAst.extendsList) { + preAst.extendsList = walker.walk(preAst.extendsList, preAst); + } + if(walker.options.goNextSibling && preAst.implementsList) { + preAst.implementsList = walker.walk(preAst.implementsList, preAst); + } + } + ChildrenWalkers.walkClassDeclChildren = walkClassDeclChildren; + function walkScriptChildren(preAst, parent, walker) { + if(preAst.bod) { + preAst.bod = walker.walk(preAst.bod, preAst); + } + } + ChildrenWalkers.walkScriptChildren = walkScriptChildren; + function walkTypeDeclChildren(preAst, parent, walker) { + walkNamedTypeChildren(preAst, parent, walker); + if(walker.options.goNextSibling && preAst.extendsList) { + preAst.extendsList = walker.walk(preAst.extendsList, preAst); + } + if(walker.options.goNextSibling && preAst.implementsList) { + preAst.implementsList = walker.walk(preAst.implementsList, preAst); + } + } + ChildrenWalkers.walkTypeDeclChildren = walkTypeDeclChildren; + function walkModuleDeclChildren(preAst, parent, walker) { + walkRecordChildren(preAst, parent, walker); + } + ChildrenWalkers.walkModuleDeclChildren = walkModuleDeclChildren; + function walkImportDeclChildren(preAst, parent, walker) { + if(preAst.id) { + preAst.id = walker.walk(preAst.id, preAst); + } + if(preAst.alias) { + preAst.alias = walker.walk(preAst.alias, preAst); + } + } + ChildrenWalkers.walkImportDeclChildren = walkImportDeclChildren; + function walkWithStatementChildren(preAst, parent, walker) { + if(preAst.expr) { + preAst.expr = walker.walk(preAst.expr, preAst); + } + if(preAst.body && walker.options.goNextSibling) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkWithStatementChildren = walkWithStatementChildren; + function walkLabelChildren(preAst, parent, walker) { + } + ChildrenWalkers.walkLabelChildren = walkLabelChildren; + function walkLabeledStatementChildren(preAst, parent, walker) { + preAst.labels = walker.walk(preAst.labels, preAst); + if(walker.options.goNextSibling) { + preAst.stmt = walker.walk(preAst.stmt, preAst); + } + } + ChildrenWalkers.walkLabeledStatementChildren = walkLabeledStatementChildren; + })(ChildrenWalkers || (ChildrenWalkers = {})); +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (AstWalkerWithDetailCallback) { + function walk(script, callback) { + var pre = function (cur, parent) { + walker.options.goChildren = AstWalkerCallback(true, cur, callback); + return cur; + }; + var post = function (cur, parent) { + AstWalkerCallback(false, cur, callback); + return cur; + }; + var walker = TypeScript.getAstWalkerFactory().getWalker(pre, post); + walker.walk(script, null); + } + AstWalkerWithDetailCallback.walk = walk; + function AstWalkerCallback(pre, ast, callback) { + var nodeType = ast.nodeType; + var callbackString = (TypeScript.NodeType)._map[nodeType] + "Callback"; + if(callback[callbackString]) { + return callback[callbackString](pre, ast); + } + if(callback.DefaultCallback) { + return callback.DefaultCallback(pre, ast); + } + return true; + } + })(TypeScript.AstWalkerWithDetailCallback || (TypeScript.AstWalkerWithDetailCallback = {})); + var AstWalkerWithDetailCallback = TypeScript.AstWalkerWithDetailCallback; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + function lastOf(items) { + return (items === null || items.length === 0) ? null : items[items.length - 1]; + } + TypeScript.lastOf = lastOf; + function max(a, b) { + return a >= b ? a : b; + } + TypeScript.max = max; + function min(a, b) { + return a <= b ? a : b; + } + TypeScript.min = min; + var AstPath = (function () { + function AstPath() { + this.asts = []; + this.top = -1; + } + AstPath.reverseIndexOf = function reverseIndexOf(items, index) { + return (items === null || items.length <= index) ? null : items[items.length - index - 1]; + } + AstPath.prototype.clone = function () { + var clone = new AstPath(); + clone.asts = this.asts.map(function (value) { + return value; + }); + clone.top = this.top; + return clone; + }; + AstPath.prototype.pop = function () { + var head = this.ast(); + this.up(); + while(this.asts.length > this.count()) { + this.asts.pop(); + } + return head; + }; + AstPath.prototype.push = function (ast) { + while(this.asts.length > this.count()) { + this.asts.pop(); + } + this.top = this.asts.length; + this.asts.push(ast); + }; + AstPath.prototype.up = function () { + if(this.top <= -1) { + throw new Error("Invalid call to 'up'"); + } + this.top--; + }; + AstPath.prototype.down = function () { + if(this.top == this.ast.length - 1) { + throw new Error("Invalid call to 'down'"); + } + this.top++; + }; + AstPath.prototype.nodeType = function () { + if(this.ast() == null) { + return TypeScript.NodeType.None; + } + return this.ast().nodeType; + }; + AstPath.prototype.ast = function () { + return AstPath.reverseIndexOf(this.asts, this.asts.length - (this.top + 1)); + }; + AstPath.prototype.parent = function () { + return AstPath.reverseIndexOf(this.asts, this.asts.length - this.top); + }; + AstPath.prototype.count = function () { + return this.top + 1; + }; + AstPath.prototype.get = function (index) { + return this.asts[index]; + }; + AstPath.prototype.isNameOfClass = function () { + if(this.ast() === null || this.parent() === null) { + return false; + } + return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.ClassDeclaration) && ((this.parent()).name === this.ast()); + }; + AstPath.prototype.isNameOfInterface = function () { + if(this.ast() === null || this.parent() === null) { + return false; + } + return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.InterfaceDeclaration) && ((this.parent()).name === this.ast()); + }; + AstPath.prototype.isNameOfArgument = function () { + if(this.ast() === null || this.parent() === null) { + return false; + } + return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.ArgDecl) && ((this.parent()).id === this.ast()); + }; + AstPath.prototype.isNameOfVariable = function () { + if(this.ast() === null || this.parent() === null) { + return false; + } + return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.VarDecl) && ((this.parent()).id === this.ast()); + }; + AstPath.prototype.isNameOfModule = function () { + if(this.ast() === null || this.parent() === null) { + return false; + } + return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.ModuleDeclaration) && ((this.parent()).name === this.ast()); + }; + AstPath.prototype.isNameOfFunction = function () { + if(this.ast() === null || this.parent() === null) { + return false; + } + return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.FuncDecl) && ((this.parent()).name === this.ast()); + }; + AstPath.prototype.isChildOfScript = function () { + var ast = lastOf(this.asts); + return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.Script; + }; + AstPath.prototype.isChildOfModule = function () { + var ast = lastOf(this.asts); + return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.ModuleDeclaration; + }; + AstPath.prototype.isChildOfClass = function () { + var ast = lastOf(this.asts); + return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.ClassDeclaration; + }; + AstPath.prototype.isArgumentOfClassConstructor = function () { + var ast = lastOf(this.asts); + return this.count() >= 5 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.FuncDecl && this.asts[this.top - 3].nodeType === TypeScript.NodeType.List && this.asts[this.top - 4].nodeType === TypeScript.NodeType.ClassDeclaration && ((this.asts[this.top - 2]).isConstructor) && ((this.asts[this.top - 2]).arguments === this.asts[this.top - 1]) && ((this.asts[this.top - 4]).constructorDecl === this.asts[this.top - 2]); + }; + AstPath.prototype.isChildOfInterface = function () { + var ast = lastOf(this.asts); + return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.InterfaceDeclaration; + }; + AstPath.prototype.isTopLevelImplicitModule = function () { + return this.count() >= 1 && this.asts[this.top].nodeType === TypeScript.NodeType.ModuleDeclaration && TypeScript.hasFlag((this.asts[this.top]).modFlags, TypeScript.ModuleFlags.IsWholeFile); + }; + AstPath.prototype.isBodyOfTopLevelImplicitModule = function () { + return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ModuleDeclaration && (this.asts[this.top - 1]).members == this.asts[this.top - 0] && TypeScript.hasFlag((this.asts[this.top - 1]).modFlags, TypeScript.ModuleFlags.IsWholeFile); + }; + AstPath.prototype.isBodyOfScript = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Script && (this.asts[this.top - 1]).bod == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfSwitch = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Switch && (this.asts[this.top - 1]).caseList == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfModule = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ModuleDeclaration && (this.asts[this.top - 1]).members == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfClass = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ClassDeclaration && (this.asts[this.top - 1]).members == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfFunction = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.FuncDecl && (this.asts[this.top - 1]).bod == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfInterface = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.InterfaceDeclaration && (this.asts[this.top - 1]).members == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfBlock = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Block && (this.asts[this.top - 1]).statements == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfFor = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.For && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfCase = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Case && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfTry = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Try && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfCatch = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Catch && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfDoWhile = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.DoWhile && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfWhile = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.While && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfForIn = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ForIn && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfWith = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.With && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfFinally = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Finally && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + }; + AstPath.prototype.isCaseOfSwitch = function () { + return this.count() >= 3 && this.asts[this.top - 2].nodeType === TypeScript.NodeType.Switch && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 2]).caseList == this.asts[this.top - 1]; + }; + AstPath.prototype.isDefaultCaseOfSwitch = function () { + return this.count() >= 3 && this.asts[this.top - 2].nodeType === TypeScript.NodeType.Switch && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 2]).caseList == this.asts[this.top - 1] && (this.asts[this.top - 2]).defaultCase == this.asts[this.top - 0]; + }; + AstPath.prototype.isListOfObjectLit = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 1]).operand == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfObjectLit = function () { + return this.isListOfObjectLit(); + }; + AstPath.prototype.isEmptyListOfObjectLit = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 1]).operand == this.asts[this.top - 0] && (this.asts[this.top - 0]).members.length == 0; + }; + AstPath.prototype.isMemberOfObjectLit = function () { + return this.count() >= 3 && this.asts[this.top - 2].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 0].nodeType === TypeScript.NodeType.Member && (this.asts[this.top - 2]).operand == this.asts[this.top - 1]; + }; + AstPath.prototype.isNameOfMemberOfObjectLit = function () { + return this.count() >= 4 && this.asts[this.top - 3].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 2].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Member && this.asts[this.top - 0].nodeType === TypeScript.NodeType.Name && (this.asts[this.top - 3]).operand == this.asts[this.top - 2]; + }; + AstPath.prototype.isListOfArrayLit = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ArrayLit && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 1]).operand == this.asts[this.top - 0]; + }; + AstPath.prototype.isTargetOfMember = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Member && (this.asts[this.top - 1]).operand1 === this.asts[this.top - 0]; + }; + AstPath.prototype.isMemberOfMember = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Member && (this.asts[this.top - 1]).operand2 === this.asts[this.top - 0]; + }; + AstPath.prototype.isItemOfList = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List; + }; + AstPath.prototype.isThenOfIf = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.If && (this.asts[this.top - 1]).thenBod == this.asts[this.top - 0]; + }; + AstPath.prototype.isElseOfIf = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.If && (this.asts[this.top - 1]).elseBod == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfDefaultCase = function () { + return this.isBodyOfCase(); + }; + AstPath.prototype.isSingleStatementList = function () { + return this.count() >= 1 && this.asts[this.top].nodeType === TypeScript.NodeType.List && (this.asts[this.top]).members.length === 1; + }; + AstPath.prototype.isArgumentListOfFunction = function () { + return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.FuncDecl && (this.asts[this.top - 1]).arguments === this.asts[this.top - 0]; + }; + AstPath.prototype.isArgumentOfFunction = function () { + return this.count() >= 3 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.FuncDecl && (this.asts[this.top - 2]).arguments === this.asts[this.top - 1]; + }; + AstPath.prototype.isArgumentListOfCall = function () { + return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Call && (this.asts[this.top - 1]).arguments === this.asts[this.top - 0]; + }; + AstPath.prototype.isArgumentListOfNew = function () { + return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.New && (this.asts[this.top - 1]).arguments === this.asts[this.top - 0]; + }; + AstPath.prototype.isSynthesizedBlock = function () { + return this.count() >= 1 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.Block && (this.asts[this.top - 0]).isStatementBlock === false; + }; + return AstPath; + })(); + TypeScript.AstPath = AstPath; + function isValidAstNode(ast) { + if(ast === null) { + return false; + } + if(ast.minChar === -1 || ast.limChar === -1) { + return false; + } + return true; + } + TypeScript.isValidAstNode = isValidAstNode; + var AstPathContext = (function () { + function AstPathContext() { + this.path = new TypeScript.AstPath(); + } + return AstPathContext; + })(); + TypeScript.AstPathContext = AstPathContext; + (function (GetAstPathOptions) { + GetAstPathOptions._map = []; + GetAstPathOptions.Default = 0; + GetAstPathOptions.EdgeInclusive = 1; + GetAstPathOptions.DontPruneSearchBasedOnPosition = 1 << 1; + })(TypeScript.GetAstPathOptions || (TypeScript.GetAstPathOptions = {})); + var GetAstPathOptions = TypeScript.GetAstPathOptions; + function getAstPathToPosition(script, pos, options) { + if (typeof options === "undefined") { options = GetAstPathOptions.Default; } + var lookInComments = function (comments) { + if(comments && comments.length > 0) { + for(var i = 0; i < comments.length; i++) { + var minChar = comments[i].minChar; + var limChar = comments[i].limChar; + if(!comments[i].isBlockComment) { + limChar++; + } + if(pos >= minChar && pos < limChar) { + ctx.path.push(comments[i]); + } + } + } + }; + var pre = function (cur, parent, walker) { + if(isValidAstNode(cur)) { + var inclusive = TypeScript.hasFlag(options, GetAstPathOptions.EdgeInclusive) || cur.nodeType === TypeScript.NodeType.Name || pos === script.limChar; + var minChar = cur.minChar; + var limChar = cur.limChar + (inclusive ? 1 : 0); + if(pos >= minChar && pos < limChar) { + var previous = ctx.path.ast(); + if(previous == null || (cur.minChar >= previous.minChar && cur.limChar <= previous.limChar)) { + ctx.path.push(cur); + } else { + } + } + if(pos < limChar) { + lookInComments(cur.preComments); + } + if(pos >= minChar) { + lookInComments(cur.postComments); + } + if(!TypeScript.hasFlag(options, GetAstPathOptions.DontPruneSearchBasedOnPosition)) { + walker.options.goChildren = (minChar <= pos && pos <= limChar); + } + } + return cur; + }; + var ctx = new AstPathContext(); + TypeScript.getAstWalkerFactory().walk(script, pre, null, null, ctx); + return ctx.path; + } + TypeScript.getAstPathToPosition = getAstPathToPosition; + function getTokenizationOffset(script, position) { + var bestOffset = 0; + var pre = function (cur, parent, walker) { + if(TypeScript.isValidAstNode(cur)) { + if(cur.minChar <= position) { + bestOffset = max(bestOffset, cur.minChar); + } + if(cur.minChar > position || cur.limChar < bestOffset) { + walker.options.goChildren = false; + } + } + return cur; + }; + TypeScript.getAstWalkerFactory().walk(script, pre); + return bestOffset; + } + TypeScript.getTokenizationOffset = getTokenizationOffset; + function walkAST(ast, callback) { + var pre = function (cur, parent, walker) { + var path = walker.state; + path.push(cur); + callback(path, walker); + return cur; + }; + var post = function (cur, parent, walker) { + var path = walker.state; + path.pop(); + return cur; + }; + var path = new AstPath(); + TypeScript.getAstWalkerFactory().walk(ast, pre, post, null, path); + } + TypeScript.walkAST = walkAST; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var AstLogger = (function () { + function AstLogger(logger) { + this.logger = logger; + } + AstLogger.prototype.logScript = function (script) { + var _this = this; + this.logLinemap(script.locationInfo.lineMap); + var stack = []; + var pre = function (cur, parent) { + stack.push(cur); + var indent = (stack.length - 1) * 2; + _this.logComments(script, cur.preComments, indent); + _this.logNode(script, cur, indent); + _this.logComments(script, cur.postComments, indent); + return cur; + }; + var post = function (cur, parent) { + stack.pop(); + return cur; + }; + TypeScript.getAstWalkerFactory().walk(script, pre, post); + }; + AstLogger.prototype.logNode = function (script, cur, indent) { + var msg = this.addPadding("", indent, "| ", true); + msg = msg.concat("+ " + cur.treeViewLabel()); + msg = this.addPadding(msg, 70, " ", false); + msg = msg + this.addLineColumn(script, cur.minChar); + msg = this.addPadding(msg, 80, " ", false); + msg = msg + "=> "; + msg = msg + this.addLineColumn(script, cur.limChar); + msg = this.addPadding(msg, 102, " ", false); + msg = msg.concat("[" + this.addPadding(cur.minChar.toString(), 1, " ", true) + ", " + this.addPadding(cur.limChar.toString(), 1, " ", true) + "]"); + msg = this.addPadding(msg, 115, " ", false); + msg = msg.concat("sym=" + (cur).sym); + msg = this.addPadding(msg, 135, " ", false); + msg = msg.concat("type=" + (cur.type === null ? "null" : cur.type.getTypeName())); + this.logger.log(msg); + }; + AstLogger.prototype.logComments = function (script, comments, indent) { + if(comments == null) { + return; + } + for(var i = 0; i < comments.length; i++) { + this.logNode(script, comments[i], indent); + } + }; + AstLogger.prototype.logLinemap = function (linemap) { + var result = "["; + for(var i = 0; i < linemap.length; i++) { + if(i > 0) { + result += ","; + } + result += linemap[i]; + } + result += "]"; + this.logger.log("linemap: " + result); + }; + AstLogger.prototype.addPadding = function (s, targetLength, paddingString, leftPadding) { + var result = (leftPadding ? "" : s); + for(var i = s.length; i < targetLength; i++) { + result = result + paddingString; + } + result = result + (leftPadding ? s : ""); + return result; + }; + AstLogger.prototype.addLineColumn = function (script, position) { + var lineInfo = { + line: -1, + col: -1 + }; + TypeScript.getSourceLineColFromMap(lineInfo, position, script.locationInfo.lineMap); + if(lineInfo.col !== -1) { + lineInfo.col++; + } + return "(" + lineInfo.line + ", " + lineInfo.col + ")"; + }; + return AstLogger; + })(); + TypeScript.AstLogger = AstLogger; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Binder = (function () { + function Binder(checker) { + this.checker = checker; + } + Binder.prototype.resolveBaseTypeLinks = function (typeLinks, scope) { + var extendsList = null; + if(typeLinks) { + extendsList = new Array(); + for(var i = 0, len = typeLinks.length; i < len; i++) { + extendsList[i] = this.checker.resolveBaseTypeLink(typeLinks[i], scope); + } + } + return extendsList; + }; + Binder.prototype.resolveBases = function (scope, type) { + type.extendsList = this.resolveBaseTypeLinks(type.extendsTypeLinks, scope); + var i = 0, len = type.extendsList.length; + var derivedIsClass = type.isClassInstance(); + for(; i < len; i++) { + var baseIsClass = type.extendsList[i].isClassInstance(); + if(type.extendsList[i] != this.checker.anyType) { + var baseRef = type.extendsTypeLinks[i].ast; + if(derivedIsClass) { + if(!baseIsClass) { + this.checker.errorReporter.simpleError(baseRef, "A class may only extend other classes, " + type.extendsList[i].symbol.fullName() + " is not a class."); + } + } else { + if(baseIsClass) { + this.checker.errorReporter.simpleError(baseRef, "An interface may only extend other interfaces, " + type.extendsList[i].symbol.fullName() + " is a class."); + } + } + } + } + type.implementsList = this.resolveBaseTypeLinks(type.implementsTypeLinks, scope); + if(type.implementsList) { + for(i = 0 , len = type.implementsList.length; i < len; i++) { + var iface = type.implementsList[i]; + var baseRef = type.implementsTypeLinks[i].ast; + if(iface.isClassInstance()) { + if(derivedIsClass) { + this.checker.errorReporter.simpleError(baseRef, "A class may only implement an interface; " + iface.symbol.fullName() + " is a class."); + } + } + } + } + }; + Binder.prototype.resolveSignatureGroup = function (signatureGroup, scope, instanceType) { + var supplyVar = !(signatureGroup.hasImplementation); + for(var i = 0, len = signatureGroup.signatures.length; i < len; i++) { + var signature = signatureGroup.signatures[i]; + if(instanceType) { + signature.returnType.type = instanceType; + } else { + this.checker.resolveTypeLink(scope, signature.returnType, supplyVar); + } + var paramLen = signature.parameters.length; + for(var j = 0; j < paramLen; j++) { + this.bindSymbol(scope, signature.parameters[j]); + } + if(signature.hasVariableArgList) { + var lastParam = signature.parameters[paramLen - 1]; + lastParam.argsOffset = paramLen - 1; + if(!lastParam.getType().isArray()) { + this.checker.errorReporter.simpleErrorFromSym(lastParam, "... parameter must have array type"); + lastParam.parameter.typeLink.type = this.checker.makeArrayType(lastParam.parameter.typeLink.type); + } + } + } + }; + Binder.prototype.bindType = function (scope, type, instanceType) { + if(instanceType) { + this.bindType(scope, instanceType, null); + } + if(type.hasMembers()) { + var members = type.members; + var ambientMembers = type.ambientMembers; + var typeMembers = type.getAllEnclosedTypes(); + var ambientTypeMembers = type.getAllAmbientEnclosedTypes(); + var memberScope = new TypeScript.SymbolTableScope(members, ambientMembers, typeMembers, ambientTypeMembers, type.symbol); + var agg = new TypeScript.SymbolAggregateScope(type.symbol); + var prevCurrentModDecl = this.checker.currentModDecl; + var prevBindStatus = this.checker.inBind; + agg.addParentScope(memberScope); + agg.addParentScope(scope); + if(type.isModuleType()) { + this.checker.currentModDecl = type.symbol.declAST; + this.checker.inBind = true; + } + if(members) { + this.bind(agg, type.members.allMembers); + } + if(typeMembers) { + this.bind(agg, typeMembers.allMembers); + } + if(ambientMembers) { + this.bind(agg, ambientMembers.allMembers); + } + if(ambientTypeMembers) { + this.bind(agg, ambientTypeMembers.allMembers); + } + this.checker.currentModDecl = prevCurrentModDecl; + this.checker.inBind = prevBindStatus; + } + if(type.extendsTypeLinks) { + this.resolveBases(scope, type); + } + if(type.construct) { + this.resolveSignatureGroup(type.construct, scope, instanceType); + } + if(type.call) { + this.resolveSignatureGroup(type.call, scope, null); + } + if(type.index) { + this.resolveSignatureGroup(type.index, scope, null); + } + if(type.elementType) { + this.bindType(scope, type.elementType, null); + } + }; + Binder.prototype.bindSymbol = function (scope, symbol) { + if(!symbol.bound) { + var prevLocationInfo = this.checker.locationInfo; + if((this.checker.units) && (symbol.unitIndex >= 0) && (symbol.unitIndex < this.checker.units.length)) { + this.checker.locationInfo = this.checker.units[symbol.unitIndex]; + } + switch(symbol.kind()) { + case TypeScript.SymbolKind.Type: { + if(symbol.flags & TypeScript.SymbolFlags.Bound) { + break; + } + var typeSymbol = symbol; + typeSymbol.flags |= TypeScript.SymbolFlags.Bound; + if(typeSymbol.aliasLink && !typeSymbol.type && typeSymbol.aliasLink.alias.nodeType == TypeScript.NodeType.Name) { + var modPath = (typeSymbol.aliasLink.alias).text; + var modSym = this.checker.findSymbolForDynamicModule(modPath, this.checker.locationInfo.filename, function (id) { + return scope.find(id, false, true); + }); + if(modSym) { + typeSymbol.type = modSym.getType(); + } + } + if(typeSymbol.type && typeSymbol.type != this.checker.gloModType) { + this.bindType(scope, typeSymbol.type, typeSymbol.instanceType); + if(typeSymbol.type.isModuleType()) { + for(var i = 0; i < typeSymbol.expansions.length; i++) { + this.bindType(scope, typeSymbol.expansions[i], typeSymbol.instanceType); + } + } + } + break; + + } + case TypeScript.SymbolKind.Field: { + this.checker.resolveTypeLink(scope, (symbol).field.typeLink, false); + break; + + } + case TypeScript.SymbolKind.Parameter: { + this.checker.resolveTypeLink(scope, (symbol).parameter.typeLink, true); + break; + + } + } + this.checker.locationInfo = prevLocationInfo; + } + symbol.bound = true; + }; + Binder.prototype.bind = function (scope, table) { + table.map(function (key, sym, binder) { + binder.bindSymbol(scope, sym); + }, this); + }; + return Binder; + })(); + TypeScript.Binder = Binder; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Base64Format = (function () { + function Base64Format() { } + Base64Format.encodedValues = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + Base64Format.encode = function encode(inValue) { + if(inValue < 64) { + return Base64Format.encodedValues.charAt(inValue); + } + throw TypeError(inValue + ": not a 64 based value"); + } + Base64Format.decodeChar = function decodeChar(inChar) { + if(inChar.length === 1) { + return Base64Format.encodedValues.indexOf(inChar); + } else { + throw TypeError('"' + inChar + '" must have length 1'); + } + } + return Base64Format; + })(); + var Base64VLQFormat = (function () { + function Base64VLQFormat() { } + Base64VLQFormat.encode = function encode(inValue) { + if(inValue < 0) { + inValue = ((-inValue) << 1) + 1; + } else { + inValue = inValue << 1; + } + var encodedStr = ""; + do { + var currentDigit = inValue & 31; + inValue = inValue >> 5; + if(inValue > 0) { + currentDigit = currentDigit | 32; + } + encodedStr = encodedStr + Base64Format.encode(currentDigit); + }while(inValue > 0) + return encodedStr; + } + Base64VLQFormat.decode = function decode(inString) { + var result = 0; + var negative = false; + var shift = 0; + for(var i = 0; i < inString.length; i++) { + var byte = Base64Format.decodeChar(inString[i]); + if(i === 0) { + if((byte & 1) === 1) { + negative = true; + } + result = (byte >> 1) & 15; + } else { + result = result | ((byte & 31) << shift); + } + shift += (i == 0) ? 4 : 5; + if((byte & 32) === 32) { + } else { + return { + value: negative ? -(result) : result, + rest: inString.substr(i + 1) + }; + } + } + throw new Error('Base64 value "' + inString + '" finished with a continuation bit'); + } + return Base64VLQFormat; + })(); + TypeScript.Base64VLQFormat = Base64VLQFormat; +})(TypeScript || (TypeScript = {})); +var JSON2 = { +}; +((function () { + 'use strict'; + function f(n) { + return n < 10 ? '0' + n : n; + } + if(typeof Date.prototype.toJSON !== 'function') { + Date.prototype.toJSON = function (key) { + return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; + }; + var strProto = String.prototype; + var numProto = Number.prototype; + numProto.JSON = strProto.JSON = (Boolean).prototype.toJSON = function (key) { + return this.valueOf(); + }; + } + var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { +'\b': '\\b', +'\t': '\\t', +'\n': '\\n', +'\f': '\\f', +'\r': '\\r', +'"': '\\"', +'\\': '\\\\' }, rep; + function quote(string) { + escapable.lastIndex = 0; + return escapable.test(string) ? '"' + string.replace(escapable, function (a) { + var c = meta[a]; + return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); + }) + '"' : '"' + string + '"'; + } + function str(key, holder) { + var i, k = null, v, length, mind = gap, partial, value = holder[key]; + if(value && typeof value === 'object' && typeof value.toJSON === 'function') { + value = value.toJSON(key); + } + if(typeof rep === 'function') { + value = rep.call(holder, key, value); + } + switch(typeof value) { + case 'string': { + return quote(value); + + } + case 'number': { + return isFinite(value) ? String(value) : 'null'; + + } + case 'boolean': + case 'null': { + return String(value); + + } + case 'object': { + if(!value) { + return 'null'; + } + gap += indent; + partial = []; + if(Object.prototype.toString.apply(value, []) === '[object Array]') { + length = value.length; + for(i = 0; i < length; i += 1) { + partial[i] = str(i, value) || 'null'; + } + v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; + gap = mind; + return v; + } + if(rep && typeof rep === 'object') { + length = rep.length; + for(i = 0; i < length; i += 1) { + if(typeof rep[i] === 'string') { + k = rep[i]; + v = str(k, value); + if(v) { + partial.push(quote(k) + (gap ? ': ' : ':') + v); + } + } + } + } else { + for(k in value) { + if(Object.prototype.hasOwnProperty.call(value, k)) { + v = str(k, value); + if(v) { + partial.push(quote(k) + (gap ? ': ' : ':') + v); + } + } + } + } + v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; + gap = mind; + return v; + + } + } + } + if(typeof JSON2.stringify !== 'function') { + JSON2.stringify = function (value, replacer, space) { + var i; + gap = ''; + indent = ''; + if(typeof space === 'number') { + for(i = 0; i < space; i += 1) { + indent += ' '; + } + } else { + if(typeof space === 'string') { + indent = space; + } + } + rep = replacer; + if(replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { + throw new Error('JSON.stringify'); + } + return str('', { + '': value + }); + }; + } + if(typeof JSON2.parse !== 'function') { + JSON2.parse = function (text, reviver) { + var j; + function walk(holder, key) { + var k = null, v, value = holder[key]; + if(value && typeof value === 'object') { + for(k in value) { + if(Object.prototype.hasOwnProperty.call(value, k)) { + v = walk(value, k); + if(v !== undefined) { + value[k] = v; + } else { + delete value[k]; + } + } + } + } + return reviver.call(holder, key, value); + } + text = String(text); + cx.lastIndex = 0; + if(cx.test(text)) { + text = text.replace(cx, function (a) { + return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); + }); + } + if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { + j = eval('(' + text + ')'); + return typeof reviver === 'function' ? walk({ + '': j + }, '') : j; + } + throw new SyntaxError('JSON.parse'); + }; + } +})()); +var TypeScript; +(function (TypeScript) { + var SourceMapPosition = (function () { + function SourceMapPosition() { } + return SourceMapPosition; + })(); + TypeScript.SourceMapPosition = SourceMapPosition; + var SourceMapping = (function () { + function SourceMapping() { + this.start = new SourceMapPosition(); + this.end = new SourceMapPosition(); + this.nameIndex = -1; + this.childMappings = []; + } + return SourceMapping; + })(); + TypeScript.SourceMapping = SourceMapping; + var SourceMapper = (function () { + function SourceMapper(tsFileName, jsFileName, jsFile, sourceMapOut, errorReporter) { + this.jsFile = jsFile; + this.sourceMapOut = sourceMapOut; + this.errorReporter = errorReporter; + this.sourceMappings = []; + this.currentMappings = []; + this.names = []; + this.currentNameIndex = []; + this.currentMappings.push(this.sourceMappings); + jsFileName = TypeScript.switchToForwardSlashes(jsFileName); + this.jsFileName = TypeScript.getPrettyName(jsFileName, false, true); + var removalIndex = jsFileName.lastIndexOf(this.jsFileName); + var fixedPath = jsFileName.substring(0, removalIndex); + this.tsFileName = TypeScript.getRelativePathToFixedPath(fixedPath, tsFileName); + } + SourceMapper.MapFileExtension = ".map"; + SourceMapper.EmitSourceMapping = function EmitSourceMapping(allSourceMappers) { + var sourceMapper = allSourceMappers[0]; + sourceMapper.jsFile.WriteLine("//@ sourceMappingURL=" + sourceMapper.jsFileName + SourceMapper.MapFileExtension); + var sourceMapOut = sourceMapper.sourceMapOut; + var mappingsString = ""; + var tsFiles = []; + var prevEmittedColumn = 0; + var prevEmittedLine = 0; + var prevSourceColumn = 0; + var prevSourceLine = 0; + var prevSourceIndex = 0; + var prevNameIndex = 0; + var namesList = []; + var namesCount = 0; + var emitComma = false; + var recordedPosition = null; + for(var sourceMapperIndex = 0; sourceMapperIndex < allSourceMappers.length; sourceMapperIndex++) { + sourceMapper = allSourceMappers[sourceMapperIndex]; + var currentSourceIndex = tsFiles.length; + tsFiles.push(sourceMapper.tsFileName); + if(sourceMapper.names.length > 0) { + namesList.push.apply(namesList, sourceMapper.names); + } + var recordSourceMapping = function (mappedPosition, nameIndex) { + if(recordedPosition != null && recordedPosition.emittedColumn == mappedPosition.emittedColumn && recordedPosition.emittedLine == mappedPosition.emittedLine) { + return; + } + if(prevEmittedLine !== mappedPosition.emittedLine) { + while(prevEmittedLine < mappedPosition.emittedLine) { + prevEmittedColumn = 0; + mappingsString = mappingsString + ";"; + prevEmittedLine++; + } + emitComma = false; + } else { + if(emitComma) { + mappingsString = mappingsString + ","; + } + } + mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(mappedPosition.emittedColumn - prevEmittedColumn); + prevEmittedColumn = mappedPosition.emittedColumn; + mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(currentSourceIndex - prevSourceIndex); + prevSourceIndex = currentSourceIndex; + mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(mappedPosition.sourceLine - 1 - prevSourceLine); + prevSourceLine = mappedPosition.sourceLine - 1; + mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(mappedPosition.sourceColumn - prevSourceColumn); + prevSourceColumn = mappedPosition.sourceColumn; + if(nameIndex >= 0) { + mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(namesCount + nameIndex - prevNameIndex); + prevNameIndex = namesCount + nameIndex; + } + emitComma = true; + recordedPosition = mappedPosition; + }; + var recordSourceMappingSiblings = function (sourceMappings) { + for(var i = 0; i < sourceMappings.length; i++) { + var sourceMapping = sourceMappings[i]; + recordSourceMapping(sourceMapping.start, sourceMapping.nameIndex); + recordSourceMappingSiblings(sourceMapping.childMappings); + recordSourceMapping(sourceMapping.end, sourceMapping.nameIndex); + } + }; + recordSourceMappingSiblings(sourceMapper.sourceMappings, -1); + namesCount = namesCount + sourceMapper.names.length; + } + if(mappingsString != "") { + sourceMapOut.Write(JSON2.stringify({ + version: 3, + file: sourceMapper.jsFileName, + sources: tsFiles, + names: namesList, + mappings: mappingsString + })); + } + try { + sourceMapOut.Close(); + } catch (ex) { + sourceMapper.errorReporter.emitterError(null, ex.message); + } + } + return SourceMapper; + })(); + TypeScript.SourceMapper = SourceMapper; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (EmitContainer) { + EmitContainer._map = []; + EmitContainer._map[0] = "Prog"; + EmitContainer.Prog = 0; + EmitContainer._map[1] = "Module"; + EmitContainer.Module = 1; + EmitContainer._map[2] = "DynamicModule"; + EmitContainer.DynamicModule = 2; + EmitContainer._map[3] = "Class"; + EmitContainer.Class = 3; + EmitContainer._map[4] = "Constructor"; + EmitContainer.Constructor = 4; + EmitContainer._map[5] = "Function"; + EmitContainer.Function = 5; + EmitContainer._map[6] = "Args"; + EmitContainer.Args = 6; + EmitContainer._map[7] = "Interface"; + EmitContainer.Interface = 7; + })(TypeScript.EmitContainer || (TypeScript.EmitContainer = {})); + var EmitContainer = TypeScript.EmitContainer; + var EmitState = (function () { + function EmitState() { + this.column = 0; + this.line = 0; + this.pretty = false; + this.inObjectLiteral = false; + this.container = EmitContainer.Prog; + } + return EmitState; + })(); + TypeScript.EmitState = EmitState; + var EmitOptions = (function () { + function EmitOptions(settings) { + this.ioHost = null; + this.outputMany = true; + this.commonDirectoryPath = ""; + this.minWhitespace = settings.minWhitespace; + this.propagateConstants = settings.propagateConstants; + this.emitComments = settings.emitComments; + this.outputOption = settings.outputOption; + } + EmitOptions.prototype.mapOutputFileName = function (fileName, extensionChanger) { + if(this.outputMany) { + var updatedFileName = fileName; + if(this.outputOption != "") { + updatedFileName = fileName.replace(this.commonDirectoryPath, ""); + updatedFileName = this.outputOption + updatedFileName; + } + return extensionChanger(updatedFileName, false); + } else { + return extensionChanger(this.outputOption, true); + } + }; + return EmitOptions; + })(); + TypeScript.EmitOptions = EmitOptions; + var Indenter = (function () { + function Indenter() { + this.indentAmt = 0; + } + Indenter.indentStep = 4; + Indenter.indentStepString = " "; + Indenter.indentStrings = []; + Indenter.prototype.increaseIndent = function () { + this.indentAmt += Indenter.indentStep; + }; + Indenter.prototype.decreaseIndent = function () { + this.indentAmt -= Indenter.indentStep; + }; + Indenter.prototype.getIndent = function () { + var indentString = Indenter.indentStrings[this.indentAmt]; + if(indentString === undefined) { + indentString = ""; + for(var i = 0; i < this.indentAmt; i = i + Indenter.indentStep) { + indentString += Indenter.indentStepString; + } + Indenter.indentStrings[this.indentAmt] = indentString; + } + return indentString; + }; + return Indenter; + })(); + TypeScript.Indenter = Indenter; + var Emitter = (function () { + function Emitter(checker, emittingFileName, outfile, emitOptions, errorReporter) { + this.checker = checker; + this.emittingFileName = emittingFileName; + this.outfile = outfile; + this.emitOptions = emitOptions; + this.errorReporter = errorReporter; + this.prologueEmitted = false; + this.thisClassNode = null; + this.thisFnc = null; + this.moduleDeclList = []; + this.moduleName = ""; + this.emitState = new EmitState(); + this.indenter = new Indenter(); + this.ambientModule = false; + this.modAliasId = null; + this.firstModAlias = null; + this.allSourceMappers = []; + this.sourceMapper = null; + this.captureThisStmtString = "var _this = this;"; + this.varListCountStack = [ + 0 + ]; + } + Emitter.prototype.setSourceMappings = function (mapper) { + this.allSourceMappers.push(mapper); + this.sourceMapper = mapper; + }; + Emitter.prototype.writeToOutput = function (s) { + this.outfile.Write(s); + this.emitState.column += s.length; + }; + Emitter.prototype.writeToOutputTrimmable = function (s) { + if(this.emitOptions.minWhitespace) { + s = s.replace(/[\s]*/g, ''); + } + this.writeToOutput(s); + }; + Emitter.prototype.writeLineToOutput = function (s) { + if(this.emitOptions.minWhitespace) { + this.writeToOutput(s); + var c = s.charCodeAt(s.length - 1); + if(!((c == TypeScript.LexCodeSpace) || (c == TypeScript.LexCodeSMC) || (c == TypeScript.LexCodeLBR))) { + this.writeToOutput(' '); + } + } else { + this.outfile.WriteLine(s); + this.emitState.column = 0; + this.emitState.line++; + } + }; + Emitter.prototype.writeCaptureThisStatement = function (ast) { + this.emitIndent(); + this.recordSourceMappingStart(ast); + this.writeToOutput(this.captureThisStmtString); + this.recordSourceMappingEnd(ast); + this.writeLineToOutput(""); + }; + Emitter.prototype.setInVarBlock = function (count) { + this.varListCountStack[this.varListCountStack.length - 1] = count; + }; + Emitter.prototype.setInObjectLiteral = function (val) { + var temp = this.emitState.inObjectLiteral; + this.emitState.inObjectLiteral = val; + return temp; + }; + Emitter.prototype.setContainer = function (c) { + var temp = this.emitState.container; + this.emitState.container = c; + return temp; + }; + Emitter.prototype.getIndentString = function () { + if(this.emitOptions.minWhitespace) { + return ""; + } else { + return this.indenter.getIndent(); + } + }; + Emitter.prototype.emitIndent = function () { + this.writeToOutput(this.getIndentString()); + }; + Emitter.prototype.emitCommentInPlace = function (comment) { + this.recordSourceMappingStart(comment); + var text = comment.getText(); + var hadNewLine = false; + if(comment.isBlockComment) { + if(this.emitState.column == 0) { + this.emitIndent(); + } + this.writeToOutput(text[0]); + if(text.length > 1 || comment.endsLine) { + this.writeLineToOutput(""); + for(var i = 1; i < text.length; i++) { + this.emitIndent(); + this.writeLineToOutput(text[i]); + } + hadNewLine = true; + } + } else { + if(this.emitState.column == 0) { + this.emitIndent(); + } + this.writeLineToOutput(text[0]); + hadNewLine = true; + } + if(hadNewLine) { + this.emitIndent(); + } else { + this.writeToOutput(" "); + } + this.recordSourceMappingEnd(comment); + }; + Emitter.prototype.emitParensAndCommentsInPlace = function (ast, pre) { + var comments = pre ? ast.preComments : ast.postComments; + if(ast.isParenthesized && !pre) { + this.writeToOutput(")"); + } + if(this.emitOptions.emitComments && comments && comments.length != 0) { + for(var i = 0; i < comments.length; i++) { + this.emitCommentInPlace(comments[i]); + } + } + if(ast.isParenthesized && pre) { + this.writeToOutput("("); + } + }; + Emitter.prototype.emitObjectLiteral = function (content) { + this.writeLineToOutput("{"); + this.indenter.increaseIndent(); + var inObjectLiteral = this.setInObjectLiteral(true); + this.emitJavascriptList(content, ",", TypeScript.TokenID.Comma, true, false, false); + this.setInObjectLiteral(inObjectLiteral); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeToOutput("}"); + }; + Emitter.prototype.emitArrayLiteral = function (content) { + this.writeToOutput("["); + if(content) { + this.writeLineToOutput(""); + this.indenter.increaseIndent(); + this.emitJavascriptList(content, ", ", TypeScript.TokenID.Comma, true, false, false); + this.indenter.decreaseIndent(); + this.emitIndent(); + } + this.writeToOutput("]"); + }; + Emitter.prototype.emitNew = function (target, args) { + this.writeToOutput("new "); + if(target.nodeType == TypeScript.NodeType.TypeRef) { + var typeRef = target; + if(typeRef.arrayCount) { + this.writeToOutput("Array()"); + } else { + this.emitJavascript(typeRef.term, TypeScript.TokenID.Tilde, false); + this.writeToOutput("()"); + } + } else { + this.emitJavascript(target, TypeScript.TokenID.Tilde, false); + this.recordSourceMappingStart(args); + this.writeToOutput("("); + this.emitJavascriptList(args, ", ", TypeScript.TokenID.Comma, false, false, false); + this.writeToOutput(")"); + this.recordSourceMappingEnd(args); + } + }; + Emitter.prototype.tryEmitConstant = function (dotExpr) { + if(!this.emitOptions.propagateConstants) { + return false; + } + var propertyName = dotExpr.operand2; + if(propertyName && propertyName.sym && propertyName.sym.isVariable()) { + if(TypeScript.hasFlag(propertyName.sym.flags, TypeScript.SymbolFlags.Constant)) { + if(propertyName.sym.declAST) { + var boundDecl = propertyName.sym.declAST; + if(boundDecl.init && (boundDecl.init.nodeType == TypeScript.NodeType.NumberLit)) { + var numLit = boundDecl.init; + this.writeToOutput(numLit.value.toString()); + var comment = " /* "; + comment += propertyName.actualText; + comment += " */ "; + this.writeToOutput(comment); + return true; + } + } + } + } + return false; + }; + Emitter.prototype.emitCall = function (callNode, target, args) { + if(!this.emitSuperCall(callNode)) { + if(!TypeScript.hasFlag(callNode.flags, TypeScript.ASTFlags.ClassBaseConstructorCall)) { + if(target.nodeType == TypeScript.NodeType.FuncDecl && !target.isParenthesized) { + this.writeToOutput("("); + } + if(callNode.target.nodeType == TypeScript.NodeType.Super && this.emitState.container == EmitContainer.Constructor) { + this.writeToOutput("_super.call"); + } else { + this.emitJavascript(target, TypeScript.TokenID.OpenParen, false); + } + if(target.nodeType == TypeScript.NodeType.FuncDecl && !target.isParenthesized) { + this.writeToOutput(")"); + } + this.recordSourceMappingStart(args); + this.writeToOutput("("); + if(callNode.target.nodeType == TypeScript.NodeType.Super && this.emitState.container == EmitContainer.Constructor) { + this.writeToOutput("this"); + if(args && args.members.length) { + this.writeToOutput(", "); + } + } + this.emitJavascriptList(args, ", ", TypeScript.TokenID.Comma, false, false, false); + this.writeToOutput(")"); + this.recordSourceMappingEnd(args); + } else { + this.indenter.decreaseIndent(); + this.indenter.decreaseIndent(); + var constructorCall = new TypeScript.ASTList(); + constructorCall.members[0] = callNode; + this.emitConstructorCalls(constructorCall, this.thisClassNode); + this.indenter.increaseIndent(); + this.indenter.increaseIndent(); + } + } + }; + Emitter.prototype.emitConstructorCalls = function (bases, classDecl) { + if(bases == null) { + return; + } + var basesLen = bases.members.length; + this.recordSourceMappingStart(classDecl); + for(var i = 0; i < basesLen; i++) { + var baseExpr = bases.members[i]; + var baseSymbol = null; + if(baseExpr.nodeType == TypeScript.NodeType.Call) { + baseSymbol = (baseExpr).target.type.symbol; + } else { + baseSymbol = baseExpr.type.symbol; + } + var baseName = baseSymbol.name; + if(baseSymbol.declModule != classDecl.type.symbol.declModule) { + baseName = baseSymbol.fullName(); + } + if(baseExpr.nodeType == TypeScript.NodeType.Call) { + this.emitIndent(); + this.writeToOutput("_super.call(this"); + var args = (baseExpr).arguments; + if(args && (args.members.length > 0)) { + this.writeToOutput(", "); + this.emitJavascriptList(args, ", ", TypeScript.TokenID.Comma, false, false, false); + } + this.writeToOutput(")"); + } else { + if(baseExpr.type && (baseExpr.type.isClassInstance())) { + this.emitIndent(); + this.writeToOutput(classDecl.name.actualText + "._super.constructor"); + this.writeToOutput(".call(this)"); + } + } + } + this.recordSourceMappingEnd(classDecl); + }; + Emitter.prototype.emitInnerFunction = function (funcDecl, printName, isMember, bases, hasSelfRef, classDecl) { + var isClassConstructor = funcDecl.isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod); + var hasNonObjectBaseType = isClassConstructor && TypeScript.hasFlag(this.thisClassNode.type.instanceType.typeFlags, TypeScript.TypeFlags.HasBaseType) && !TypeScript.hasFlag(this.thisClassNode.type.instanceType.typeFlags, TypeScript.TypeFlags.HasBaseTypeOfObject); + var classPropertiesMustComeAfterSuperCall = hasNonObjectBaseType && TypeScript.hasFlag((this.thisClassNode).varFlags, TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor); + var shouldParenthesize = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFunctionExpression) && !funcDecl.isParenthesized && !funcDecl.isAccessor() && (TypeScript.hasFlag(funcDecl.flags, TypeScript.ASTFlags.ExplicitSemicolon) || TypeScript.hasFlag(funcDecl.flags, TypeScript.ASTFlags.AutomaticSemicolon)); + this.emitParensAndCommentsInPlace(funcDecl, true); + if(shouldParenthesize) { + this.writeToOutput("("); + } + this.recordSourceMappingStart(funcDecl); + if(!(funcDecl.isAccessor() && (funcDecl.accessorSymbol).isObjectLitField)) { + this.writeToOutput("function "); + } + if(printName) { + var id = funcDecl.getNameText(); + if(id && !funcDecl.isAccessor()) { + if(funcDecl.name) { + this.recordSourceMappingStart(funcDecl.name); + } + this.writeToOutput(id); + if(funcDecl.name) { + this.recordSourceMappingEnd(funcDecl.name); + } + } + } + this.writeToOutput("("); + var argsLen = 0; + var i = 0; + var arg; + var defaultArgs = []; + if(funcDecl.arguments) { + var tempContainer = this.setContainer(EmitContainer.Args); + argsLen = funcDecl.arguments.members.length; + var printLen = argsLen; + if(funcDecl.variableArgList) { + printLen--; + } + for(i = 0; i < printLen; i++) { + arg = funcDecl.arguments.members[i]; + if(arg.init) { + defaultArgs.push(arg); + } + this.emitJavascript(arg, TypeScript.TokenID.OpenParen, false); + if(i < (printLen - 1)) { + this.writeToOutput(", "); + } + } + this.setContainer(tempContainer); + } + this.writeLineToOutput(") {"); + if(funcDecl.isConstructor) { + this.recordSourceMappingNameStart("constructor"); + } else { + if(funcDecl.isGetAccessor()) { + this.recordSourceMappingNameStart("get_" + funcDecl.getNameText()); + } else { + if(funcDecl.isSetAccessor()) { + this.recordSourceMappingNameStart("set_" + funcDecl.getNameText()); + } else { + this.recordSourceMappingNameStart(funcDecl.getNameText()); + } + } + } + this.indenter.increaseIndent(); + for(i = 0; i < defaultArgs.length; i++) { + var arg = defaultArgs[i]; + this.emitIndent(); + this.recordSourceMappingStart(arg); + this.writeToOutput("if (typeof " + arg.id.actualText + " === \"undefined\") { "); + this.recordSourceMappingStart(arg.id); + this.writeToOutput(arg.id.actualText); + this.recordSourceMappingEnd(arg.id); + this.writeToOutput(" = "); + this.emitJavascript(arg.init, TypeScript.TokenID.OpenParen, false); + this.writeLineToOutput("; }"); + this.recordSourceMappingEnd(arg); + } + if(funcDecl.isConstructor && ((funcDecl.classDecl).varFlags & TypeScript.VarFlags.MustCaptureThis)) { + this.writeCaptureThisStatement(funcDecl); + } + if(funcDecl.isConstructor && !classPropertiesMustComeAfterSuperCall) { + if(funcDecl.arguments) { + argsLen = funcDecl.arguments.members.length; + for(i = 0; i < argsLen; i++) { + arg = funcDecl.arguments.members[i]; + if((arg.varFlags & TypeScript.VarFlags.Property) != TypeScript.VarFlags.None) { + this.emitIndent(); + this.recordSourceMappingStart(arg); + this.recordSourceMappingStart(arg.id); + this.writeToOutput("this." + arg.id.actualText); + this.recordSourceMappingEnd(arg.id); + this.writeToOutput(" = "); + this.recordSourceMappingStart(arg.id); + this.writeToOutput(arg.id.actualText); + this.recordSourceMappingEnd(arg.id); + this.writeLineToOutput(";"); + this.recordSourceMappingEnd(arg); + } + } + } + if(!TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { + this.emitConstructorCalls(bases, classDecl); + } + } + if(hasSelfRef) { + this.writeCaptureThisStatement(funcDecl); + } + if(funcDecl.variableArgList) { + argsLen = funcDecl.arguments.members.length; + var lastArg = funcDecl.arguments.members[argsLen - 1]; + this.emitIndent(); + this.recordSourceMappingStart(lastArg); + this.writeToOutput("var "); + this.recordSourceMappingStart(lastArg.id); + this.writeToOutput(lastArg.id.actualText); + this.recordSourceMappingEnd(lastArg.id); + this.writeLineToOutput(" = [];"); + this.recordSourceMappingEnd(lastArg); + this.emitIndent(); + this.writeToOutput("for ("); + this.recordSourceMappingStart(lastArg); + this.writeToOutput("var _i = 0;"); + this.recordSourceMappingEnd(lastArg); + this.writeToOutput(" "); + this.recordSourceMappingStart(lastArg); + this.writeToOutput("_i < (arguments.length - " + (argsLen - 1) + ")"); + this.recordSourceMappingEnd(lastArg); + this.writeToOutput("; "); + this.recordSourceMappingStart(lastArg); + this.writeToOutput("_i++"); + this.recordSourceMappingEnd(lastArg); + this.writeLineToOutput(") {"); + this.indenter.increaseIndent(); + this.emitIndent(); + this.recordSourceMappingStart(lastArg); + this.writeToOutput(lastArg.id.actualText + "[_i] = arguments[_i + " + (argsLen - 1) + "];"); + this.recordSourceMappingEnd(lastArg); + this.writeLineToOutput(""); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeLineToOutput("}"); + } + if(funcDecl.isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod) && !classPropertiesMustComeAfterSuperCall) { + var nProps = (this.thisClassNode.members).members.length; + for(var i = 0; i < nProps; i++) { + if((this.thisClassNode.members).members[i].nodeType == TypeScript.NodeType.VarDecl) { + var varDecl = (this.thisClassNode.members).members[i]; + if(!TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static) && varDecl.init) { + this.emitIndent(); + this.emitJavascriptVarDecl(varDecl, TypeScript.TokenID.Tilde); + this.writeLineToOutput(""); + } + } + } + } + this.emitBareJavascriptStatements(funcDecl.bod, classPropertiesMustComeAfterSuperCall); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.recordSourceMappingStart(funcDecl.endingToken); + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(funcDecl.endingToken); + this.recordSourceMappingEnd(funcDecl); + if(shouldParenthesize) { + this.writeToOutput(")"); + } + this.recordSourceMappingEnd(funcDecl); + this.emitParensAndCommentsInPlace(funcDecl, false); + if(!isMember && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFunctionExpression) && (TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Definition) || funcDecl.isConstructor)) { + this.writeLineToOutput(""); + } else { + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFunctionExpression)) { + if(TypeScript.hasFlag(funcDecl.flags, TypeScript.ASTFlags.ExplicitSemicolon) || TypeScript.hasFlag(funcDecl.flags, TypeScript.ASTFlags.AutomaticSemicolon)) { + this.writeLineToOutput(";"); + } + } + } + }; + Emitter.prototype.emitJavascriptModule = function (moduleDecl) { + var modName = moduleDecl.name.actualText; + if(TypeScript.isTSFile(modName)) { + moduleDecl.name.setText(modName.substring(0, modName.length - 3)); + } else { + if(TypeScript.isSTRFile(modName)) { + moduleDecl.name.setText(modName.substring(0, modName.length - 4)); + } + } + if(!TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.Ambient)) { + var isDynamicMod = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsDynamic); + var prevOutFile = this.outfile; + var prevOutFileName = this.emittingFileName; + var prevAllSourceMappers = this.allSourceMappers; + var prevSourceMapper = this.sourceMapper; + var prevColumn = this.emitState.column; + var prevLine = this.emitState.line; + var temp = this.setContainer(EmitContainer.Module); + var svModuleName = this.moduleName; + var isExported = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.Exported); + this.moduleDeclList[this.moduleDeclList.length] = moduleDecl; + var isWholeFile = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsWholeFile); + this.moduleName = moduleDecl.name.actualText; + if(isDynamicMod) { + var tsModFileName = TypeScript.stripQuotes(moduleDecl.name.actualText); + var modFilePath = TypeScript.trimModName(tsModFileName) + ".js"; + modFilePath = this.emitOptions.mapOutputFileName(modFilePath, TypeScript.TypeScriptCompiler.mapToJSFileName); + if(this.emitOptions.ioHost) { + if(TypeScript.switchToForwardSlashes(modFilePath) != TypeScript.switchToForwardSlashes(this.emittingFileName)) { + this.emittingFileName = modFilePath; + var useUTF8InOutputfile = moduleDecl.containsUnicodeChar || (this.emitOptions.emitComments && moduleDecl.containsUnicodeCharInComment); + this.outfile = this.createFile(this.emittingFileName, useUTF8InOutputfile); + if(prevSourceMapper != null) { + this.allSourceMappers = []; + var sourceMappingFile = this.createFile(this.emittingFileName + TypeScript.SourceMapper.MapFileExtension, false); + this.setSourceMappings(new TypeScript.SourceMapper(tsModFileName, this.emittingFileName, this.outfile, sourceMappingFile, this.errorReporter)); + this.emitState.column = 0; + this.emitState.line = 0; + } + } else { + TypeScript.CompilerDiagnostics.assert(this.emitOptions.outputMany, "Cannot have dynamic modules compiling into single file"); + } + } + this.setContainer(EmitContainer.DynamicModule); + this.recordSourceMappingStart(moduleDecl); + if(TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { + var dependencyList = "[\"require\", \"exports\""; + var importList = "require, exports"; + var importStatement = null; + for(var i = 0; i < (moduleDecl.mod).importedModules.length; i++) { + importStatement = (moduleDecl.mod).importedModules[i]; + if(importStatement.id.sym && !(importStatement.id.sym).onlyReferencedAsTypeRef) { + if(i <= (moduleDecl.mod).importedModules.length - 1) { + dependencyList += ", "; + importList += ", "; + } + importList += "__" + importStatement.id.actualText + "__"; + dependencyList += importStatement.firstAliasedModToString(); + } + } + for(var i = 0; i < moduleDecl.amdDependencies.length; i++) { + dependencyList += ", \"" + moduleDecl.amdDependencies[i] + "\""; + } + dependencyList += "]"; + this.writeLineToOutput("define(" + dependencyList + "," + " function(" + importList + ") {"); + } else { + } + } else { + if(!isExported) { + this.recordSourceMappingStart(moduleDecl); + this.writeToOutput("var "); + this.recordSourceMappingStart(moduleDecl.name); + this.writeToOutput(this.moduleName); + this.recordSourceMappingEnd(moduleDecl.name); + this.writeLineToOutput(";"); + this.recordSourceMappingEnd(moduleDecl); + this.emitIndent(); + } + this.writeToOutput("("); + this.recordSourceMappingStart(moduleDecl); + this.writeToOutput("function ("); + this.recordSourceMappingStart(moduleDecl.name); + this.writeToOutput(this.moduleName); + this.recordSourceMappingEnd(moduleDecl.name); + this.writeLineToOutput(") {"); + } + if(!isWholeFile) { + this.recordSourceMappingNameStart(this.moduleName); + } + if(!isDynamicMod || TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { + this.indenter.increaseIndent(); + } + if(moduleDecl.modFlags & TypeScript.ModuleFlags.MustCaptureThis) { + this.writeCaptureThisStatement(moduleDecl); + } + this.emitJavascriptList(moduleDecl.members, null, TypeScript.TokenID.Semicolon, true, false, false); + if(!isDynamicMod || TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { + this.indenter.decreaseIndent(); + } + this.emitIndent(); + if(isDynamicMod) { + if(TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { + this.writeLineToOutput("})"); + } else { + } + if(!isWholeFile) { + this.recordSourceMappingNameEnd(); + } + this.recordSourceMappingEnd(moduleDecl); + if(this.outfile != prevOutFile) { + this.Close(); + if(prevSourceMapper != null) { + this.allSourceMappers = prevAllSourceMappers; + this.sourceMapper = prevSourceMapper; + this.emitState.column = prevColumn; + this.emitState.line = prevLine; + } + this.outfile = prevOutFile; + this.emittingFileName = prevOutFileName; + } + } else { + var containingMod = null; + if(moduleDecl.type && moduleDecl.type.symbol.container && moduleDecl.type.symbol.container.declAST) { + containingMod = moduleDecl.type.symbol.container.declAST; + } + var parentIsDynamic = containingMod && TypeScript.hasFlag(containingMod.modFlags, TypeScript.ModuleFlags.IsDynamic); + this.recordSourceMappingStart(moduleDecl.endingToken); + if(temp == EmitContainer.Prog && isExported) { + this.writeToOutput("}"); + if(!isWholeFile) { + this.recordSourceMappingNameEnd(); + } + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeLineToOutput(")(this." + this.moduleName + " || (this." + this.moduleName + " = {}));"); + } else { + if(isExported || temp == EmitContainer.Prog) { + var dotMod = svModuleName != "" ? (parentIsDynamic ? "exports" : svModuleName) + "." : svModuleName; + this.writeToOutput("}"); + if(!isWholeFile) { + this.recordSourceMappingNameEnd(); + } + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeLineToOutput(")(" + dotMod + this.moduleName + " || (" + dotMod + this.moduleName + " = {}));"); + } else { + if(!isExported && temp != EmitContainer.Prog) { + this.writeToOutput("}"); + if(!isWholeFile) { + this.recordSourceMappingNameEnd(); + } + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeLineToOutput(")(" + this.moduleName + " || (" + this.moduleName + " = {}));"); + } else { + this.writeToOutput("}"); + if(!isWholeFile) { + this.recordSourceMappingNameEnd(); + } + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeLineToOutput(")();"); + } + } + } + this.recordSourceMappingEnd(moduleDecl); + if(temp != EmitContainer.Prog && isExported) { + this.emitIndent(); + this.recordSourceMappingStart(moduleDecl); + if(parentIsDynamic) { + this.writeLineToOutput("var " + this.moduleName + " = exports." + this.moduleName + ";"); + } else { + this.writeLineToOutput("var " + this.moduleName + " = " + svModuleName + "." + this.moduleName + ";"); + } + this.recordSourceMappingEnd(moduleDecl); + } + } + this.setContainer(temp); + this.moduleName = svModuleName; + this.moduleDeclList.length--; + } + }; + Emitter.prototype.emitIndex = function (operand1, operand2) { + var temp = this.setInObjectLiteral(false); + this.emitJavascript(operand1, TypeScript.TokenID.Tilde, false); + this.writeToOutput("["); + this.emitJavascriptList(operand2, ", ", TypeScript.TokenID.Comma, false, false, false); + this.writeToOutput("]"); + this.setInObjectLiteral(temp); + }; + Emitter.prototype.emitStringLiteral = function (text) { + this.writeToOutput(text); + }; + Emitter.prototype.emitJavascriptFunction = function (funcDecl) { + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Signature) || funcDecl.isOverload) { + return; + } + var temp; + var tempFnc = this.thisFnc; + this.thisFnc = funcDecl; + if(funcDecl.isConstructor) { + temp = this.setContainer(EmitContainer.Constructor); + } else { + temp = this.setContainer(EmitContainer.Function); + } + var bases = null; + var hasSelfRef = false; + var funcName = funcDecl.getNameText(); + if((this.emitState.inObjectLiteral || !funcDecl.isAccessor()) && ((temp != EmitContainer.Constructor) || ((funcDecl.fncFlags & TypeScript.FncFlags.Method) == TypeScript.FncFlags.None))) { + var tempLit = this.setInObjectLiteral(false); + if(this.thisClassNode) { + bases = this.thisClassNode.extendsList; + } + hasSelfRef = Emitter.shouldCaptureThis(funcDecl); + this.recordSourceMappingStart(funcDecl); + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Exported | TypeScript.FncFlags.ClassPropertyMethodExported) && funcDecl.type.symbol.container == this.checker.gloMod && !funcDecl.isConstructor) { + this.writeToOutput("this." + funcName + " = "); + this.emitInnerFunction(funcDecl, false, false, bases, hasSelfRef, this.thisClassNode); + } else { + this.emitInnerFunction(funcDecl, (funcDecl.name && !funcDecl.name.isMissing()), false, bases, hasSelfRef, this.thisClassNode); + } + this.setInObjectLiteral(tempLit); + } + this.setContainer(temp); + this.thisFnc = tempFnc; + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Definition)) { + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static)) { + if(this.thisClassNode) { + if(funcDecl.isAccessor()) { + this.emitPropertyAccessor(funcDecl, this.thisClassNode.name.actualText, false); + } else { + this.emitIndent(); + this.recordSourceMappingStart(funcDecl); + this.writeLineToOutput(this.thisClassNode.name.actualText + "." + funcName + " = " + funcName + ";"); + this.recordSourceMappingEnd(funcDecl); + } + } + } else { + if((this.emitState.container == EmitContainer.Module || this.emitState.container == EmitContainer.DynamicModule) && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Exported | TypeScript.FncFlags.ClassPropertyMethodExported)) { + this.emitIndent(); + var modName = this.emitState.container == EmitContainer.Module ? this.moduleName : "exports"; + this.recordSourceMappingStart(funcDecl); + this.writeLineToOutput(modName + "." + funcName + " = " + funcName + ";"); + this.recordSourceMappingEnd(funcDecl); + } + } + } + }; + Emitter.prototype.emitAmbientVarDecl = function (varDecl) { + if(varDecl.init) { + this.emitParensAndCommentsInPlace(varDecl, true); + this.recordSourceMappingStart(varDecl); + this.recordSourceMappingStart(varDecl.id); + this.writeToOutput(varDecl.id.actualText); + this.recordSourceMappingEnd(varDecl.id); + this.writeToOutput(" = "); + this.emitJavascript(varDecl.init, TypeScript.TokenID.Comma, false); + this.recordSourceMappingEnd(varDecl); + this.writeToOutput(";"); + this.emitParensAndCommentsInPlace(varDecl, false); + } + }; + Emitter.prototype.varListCount = function () { + return this.varListCountStack[this.varListCountStack.length - 1]; + }; + Emitter.prototype.emitVarDeclVar = function () { + if(this.varListCount() >= 0) { + this.writeToOutput("var "); + this.setInVarBlock(-this.varListCount()); + } + return true; + }; + Emitter.prototype.onEmitVar = function () { + if(this.varListCount() > 0) { + this.setInVarBlock(this.varListCount() - 1); + } else { + if(this.varListCount() < 0) { + this.setInVarBlock(this.varListCount() + 1); + } + } + }; + Emitter.prototype.emitJavascriptVarDecl = function (varDecl, tokenId) { + if((varDecl.varFlags & TypeScript.VarFlags.Ambient) == TypeScript.VarFlags.Ambient) { + this.emitAmbientVarDecl(varDecl); + this.onEmitVar(); + } else { + var sym = varDecl.sym; + var hasInitializer = (varDecl.init != null); + this.emitParensAndCommentsInPlace(varDecl, true); + this.recordSourceMappingStart(varDecl); + if(sym && sym.isMember() && sym.container && (sym.container.kind() == TypeScript.SymbolKind.Type)) { + var type = (sym.container).type; + if(type.isClass() && (!TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.ModuleMember))) { + if(this.emitState.container != EmitContainer.Args) { + if(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Static)) { + this.writeToOutput(sym.container.name + "."); + } else { + this.writeToOutput("this."); + } + } + } else { + if(type.hasImplementation()) { + if(!TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Exported) && (sym.container == this.checker.gloMod || !TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Property))) { + this.emitVarDeclVar(); + } else { + if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.LocalStatic)) { + this.writeToOutput("."); + } else { + if(this.emitState.container == EmitContainer.DynamicModule) { + this.writeToOutput("exports."); + } else { + this.writeToOutput(this.moduleName + "."); + } + } + } + } else { + if(tokenId != TypeScript.TokenID.OpenParen) { + if(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Exported) && sym.container == this.checker.gloMod) { + this.writeToOutput("this."); + } else { + this.emitVarDeclVar(); + } + } + } + } + } else { + if(tokenId != TypeScript.TokenID.OpenParen) { + this.emitVarDeclVar(); + } + } + this.recordSourceMappingStart(varDecl.id); + this.writeToOutput(varDecl.id.actualText); + this.recordSourceMappingEnd(varDecl.id); + if(hasInitializer) { + this.writeToOutputTrimmable(" = "); + this.varListCountStack.push(0); + this.emitJavascript(varDecl.init, TypeScript.TokenID.Comma, false); + this.varListCountStack.pop(); + } + this.onEmitVar(); + if((tokenId != TypeScript.TokenID.OpenParen)) { + if(this.varListCount() < 0) { + this.writeToOutput(", "); + } else { + if(tokenId != TypeScript.TokenID.For) { + this.writeToOutputTrimmable(";"); + } + } + } + this.recordSourceMappingEnd(varDecl); + this.emitParensAndCommentsInPlace(varDecl, false); + } + }; + Emitter.prototype.declEnclosed = function (moduleDecl) { + if(moduleDecl == null) { + return true; + } + for(var i = 0, len = this.moduleDeclList.length; i < len; i++) { + if(this.moduleDeclList[i] == moduleDecl) { + return true; + } + } + return false; + }; + Emitter.prototype.emitJavascriptName = function (name, addThis) { + var sym = name.sym; + this.emitParensAndCommentsInPlace(name, true); + this.recordSourceMappingStart(name); + if(!name.isMissing()) { + if(addThis && (this.emitState.container != EmitContainer.Args) && sym) { + if(sym.container && (sym.container.name != TypeScript.globalId)) { + if(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Static) && (TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Property))) { + if(sym.declModule && TypeScript.hasFlag(sym.declModule.modFlags, TypeScript.ModuleFlags.IsDynamic)) { + this.writeToOutput("exports."); + } else { + this.writeToOutput(sym.container.name + "."); + } + } else { + if(sym.kind() == TypeScript.SymbolKind.Field) { + var fieldSym = sym; + if(TypeScript.hasFlag(fieldSym.flags, TypeScript.SymbolFlags.ModuleMember)) { + if((sym.container != this.checker.gloMod) && ((TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Property)) || TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Exported))) { + if(TypeScript.hasFlag(sym.declModule.modFlags, TypeScript.ModuleFlags.IsDynamic)) { + this.writeToOutput("exports."); + } else { + this.writeToOutput(sym.container.name + "."); + } + } + } else { + if(sym.isInstanceProperty()) { + this.emitThis(); + this.writeToOutput("."); + } + } + } else { + if(sym.kind() == TypeScript.SymbolKind.Type) { + if(sym.isInstanceProperty()) { + var typeSym = sym; + var type = typeSym.type; + if(type.call && !TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.ModuleMember)) { + this.emitThis(); + this.writeToOutput("."); + } + } else { + if((sym.unitIndex != this.checker.locationInfo.unitIndex) || (!this.declEnclosed(sym.declModule))) { + this.writeToOutput(sym.container.name + "."); + } + } + } + } + } + } else { + if(sym.container == this.checker.gloMod && TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Exported) && !TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Ambient) && !((sym.isType() || sym.isMember()) && sym.declModule && TypeScript.hasFlag(sym.declModule.modFlags, TypeScript.ModuleFlags.Ambient)) && this.emitState.container == EmitContainer.Prog && sym.declAST.nodeType != TypeScript.NodeType.FuncDecl) { + this.writeToOutput("this."); + } + } + } + if(sym && sym.declAST && sym.declAST.nodeType == TypeScript.NodeType.ModuleDeclaration && (TypeScript.hasFlag((sym.declAST).modFlags, TypeScript.ModuleFlags.IsDynamic))) { + var moduleDecl = sym.declAST; + if(TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { + this.writeLineToOutput("__" + this.modAliasId + "__;"); + } else { + var modPath = name.actualText; + var isAmbient = moduleDecl.mod.symbol.declAST && TypeScript.hasFlag((moduleDecl.mod.symbol.declAST).modFlags, TypeScript.ModuleFlags.Ambient); + modPath = isAmbient ? modPath : this.firstModAlias ? this.firstModAlias : TypeScript.quoteBaseName(modPath); + modPath = isAmbient ? modPath : (!TypeScript.isRelative(TypeScript.stripQuotes(modPath)) ? TypeScript.quoteStr("./" + TypeScript.stripQuotes(modPath)) : modPath); + this.writeToOutput("require(" + modPath + ")"); + } + } else { + this.writeToOutput(name.actualText); + } + } + this.recordSourceMappingEnd(name); + this.emitParensAndCommentsInPlace(name, false); + }; + Emitter.prototype.emitJavascriptStatements = function (stmts, emitEmptyBod) { + if(stmts) { + if(stmts.nodeType != TypeScript.NodeType.Block) { + var hasContents = (stmts && (stmts.nodeType != TypeScript.NodeType.List || ((stmts).members.length > 0))); + if(emitEmptyBod || hasContents) { + var hasOnlyBlockStatement = ((stmts.nodeType == TypeScript.NodeType.Block) || ((stmts.nodeType == TypeScript.NodeType.List) && ((stmts).members.length == 1) && ((stmts).members[0].nodeType == TypeScript.NodeType.Block))); + this.recordSourceMappingStart(stmts); + if(!hasOnlyBlockStatement) { + this.writeLineToOutput(" {"); + this.indenter.increaseIndent(); + } + this.emitJavascriptList(stmts, null, TypeScript.TokenID.Semicolon, true, false, false); + if(!hasOnlyBlockStatement) { + this.writeLineToOutput(""); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeToOutput("}"); + } + this.recordSourceMappingEnd(stmts); + } + } else { + this.emitJavascript(stmts, TypeScript.TokenID.Semicolon, true); + } + } else { + if(emitEmptyBod) { + this.writeToOutput("{ }"); + } + } + }; + Emitter.prototype.emitBareJavascriptStatements = function (stmts, emitClassPropertiesAfterSuperCall) { + if (typeof emitClassPropertiesAfterSuperCall === "undefined") { emitClassPropertiesAfterSuperCall = false; } + if(stmts.nodeType != TypeScript.NodeType.Block) { + if(stmts.nodeType == TypeScript.NodeType.List) { + var stmtList = stmts; + if((stmtList.members.length == 2) && (stmtList.members[0].nodeType == TypeScript.NodeType.Block) && (stmtList.members[1].nodeType == TypeScript.NodeType.EndCode)) { + this.emitJavascript(stmtList.members[0], TypeScript.TokenID.Semicolon, true); + this.writeLineToOutput(""); + } else { + this.emitJavascriptList(stmts, null, TypeScript.TokenID.Semicolon, true, false, emitClassPropertiesAfterSuperCall); + } + } else { + this.emitJavascript(stmts, TypeScript.TokenID.Semicolon, true); + } + } else { + this.emitJavascript(stmts, TypeScript.TokenID.Semicolon, true); + } + }; + Emitter.prototype.recordSourceMappingNameStart = function (name) { + if(this.sourceMapper) { + var finalName = name; + if(!name) { + finalName = ""; + } else { + if(this.sourceMapper.currentNameIndex.length > 0) { + finalName = this.sourceMapper.names[this.sourceMapper.currentNameIndex.length - 1] + "." + name; + } + } + this.sourceMapper.names.push(finalName); + this.sourceMapper.currentNameIndex.push(this.sourceMapper.names.length - 1); + } + }; + Emitter.prototype.recordSourceMappingNameEnd = function () { + if(this.sourceMapper) { + this.sourceMapper.currentNameIndex.pop(); + } + }; + Emitter.prototype.recordSourceMappingStart = function (ast) { + if(this.sourceMapper && TypeScript.isValidAstNode(ast)) { + var lineCol = { + line: -1, + col: -1 + }; + var sourceMapping = new TypeScript.SourceMapping(); + sourceMapping.start.emittedColumn = this.emitState.column; + sourceMapping.start.emittedLine = this.emitState.line; + TypeScript.getSourceLineColFromMap(lineCol, ast.minChar, this.checker.locationInfo.lineMap); + sourceMapping.start.sourceColumn = lineCol.col; + sourceMapping.start.sourceLine = lineCol.line; + TypeScript.getSourceLineColFromMap(lineCol, ast.limChar, this.checker.locationInfo.lineMap); + sourceMapping.end.sourceColumn = lineCol.col; + sourceMapping.end.sourceLine = lineCol.line; + if(this.sourceMapper.currentNameIndex.length > 0) { + sourceMapping.nameIndex = this.sourceMapper.currentNameIndex[this.sourceMapper.currentNameIndex.length - 1]; + } + var siblings = this.sourceMapper.currentMappings[this.sourceMapper.currentMappings.length - 1]; + siblings.push(sourceMapping); + this.sourceMapper.currentMappings.push(sourceMapping.childMappings); + } + }; + Emitter.prototype.recordSourceMappingEnd = function (ast) { + if(this.sourceMapper && TypeScript.isValidAstNode(ast)) { + this.sourceMapper.currentMappings.pop(); + var siblings = this.sourceMapper.currentMappings[this.sourceMapper.currentMappings.length - 1]; + var sourceMapping = siblings[siblings.length - 1]; + sourceMapping.end.emittedColumn = this.emitState.column; + sourceMapping.end.emittedLine = this.emitState.line; + } + }; + Emitter.prototype.Close = function () { + if(this.sourceMapper != null) { + TypeScript.SourceMapper.EmitSourceMapping(this.allSourceMappers); + } + try { + this.outfile.Close(); + } catch (ex) { + this.errorReporter.emitterError(null, ex.message); + } + }; + Emitter.prototype.emitJavascriptList = function (ast, delimiter, tokenId, startLine, onlyStatics, emitClassPropertiesAfterSuperCall, emitPrologue, requiresExtendsBlock) { + if (typeof emitClassPropertiesAfterSuperCall === "undefined") { emitClassPropertiesAfterSuperCall = false; } + if (typeof emitPrologue === "undefined") { emitPrologue = false; } + if(ast == null) { + return; + } else { + if(ast.nodeType != TypeScript.NodeType.List) { + this.emitPrologue(emitPrologue); + this.emitJavascript(ast, tokenId, startLine); + } else { + var list = ast; + if(list.members.length == 0) { + return; + } + this.emitParensAndCommentsInPlace(ast, true); + var len = list.members.length; + for(var i = 0; i < len; i++) { + if(emitPrologue) { + if(i == 1 || !TypeScript.hasFlag(list.flags, TypeScript.ASTFlags.StrictMode)) { + this.emitPrologue(requiresExtendsBlock); + emitPrologue = false; + } + } + if(i == 1 && emitClassPropertiesAfterSuperCall) { + var constructorDecl = (this.thisClassNode).constructorDecl; + if(constructorDecl && constructorDecl.arguments) { + var argsLen = constructorDecl.arguments.members.length; + for(var iArg = 0; iArg < argsLen; iArg++) { + var arg = constructorDecl.arguments.members[iArg]; + if((arg.varFlags & TypeScript.VarFlags.Property) != TypeScript.VarFlags.None) { + this.emitIndent(); + this.recordSourceMappingStart(arg); + this.recordSourceMappingStart(arg.id); + this.writeToOutput("this." + arg.id.actualText); + this.recordSourceMappingEnd(arg.id); + this.writeToOutput(" = "); + this.recordSourceMappingStart(arg.id); + this.writeToOutput(arg.id.actualText); + this.recordSourceMappingEnd(arg.id); + this.writeLineToOutput(";"); + this.recordSourceMappingEnd(arg); + } + } + } + var nProps = (this.thisClassNode.members).members.length; + for(var iMember = 0; iMember < nProps; iMember++) { + if((this.thisClassNode.members).members[iMember].nodeType == TypeScript.NodeType.VarDecl) { + var varDecl = (this.thisClassNode.members).members[iMember]; + if(!TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static) && varDecl.init) { + this.emitIndent(); + this.emitJavascriptVarDecl(varDecl, TypeScript.TokenID.Tilde); + this.writeLineToOutput(""); + } + } + } + } + var emitNode = list.members[i]; + var isStaticDecl = (emitNode.nodeType == TypeScript.NodeType.FuncDecl && TypeScript.hasFlag((emitNode).fncFlags, TypeScript.FncFlags.Static)) || (emitNode.nodeType == TypeScript.NodeType.VarDecl && TypeScript.hasFlag((emitNode).varFlags, TypeScript.VarFlags.Static)); + if(onlyStatics ? !isStaticDecl : isStaticDecl) { + continue; + } + this.emitJavascript(emitNode, tokenId, startLine); + if(delimiter && (i < (len - 1))) { + if(startLine) { + this.writeLineToOutput(delimiter); + } else { + this.writeToOutput(delimiter); + } + } else { + if(startLine && (emitNode.nodeType != TypeScript.NodeType.ModuleDeclaration) && (emitNode.nodeType != TypeScript.NodeType.InterfaceDeclaration) && (!((emitNode.nodeType == TypeScript.NodeType.VarDecl) && ((((emitNode).varFlags) & TypeScript.VarFlags.Ambient) == TypeScript.VarFlags.Ambient) && (((emitNode).init) == null)) && this.varListCount() >= 0) && (emitNode.nodeType != TypeScript.NodeType.Block || (emitNode).isStatementBlock) && (emitNode.nodeType != TypeScript.NodeType.EndCode) && (emitNode.nodeType != TypeScript.NodeType.FuncDecl)) { + this.writeLineToOutput(""); + } + } + } + this.emitParensAndCommentsInPlace(ast, false); + } + } + }; + Emitter.prototype.emitJavascript = function (ast, tokenId, startLine) { + if(ast == null) { + return; + } + if(startLine && (this.indenter.indentAmt > 0) && (ast.nodeType != TypeScript.NodeType.List) && (ast.nodeType != TypeScript.NodeType.Block)) { + if((ast.nodeType != TypeScript.NodeType.InterfaceDeclaration) && (!((ast.nodeType == TypeScript.NodeType.VarDecl) && ((((ast).varFlags) & TypeScript.VarFlags.Ambient) == TypeScript.VarFlags.Ambient) && (((ast).init) == null)) && this.varListCount() >= 0) && (ast.nodeType != TypeScript.NodeType.EndCode) && ((ast.nodeType != TypeScript.NodeType.FuncDecl) || (this.emitState.container != EmitContainer.Constructor))) { + this.emitIndent(); + } + } + ast.emit(this, tokenId, startLine); + if((tokenId == TypeScript.TokenID.Semicolon) && (ast.nodeType < TypeScript.NodeType.GeneralNode)) { + this.writeToOutput(";"); + } + }; + Emitter.prototype.emitPropertyAccessor = function (funcDecl, className, isProto) { + if(!(funcDecl.accessorSymbol).hasBeenEmitted) { + var accessorSymbol = funcDecl.accessorSymbol; + this.emitIndent(); + this.recordSourceMappingStart(funcDecl); + this.writeLineToOutput("Object.defineProperty(" + className + (isProto ? ".prototype, \"" : ", \"") + funcDecl.name.actualText + "\"" + ", {"); + this.indenter.increaseIndent(); + if(accessorSymbol.getter) { + var getter = accessorSymbol.getter.declAST; + this.emitIndent(); + this.recordSourceMappingStart(getter); + this.writeToOutput("get: "); + this.emitInnerFunction(getter, false, isProto, null, Emitter.shouldCaptureThis(getter), null); + this.writeLineToOutput(","); + } + if(accessorSymbol.setter) { + var setter = accessorSymbol.setter.declAST; + this.emitIndent(); + this.recordSourceMappingStart(setter); + this.writeToOutput("set: "); + this.emitInnerFunction(setter, false, isProto, null, Emitter.shouldCaptureThis(setter), null); + this.writeLineToOutput(","); + } + this.emitIndent(); + this.writeLineToOutput("enumerable: true,"); + this.emitIndent(); + this.writeLineToOutput("configurable: true"); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeLineToOutput("});"); + this.recordSourceMappingEnd(funcDecl); + accessorSymbol.hasBeenEmitted = true; + } + }; + Emitter.prototype.emitPrototypeMember = function (member, className) { + if(member.nodeType == TypeScript.NodeType.FuncDecl) { + var funcDecl = member; + if(funcDecl.isAccessor()) { + this.emitPropertyAccessor(funcDecl, className, true); + } else { + this.emitIndent(); + this.recordSourceMappingStart(funcDecl); + this.writeToOutput(className + ".prototype." + funcDecl.getNameText() + " = "); + this.emitInnerFunction(funcDecl, false, true, null, Emitter.shouldCaptureThis(funcDecl), null); + this.writeLineToOutput(";"); + } + } else { + if(member.nodeType == TypeScript.NodeType.VarDecl) { + var varDecl = member; + if(varDecl.init) { + this.emitIndent(); + this.recordSourceMappingStart(varDecl); + this.recordSourceMappingStart(varDecl.id); + this.writeToOutput(className + ".prototype." + varDecl.id.actualText); + this.recordSourceMappingEnd(varDecl.id); + this.writeToOutput(" = "); + this.emitJavascript(varDecl.init, TypeScript.TokenID.Equals, false); + this.recordSourceMappingEnd(varDecl); + this.writeLineToOutput(";"); + } + } + } + }; + Emitter.prototype.emitAddBaseMethods = function (className, base, classDecl) { + if(base.members) { + var baseSymbol = base.symbol; + var baseName = baseSymbol.name; + if(baseSymbol.declModule != classDecl.type.symbol.declModule) { + baseName = baseSymbol.fullName(); + } + base.members.allMembers.map(function (key, s, c) { + var sym = s; + if((sym.kind() == TypeScript.SymbolKind.Type) && (sym).type.call) { + this.recordSourceMappingStart(sym.declAST); + this.writeLineToOutput(className + ".prototype." + sym.name + " = " + baseName + ".prototype." + sym.name + ";"); + this.recordSourceMappingEnd(sym.declAST); + } + }, null); + } + if(base.extendsList) { + for(var i = 0, len = base.extendsList.length; i < len; i++) { + this.emitAddBaseMethods(className, base.extendsList[i], classDecl); + } + } + }; + Emitter.prototype.emitJavascriptClass = function (classDecl) { + if(!TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Ambient)) { + var svClassNode = this.thisClassNode; + var i = 0; + this.thisClassNode = classDecl; + var className = classDecl.name.actualText; + this.emitParensAndCommentsInPlace(classDecl, true); + var temp = this.setContainer(EmitContainer.Class); + this.recordSourceMappingStart(classDecl); + if(TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Exported) && classDecl.type.symbol.container == this.checker.gloMod) { + this.writeToOutput("this." + className); + } else { + this.writeToOutput("var " + className); + } + var hasBaseClass = classDecl.extendsList && classDecl.extendsList.members.length; + var baseNameDecl = null; + var baseName = null; + if(hasBaseClass) { + this.writeLineToOutput(" = (function (_super) {"); + } else { + this.writeLineToOutput(" = (function () {"); + } + this.recordSourceMappingNameStart(className); + this.indenter.increaseIndent(); + if(hasBaseClass) { + baseNameDecl = classDecl.extendsList.members[0]; + baseName = baseNameDecl.nodeType == TypeScript.NodeType.Call ? (baseNameDecl).target : baseNameDecl; + this.emitIndent(); + this.writeLineToOutput("__extends(" + className + ", _super);"); + } + this.emitIndent(); + var constrDecl = classDecl.constructorDecl; + if(constrDecl) { + this.emitJavascript(classDecl.constructorDecl, TypeScript.TokenID.OpenParen, false); + } else { + var wroteProps = 0; + this.recordSourceMappingStart(classDecl); + this.indenter.increaseIndent(); + this.writeToOutput("function " + classDecl.name.actualText + "() {"); + this.recordSourceMappingNameStart("constructor"); + if(hasBaseClass) { + this.writeLineToOutput(""); + this.emitIndent(); + this.writeLineToOutput("_super.apply(this, arguments);"); + wroteProps++; + } + if(classDecl.varFlags & TypeScript.VarFlags.MustCaptureThis) { + this.writeCaptureThisStatement(classDecl); + } + var members = (this.thisClassNode.members).members; + for(var i = 0; i < members.length; i++) { + if(members[i].nodeType == TypeScript.NodeType.VarDecl) { + var varDecl = members[i]; + if(!TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static) && varDecl.init) { + this.writeLineToOutput(""); + this.emitIndent(); + this.emitJavascriptVarDecl(varDecl, TypeScript.TokenID.Tilde); + wroteProps++; + } + } + } + if(wroteProps) { + this.writeLineToOutput(""); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeLineToOutput("}"); + } else { + this.writeLineToOutput(" }"); + this.indenter.decreaseIndent(); + } + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(classDecl); + } + var membersLen = classDecl.members.members.length; + for(var j = 0; j < membersLen; j++) { + var memberDecl = classDecl.members.members[j]; + if(memberDecl.nodeType == TypeScript.NodeType.FuncDecl) { + var fn = memberDecl; + if(TypeScript.hasFlag(fn.fncFlags, TypeScript.FncFlags.Method) && !fn.isSignature()) { + if(!TypeScript.hasFlag(fn.fncFlags, TypeScript.FncFlags.Static)) { + this.emitPrototypeMember(fn, className); + } else { + if(fn.isAccessor()) { + this.emitPropertyAccessor(fn, this.thisClassNode.name.actualText, false); + } else { + this.emitIndent(); + this.recordSourceMappingStart(fn); + this.writeToOutput(classDecl.name.actualText + "." + fn.name.actualText + " = "); + this.emitInnerFunction(fn, (fn.name && !fn.name.isMissing()), true, null, Emitter.shouldCaptureThis(fn), null); + this.writeLineToOutput(";"); + } + } + } + } else { + if(memberDecl.nodeType == TypeScript.NodeType.VarDecl) { + var varDecl = memberDecl; + if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static)) { + if(varDecl.init) { + this.emitIndent(); + this.recordSourceMappingStart(varDecl); + this.writeToOutput(classDecl.name.actualText + "." + varDecl.id.actualText + " = "); + this.emitJavascript(varDecl.init, TypeScript.TokenID.Equals, false); + this.writeLineToOutput(";"); + this.recordSourceMappingEnd(varDecl); + } + } + } else { + throw Error("We want to catch this"); + } + } + } + this.emitIndent(); + this.recordSourceMappingStart(classDecl.endingToken); + this.writeLineToOutput("return " + className + ";"); + this.recordSourceMappingEnd(classDecl.endingToken); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.recordSourceMappingStart(classDecl.endingToken); + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(classDecl.endingToken); + this.recordSourceMappingStart(classDecl); + this.writeToOutput(")("); + if(hasBaseClass) { + this.emitJavascript(baseName, TypeScript.TokenID.Tilde, false); + } + this.writeToOutput(");"); + this.recordSourceMappingEnd(classDecl); + if((temp == EmitContainer.Module || temp == EmitContainer.DynamicModule) && TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Exported)) { + this.writeLineToOutput(""); + this.emitIndent(); + var modName = temp == EmitContainer.Module ? this.moduleName : "exports"; + this.recordSourceMappingStart(classDecl); + this.writeToOutput(modName + "." + className + " = " + className + ";"); + this.recordSourceMappingEnd(classDecl); + } + this.emitIndent(); + this.recordSourceMappingEnd(classDecl); + this.emitParensAndCommentsInPlace(classDecl, false); + this.setContainer(temp); + this.thisClassNode = svClassNode; + } + }; + Emitter.prototype.emitPrologue = function (reqInherits) { + if(!this.prologueEmitted) { + if(reqInherits) { + this.prologueEmitted = true; + this.writeLineToOutput("var __extends = this.__extends || function (d, b) {"); + this.writeLineToOutput(" function __() { this.constructor = d; }"); + this.writeLineToOutput(" __.prototype = b.prototype;"); + this.writeLineToOutput(" d.prototype = new __();"); + this.writeLineToOutput("};"); + } + if(this.checker.mustCaptureGlobalThis) { + this.prologueEmitted = true; + this.writeLineToOutput(this.captureThisStmtString); + } + } + }; + Emitter.prototype.emitSuperReference = function () { + this.writeToOutput("_super.prototype"); + }; + Emitter.prototype.emitSuperCall = function (callEx) { + if(callEx.target.nodeType == TypeScript.NodeType.Dot) { + var dotNode = callEx.target; + if(dotNode.operand1.nodeType == TypeScript.NodeType.Super) { + this.emitJavascript(dotNode, TypeScript.TokenID.OpenParen, false); + this.writeToOutput(".call("); + this.emitThis(); + if(callEx.arguments && callEx.arguments.members.length > 0) { + this.writeToOutput(", "); + this.emitJavascriptList(callEx.arguments, ", ", TypeScript.TokenID.Comma, false, false, false); + } + this.writeToOutput(")"); + return true; + } + } + return false; + }; + Emitter.prototype.emitThis = function () { + if(this.thisFnc && !this.thisFnc.isMethod() && (!this.thisFnc.isConstructor)) { + this.writeToOutput("_this"); + } else { + this.writeToOutput("this"); + } + }; + Emitter.shouldCaptureThis = function shouldCaptureThis(func) { + return func.hasSelfReference() || func.hasSuperReferenceInFatArrowFunction(); + } + Emitter.prototype.createFile = function (fileName, useUTF8) { + try { + return this.emitOptions.ioHost.createFile(fileName, useUTF8); + } catch (ex) { + this.errorReporter.emitterError(null, ex.message); + } + }; + return Emitter; + })(); + TypeScript.Emitter = Emitter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ErrorReporter = (function () { + function ErrorReporter(outfile) { + this.outfile = outfile; + this.parser = null; + this.checker = null; + this.lineCol = { + line: 0, + col: 0 + }; + this.emitAsComments = true; + this.hasErrors = false; + this.pushToErrorSink = false; + this.errorSink = []; + } + ErrorReporter.prototype.getCapturedErrors = function () { + return this.errorSink; + }; + ErrorReporter.prototype.freeCapturedErrors = function () { + this.errorSink = []; + }; + ErrorReporter.prototype.captureError = function (emsg) { + this.errorSink[this.errorSink.length] = emsg; + }; + ErrorReporter.prototype.setErrOut = function (outerr) { + this.outfile = outerr; + this.emitAsComments = false; + }; + ErrorReporter.prototype.emitPrefix = function () { + if(this.emitAsComments) { + this.outfile.Write("// "); + } + this.outfile.Write(this.checker.locationInfo.filename + "(" + this.lineCol.line + "," + this.lineCol.col + "): "); + }; + ErrorReporter.prototype.writePrefix = function (ast) { + if(ast) { + this.setError(ast); + } else { + this.lineCol.line = 0; + this.lineCol.col = 0; + } + this.emitPrefix(); + }; + ErrorReporter.prototype.writePrefixFromSym = function (symbol) { + if(symbol && this.checker.locationInfo.lineMap) { + TypeScript.getSourceLineColFromMap(this.lineCol, symbol.location, this.checker.locationInfo.lineMap); + } else { + this.lineCol.line = -1; + this.lineCol.col = -1; + } + this.emitPrefix(); + }; + ErrorReporter.prototype.setError = function (ast) { + if(ast) { + ast.flags |= TypeScript.ASTFlags.Error; + if(this.checker.locationInfo.lineMap) { + TypeScript.getSourceLineColFromMap(this.lineCol, ast.minChar, this.checker.locationInfo.lineMap); + } + } + }; + ErrorReporter.prototype.reportError = function (ast, message) { + if(this.pushToErrorSink) { + this.captureError(message); + return; + } + this.hasErrors = true; + if(ast && this.parser.errorRecovery && this.parser.errorCallback) { + var len = (ast.limChar - ast.minChar); + this.parser.errorCallback(ast.minChar, len, message, this.checker.locationInfo.unitIndex); + } else { + this.writePrefix(ast); + this.outfile.WriteLine(message); + } + }; + ErrorReporter.prototype.reportErrorFromSym = function (symbol, message) { + if(this.pushToErrorSink) { + this.captureError(message); + return; + } + this.hasErrors = true; + if(this.parser.errorRecovery && this.parser.errorCallback) { + this.parser.errorCallback(symbol.location, symbol.length, message, this.checker.locationInfo.unitIndex); + } else { + this.writePrefixFromSym(symbol); + this.outfile.WriteLine(message); + } + }; + ErrorReporter.prototype.emitterError = function (ast, message) { + this.reportError(ast, message); + throw Error("EmitError"); + }; + ErrorReporter.prototype.duplicateIdentifier = function (ast, name) { + this.reportError(ast, "Duplicate identifier '" + name + "'"); + }; + ErrorReporter.prototype.showRef = function (ast, text, symbol) { + var defLineCol = { + line: -1, + col: -1 + }; + this.parser.getSourceLineCol(defLineCol, symbol.location); + this.reportError(ast, "symbol " + text + " defined at (" + defLineCol.line + "," + defLineCol.col + ")"); + }; + ErrorReporter.prototype.unresolvedSymbol = function (ast, name) { + this.reportError(ast, "The name '" + name + "' does not exist in the current scope"); + }; + ErrorReporter.prototype.symbolDoesNotReferToAValue = function (ast, name) { + this.reportError(ast, "The name '" + name + "' does not refer to a value"); + }; + ErrorReporter.prototype.styleError = function (ast, msg) { + var bkThrow = this.pushToErrorSink; + this.pushToErrorSink = false; + this.reportError(ast, "STYLE: " + msg); + this.pushToErrorSink = bkThrow; + }; + ErrorReporter.prototype.simpleError = function (ast, msg) { + this.reportError(ast, msg); + }; + ErrorReporter.prototype.simpleErrorFromSym = function (sym, msg) { + this.reportErrorFromSym(sym, msg); + }; + ErrorReporter.prototype.invalidSuperReference = function (ast) { + this.simpleError(ast, "Keyword 'super' can only be used inside a class instance method"); + }; + ErrorReporter.prototype.valueCannotBeModified = function (ast) { + this.simpleError(ast, "The left-hand side of an assignment expression must be a variable, property or indexer"); + }; + ErrorReporter.prototype.invalidCall = function (ast, nodeType, scope) { + var targetType = ast.target.type; + var typeName = targetType.getScopedTypeName(scope); + if(targetType.construct && (nodeType == TypeScript.NodeType.Call)) { + this.reportError(ast, "Value of type '" + typeName + "' is not callable. Did you mean to include 'new'?"); + } else { + var catString = (nodeType == TypeScript.NodeType.Call) ? "callable" : "newable"; + this.reportError(ast, "Value of type '" + typeName + "' is not " + catString); + } + }; + ErrorReporter.prototype.indexLHS = function (ast, scope) { + var targetType = ast.operand1.type.getScopedTypeName(scope); + var indexType = ast.operand2.type.getScopedTypeName(scope); + this.simpleError(ast, "Value of type '" + targetType + "' is not indexable by type '" + indexType + "'"); + }; + ErrorReporter.prototype.incompatibleTypes = function (ast, t1, t2, op, scope, comparisonInfo) { + if(!t1) { + t1 = this.checker.anyType; + } + if(!t2) { + t2 = this.checker.anyType; + } + var reason = comparisonInfo ? comparisonInfo.message : ""; + if(op) { + this.reportError(ast, "Operator '" + op + "' cannot be applied to types '" + t1.getScopedTypeName(scope) + "' and '" + t2.getScopedTypeName(scope) + "'" + (reason ? ": " + reason : "")); + } else { + this.reportError(ast, "Cannot convert '" + t1.getScopedTypeName(scope) + "' to '" + t2.getScopedTypeName(scope) + "'" + (reason ? ": " + reason : "")); + } + }; + ErrorReporter.prototype.expectedClassOrInterface = function (ast) { + this.simpleError(ast, "Expected var, class, interface, or module"); + }; + ErrorReporter.prototype.unaryOperatorTypeError = function (ast, op, type) { + this.reportError(ast, "Operator '" + op + "' cannot be applied to type '" + type.getTypeName() + "'"); + }; + return ErrorReporter; + })(); + TypeScript.ErrorReporter = ErrorReporter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (TypeContext) { + TypeContext._map = []; + TypeContext.NoTypes = 0; + TypeContext.ArraySuffix = 1; + TypeContext.Primitive = 2; + TypeContext.Named = 4; + TypeContext.AllSimpleTypes = TypeContext.Primitive | TypeContext.Named; + TypeContext.AllTypes = TypeContext.Primitive | TypeContext.Named | TypeContext.ArraySuffix; + })(TypeScript.TypeContext || (TypeScript.TypeContext = {})); + var TypeContext = TypeScript.TypeContext; + (function (ParseState) { + ParseState._map = []; + ParseState._map[0] = "None"; + ParseState.None = 0; + ParseState._map[1] = "StartScript"; + ParseState.StartScript = 1; + ParseState._map[2] = "StartStatementList"; + ParseState.StartStatementList = 2; + ParseState._map[3] = "StartStatement"; + ParseState.StartStatement = 3; + ParseState._map[4] = "StartFncDecl"; + ParseState.StartFncDecl = 4; + ParseState._map[5] = "FncDeclName"; + ParseState.FncDeclName = 5; + ParseState._map[6] = "FncDeclArgs"; + ParseState.FncDeclArgs = 6; + ParseState._map[7] = "FncDeclReturnType"; + ParseState.FncDeclReturnType = 7; + ParseState._map[8] = "ForInit"; + ParseState.ForInit = 8; + ParseState._map[9] = "ForInitAfterVar"; + ParseState.ForInitAfterVar = 9; + ParseState._map[10] = "ForCondStart"; + ParseState.ForCondStart = 10; + ParseState._map[11] = "EndStmtList"; + ParseState.EndStmtList = 11; + ParseState._map[12] = "EndScript"; + ParseState.EndScript = 12; + })(TypeScript.ParseState || (TypeScript.ParseState = {})); + var ParseState = TypeScript.ParseState; + var QuickParseResult = (function () { + function QuickParseResult(Script, endLexState) { + this.Script = Script; + this.endLexState = endLexState; + } + return QuickParseResult; + })(); + TypeScript.QuickParseResult = QuickParseResult; + var Parser = (function () { + function Parser() { + this.varLists = []; + this.scopeLists = []; + this.staticsLists = []; + this.scanner = new TypeScript.Scanner(); + this.currentToken = null; + this.needTerminator = false; + this.inFunction = false; + this.inInterfaceDecl = false; + this.currentClassDecl = null; + this.inFncDecl = false; + this.anonId = new TypeScript.Identifier("_anonymous"); + this.style_requireSemi = false; + this.style_funcInLoop = true; + this.incremental = false; + this.errorRecovery = false; + this.outfile = undefined; + this.errorCallback = null; + this.state = ParseState.StartStatementList; + this.ambientModule = false; + this.ambientClass = false; + this.topLevel = true; + this.allowImportDeclaration = true; + this.currentUnitIndex = (-1); + this.prevIDTok = null; + this.statementInfoStack = new Array(); + this.hasTopLevelImportOrExport = false; + this.strictMode = false; + this.nestingLevel = 0; + this.prevExpr = null; + this.currentClassDefinition = null; + this.parsingClassConstructorDefinition = false; + this.parsingDeclareFile = false; + this.amdDependencies = []; + this.inferPropertiesFromThisAssignment = false; + this.requiresExtendsBlock = false; + this.fname = ""; + } + Parser.prototype.resetStmtStack = function () { + this.statementInfoStack = new Array(); + }; + Parser.prototype.inLoop = function () { + for(var j = this.statementInfoStack.length - 1; j >= 0; j--) { + if(this.statementInfoStack[j].stmt.isLoop()) { + return true; + } + } + return false; + }; + Parser.prototype.pushStmt = function (stmt, labels) { + var info = { + stmt: stmt, + labels: labels + }; + this.statementInfoStack.push(info); + }; + Parser.prototype.popStmt = function () { + return this.statementInfoStack.pop(); + }; + Parser.prototype.resolveJumpTarget = function (jump) { + var resolvedTarget = TypeScript.AST.getResolvedIdentifierName(jump.target); + var len = this.statementInfoStack.length; + for(var i = len - 1; i >= 0; i--) { + var info = this.statementInfoStack[i]; + if(jump.target) { + if(info.labels && (info.labels.members.length > 0)) { + for(var j = 0, labLen = info.labels.members.length; j < labLen; j++) { + var label = info.labels.members[j]; + if(label.id.text == resolvedTarget) { + jump.setResolvedTarget(this, info.stmt); + return; + } + } + } + } else { + if(info.stmt.isLoop()) { + jump.setResolvedTarget(this, info.stmt); + return; + } else { + if((info.stmt.nodeType == TypeScript.NodeType.Switch) && (jump.nodeType == TypeScript.NodeType.Break)) { + jump.setResolvedTarget(this, info.stmt); + return; + } + } + } + } + if(jump.target) { + this.reportParseError("could not find enclosing statement with label " + jump.target); + } else { + if(jump.nodeType == TypeScript.NodeType.Break) { + this.reportParseError("break statement requires enclosing loop or switch"); + } else { + this.reportParseError("continue statement requires enclosing loop"); + } + } + }; + Parser.prototype.setErrorRecovery = function (outfile) { + this.outfile = outfile; + this.errorRecovery = true; + }; + Parser.prototype.getSourceLineCol = function (lineCol, minChar) { + TypeScript.getSourceLineColFromMap(lineCol, minChar, this.scanner.lineMap); + }; + Parser.prototype.createRef = function (text, hasEscapeSequence, minChar) { + var id = new TypeScript.Identifier(text, hasEscapeSequence); + id.minChar = minChar; + return id; + }; + Parser.prototype.reportParseStyleError = function (message) { + this.reportParseError("STYLE: " + message); + }; + Parser.prototype.reportParseError = function (message, startPos, pos) { + if (typeof startPos === "undefined") { startPos = this.scanner.startPos; } + if (typeof pos === "undefined") { pos = this.scanner.pos; } + var len = Math.max(1, pos - startPos); + if(this.errorCallback) { + this.errorCallback(startPos, len, message, this.currentUnitIndex); + } else { + if(this.errorRecovery) { + var lineCol = { + line: -1, + col: -1 + }; + this.getSourceLineCol(lineCol, startPos); + if(this.outfile) { + this.outfile.WriteLine("// " + this.fname + " (" + lineCol.line + "," + lineCol.col + "): " + message); + } + } else { + throw new SyntaxError(this.fname + " (" + this.scanner.line + "," + this.scanner.col + "): " + message); + } + } + }; + Parser.prototype.checkNextToken = function (tokenId, errorRecoverySet, errorText) { + if (typeof errorText === "undefined") { errorText = null; } + this.currentToken = this.scanner.scan(); + this.checkCurrentToken(tokenId, errorRecoverySet, errorText); + }; + Parser.prototype.skip = function (errorRecoverySet) { + errorRecoverySet |= TypeScript.ErrorRecoverySet.EOF; + var ersTok = TypeScript.ErrorRecoverySet.None; + var tokenInfo = TypeScript.lookupToken(this.currentToken.tokenId); + if(tokenInfo != undefined) { + ersTok = tokenInfo.ers; + } + var pendingRightCurlies = 0; + while(((ersTok & errorRecoverySet) == TypeScript.ErrorRecoverySet.None) || (this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) && (pendingRightCurlies > 0)) { + if(this.currentToken.tokenId == TypeScript.TokenID.OpenBrace) { + pendingRightCurlies++; + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { + pendingRightCurlies--; + } + } + this.currentToken = this.scanner.scan(); + ersTok = TypeScript.ErrorRecoverySet.None; + tokenInfo = TypeScript.lookupToken(this.currentToken.tokenId); + if(tokenInfo != undefined) { + ersTok = tokenInfo.ers; + } + } + }; + Parser.prototype.checkCurrentToken = function (tokenId, errorRecoverySet, errorText) { + if (typeof errorText === "undefined") { errorText = null; } + if(this.currentToken.tokenId != tokenId) { + errorText = errorText == null ? ("Expected '" + TypeScript.tokenTable[tokenId].text + "'") : errorText; + this.reportParseError(errorText); + if(this.errorRecovery) { + this.skip(errorRecoverySet); + } + } else { + this.currentToken = this.scanner.scan(); + } + }; + Parser.prototype.pushDeclLists = function () { + this.staticsLists.push(new TypeScript.ASTList()); + this.varLists.push(new TypeScript.ASTList()); + this.scopeLists.push(new TypeScript.ASTList()); + }; + Parser.prototype.popDeclLists = function () { + this.staticsLists.pop(); + this.varLists.pop(); + this.scopeLists.pop(); + }; + Parser.prototype.topVarList = function () { + return this.varLists[this.varLists.length - 1]; + }; + Parser.prototype.topScopeList = function () { + return this.scopeLists[this.scopeLists.length - 1]; + }; + Parser.prototype.topStaticsList = function () { + return this.staticsLists[this.staticsLists.length - 1]; + }; + Parser.prototype.parseComment = function (comment) { + if(comment) { + var c = new TypeScript.Comment(comment.value, comment.isBlock, comment.endsLine); + c.minChar = comment.startPos; + c.limChar = comment.startPos + comment.value.length; + var lineCol = { + line: -1, + col: -1 + }; + this.getSourceLineCol(lineCol, c.minChar); + c.minLine = lineCol.line; + this.getSourceLineCol(lineCol, c.limChar); + c.limLine = lineCol.line; + if(!comment.isBlock && comment.value.length > 3 && comment.value.substring(0, 3) == "///") { + var dependencyPath = TypeScript.getAdditionalDependencyPath(comment.value); + if(dependencyPath) { + this.amdDependencies.push(dependencyPath); + } + if(TypeScript.getImplicitImport(comment.value)) { + this.hasTopLevelImportOrExport = true; + } + } + return c; + } else { + return null; + } + }; + Parser.prototype.parseCommentsInner = function (comments) { + if(comments) { + var commentASTs = new Array(); + for(var i = 0; i < comments.length; i++) { + commentASTs.push(this.parseComment(comments[i])); + } + return commentASTs; + } else { + return null; + } + }; + Parser.prototype.parseComments = function () { + var comments = this.scanner.getComments(); + return this.parseCommentsInner(comments); + }; + Parser.prototype.parseCommentsForLine = function (line) { + var comments = this.scanner.getCommentsForLine(line); + return this.parseCommentsInner(comments); + }; + Parser.prototype.combineComments = function (comment1, comment2) { + if(comment1 == null) { + return comment2; + } else { + if(comment2 == null) { + return comment1; + } else { + return comment1.concat(comment2); + } + } + }; + Parser.prototype.parseEnumDecl = function (errorRecoverySet, modifiers) { + var leftCurlyCount = this.scanner.leftCurlyCount; + var rightCurlyCount = this.scanner.rightCurlyCount; + var name = null; + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + name = TypeScript.Identifier.fromToken(this.currentToken); + name.minChar = this.scanner.startPos; + name.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + } else { + this.reportParseError("Enum declaration requires identifier"); + if(this.errorRecovery) { + name = new TypeScript.MissingIdentifier(); + name.minChar = this.scanner.startPos; + name.limChar = this.scanner.startPos; + name.flags |= TypeScript.ASTFlags.Error; + } + } + var membersMinChar = this.scanner.startPos; + this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.ID); + this.pushDeclLists(); + var members = new TypeScript.ASTList(); + members.minChar = membersMinChar; + var mapDecl = new TypeScript.VarDecl(new TypeScript.Identifier("_map"), 0); + mapDecl.varFlags |= TypeScript.VarFlags.Exported; + mapDecl.varFlags |= TypeScript.VarFlags.Private; + mapDecl.varFlags |= (TypeScript.VarFlags.Property | TypeScript.VarFlags.Public); + mapDecl.init = new TypeScript.UnaryExpression(TypeScript.NodeType.ArrayLit, null); + members.append(mapDecl); + var lastValue = null; + for(; ; ) { + var minChar = this.scanner.startPos; + var limChar; + var memberName = null; + var memberValue = null; + var preComments = null; + var postComments = null; + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToIDName(this.currentToken)) { + memberName = TypeScript.Identifier.fromToken(this.currentToken); + memberName.minChar = this.scanner.startPos; + memberName.limChar = this.scanner.pos; + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { + break; + } else { + this.reportParseError("Expected identifer of enum member"); + if(this.errorRecovery) { + memberName = new TypeScript.MissingIdentifier(); + memberName.minChar = this.scanner.startPos; + memberName.limChar = this.scanner.startPos; + memberName.flags |= TypeScript.ASTFlags.Error; + } + } + } + limChar = this.scanner.pos; + preComments = this.parseComments(); + this.currentToken = this.scanner.scan(); + postComments = this.parseComments(); + if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { + this.currentToken = this.scanner.scan(); + memberValue = this.parseExpr(errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); + lastValue = memberValue; + limChar = memberValue.limChar; + } else { + if(lastValue == null) { + memberValue = new TypeScript.NumberLiteral(0); + lastValue = memberValue; + } else { + memberValue = new TypeScript.NumberLiteral(lastValue.value + 1); + lastValue = memberValue; + } + var map = new TypeScript.BinaryExpression(TypeScript.NodeType.Asg, new TypeScript.BinaryExpression(TypeScript.NodeType.Index, new TypeScript.Identifier("_map"), memberValue), new TypeScript.StringLiteral('"' + memberName.actualText + '"')); + members.append(map); + } + var member = new TypeScript.VarDecl(memberName, this.nestingLevel); + member.minChar = minChar; + member.limChar = limChar; + member.init = memberValue; + member.typeExpr = new TypeScript.TypeReference(this.createRef(name.actualText, name.hasEscapeSequence, -1), 0); + member.varFlags |= (TypeScript.VarFlags.Readonly | TypeScript.VarFlags.Property); + if(memberValue.nodeType == TypeScript.NodeType.NumberLit) { + member.varFlags |= TypeScript.VarFlags.Constant; + } + member.preComments = preComments; + members.append(member); + member.postComments = postComments; + member.varFlags |= TypeScript.VarFlags.Exported; + if(this.currentToken.tokenId == TypeScript.TokenID.Comma) { + this.currentToken = this.scanner.scan(); + member.postComments = this.combineComments(member.postComments, this.parseCommentsForLine(this.scanner.prevLine)); + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || (TypeScript.convertTokToIDName(this.currentToken))) { + continue; + } + } + break; + } + var endingToken = new TypeScript.ASTSpan(); + endingToken.minChar = this.scanner.startPos; + endingToken.limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); + members.limChar = this.scanner.lastTokenLimChar(); + var modDecl = new TypeScript.ModuleDeclaration(name, members, this.topVarList(), this.topScopeList(), endingToken); + modDecl.modFlags |= TypeScript.ModuleFlags.IsEnum; + this.popDeclLists(); + modDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; + modDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; + return modDecl; + }; + Parser.prototype.parseDottedName = function (enclosedList) { + this.currentToken = this.scanner.scan(); + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + var id = TypeScript.Identifier.fromToken(this.currentToken); + id.preComments = this.parseComments(); + enclosedList[enclosedList.length] = id; + id.minChar = this.scanner.startPos; + id.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.Dot) { + this.parseDottedName(enclosedList); + } + } else { + this.reportParseError("need identifier after '.'"); + } + }; + Parser.prototype.isValidImportPath = function (importPath) { + importPath = TypeScript.stripQuotes(importPath); + if(!importPath || importPath.indexOf(':') != -1 || importPath.indexOf('\\') != -1 || importPath.charAt(0) == '/') { + return false; + } + return true; + }; + Parser.prototype.parseImportDeclaration = function (errorRecoverySet, modifiers) { + var name = null; + var alias = null; + var importDecl = null; + var minChar = this.scanner.startPos; + var isDynamicImport = false; + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + name = TypeScript.Identifier.fromToken(this.currentToken); + } else { + this.reportParseError("Expected identifer after 'import'"); + name = new TypeScript.MissingIdentifier(); + } + name.minChar = this.scanner.startPos; + name.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + this.checkCurrentToken(TypeScript.TokenID.Equals, errorRecoverySet | TypeScript.ErrorRecoverySet.ID); + var aliasPreComments = this.parseComments(); + var limChar; + if(this.currentToken.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + if(this.currentToken.tokenId == TypeScript.TokenID.Module) { + limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.StringLiteral || this.currentToken.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + if(this.currentToken.tokenId == TypeScript.TokenID.StringLiteral) { + if(this.topLevel) { + this.hasTopLevelImportOrExport = true; + } else { + if(!this.allowImportDeclaration) { + this.reportParseError("Import declaration of external module is permitted only in global or top level dynamic modules"); + } + } + var aliasText = this.currentToken.getText(); + alias = TypeScript.Identifier.fromToken(this.currentToken); + alias.minChar = this.scanner.startPos; + alias.limChar = this.scanner.pos; + if(!this.isValidImportPath((alias).text)) { + this.reportParseError("Invalid import path"); + } + isDynamicImport = true; + this.currentToken = this.scanner.scan(); + alias.preComments = aliasPreComments; + } else { + alias = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.Assignment, true, TypeContext.NoTypes); + alias.preComments = aliasPreComments; + } + } + limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ID); + if(alias) { + alias.postComments = this.parseComments(); + } + } + } else { + alias = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.Assignment, true, TypeContext.NoTypes); + limChar = this.scanner.pos; + } + } else { + this.reportParseError("Expected module name"); + alias = new TypeScript.MissingIdentifier(); + alias.minChar = this.scanner.startPos; + if(this.currentToken.tokenId == TypeScript.TokenID.Semicolon) { + alias.limChar = this.scanner.startPos; + } else { + alias.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + } + alias.flags |= TypeScript.ASTFlags.Error; + limChar = alias.limChar; + } + importDecl = new TypeScript.ImportDeclaration(name, alias); + importDecl.isDynamicImport = isDynamicImport; + importDecl.minChar = minChar; + importDecl.limChar = limChar; + return importDecl; + }; + Parser.prototype.parseModuleDecl = function (errorRecoverySet, modifiers, preComments) { + var leftCurlyCount = this.scanner.leftCurlyCount; + var rightCurlyCount = this.scanner.rightCurlyCount; + var svAmbient = this.ambientModule; + var svTopLevel = this.topLevel; + this.topLevel = false; + if(this.parsingDeclareFile || svAmbient || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + this.ambientModule = true; + } + this.currentToken = this.scanner.scan(); + var name = null; + var enclosedList = null; + this.pushDeclLists(); + var minChar = this.scanner.startPos; + var isDynamicMod = false; + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || (this.currentToken.tokenId == TypeScript.TokenID.StringLiteral) || (!TypeScript.isPrimitiveTypeToken(this.currentToken) && TypeScript.convertTokToID(this.currentToken, this.strictMode))) { + var nameText = this.currentToken.getText(); + if(this.currentToken.tokenId == TypeScript.TokenID.StringLiteral) { + isDynamicMod = true; + if(!this.ambientModule) { + this.reportParseError("Only ambient dynamic modules may have string literal names"); + } + if(!svTopLevel) { + this.reportParseError("Dynamic modules may not be nested within other modules"); + } + } + name = TypeScript.Identifier.fromToken(this.currentToken); + name.minChar = this.scanner.startPos; + name.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.OpenBrace) { + this.reportParseError("Module name missing"); + name = new TypeScript.Identifier(""); + name.minChar = minChar; + name.limChar = minChar; + } + } + if(this.currentToken.tokenId == TypeScript.TokenID.Dot) { + enclosedList = new Array(); + this.parseDottedName(enclosedList); + } + if(name == null) { + name = new TypeScript.MissingIdentifier(); + } + var moduleBody = new TypeScript.ASTList(); + var bodyMinChar = this.scanner.startPos; + this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.ID); + if(svTopLevel && isDynamicMod) { + this.allowImportDeclaration = true; + } else { + this.allowImportDeclaration = false; + } + this.parseStatementList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, moduleBody, true, true, TypeScript.AllowedElements.Global, modifiers); + moduleBody.minChar = bodyMinChar; + moduleBody.limChar = this.scanner.pos; + var endingToken = new TypeScript.ASTSpan(); + endingToken.minChar = this.scanner.startPos; + endingToken.limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); + var limChar = this.scanner.lastTokenLimChar(); + var moduleDecl; + this.allowImportDeclaration = svTopLevel; + if(enclosedList && (enclosedList.length > 0)) { + var len = enclosedList.length; + var innerName = enclosedList[len - 1]; + var innerDecl = new TypeScript.ModuleDeclaration(innerName, moduleBody, this.topVarList(), this.topScopeList(), endingToken); + innerDecl.preComments = preComments; + if(this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + innerDecl.modFlags |= TypeScript.ModuleFlags.Ambient; + } + innerDecl.modFlags |= TypeScript.ModuleFlags.Exported; + innerDecl.minChar = minChar; + innerDecl.limChar = limChar; + this.popDeclLists(); + var outerModBod; + for(var i = len - 2; i >= 0; i--) { + outerModBod = new TypeScript.ASTList(); + outerModBod.append(innerDecl); + innerName = enclosedList[i]; + innerDecl = new TypeScript.ModuleDeclaration(innerName, outerModBod, new TypeScript.ASTList(), new TypeScript.ASTList(), endingToken); + outerModBod.minChar = innerDecl.minChar = minChar; + outerModBod.limChar = innerDecl.limChar = limChar; + if(this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + innerDecl.modFlags |= TypeScript.ModuleFlags.Ambient; + } + innerDecl.modFlags |= TypeScript.ModuleFlags.Exported; + } + outerModBod = new TypeScript.ASTList(); + outerModBod.append(innerDecl); + outerModBod.minChar = minChar; + outerModBod.limChar = limChar; + moduleDecl = new TypeScript.ModuleDeclaration(name, outerModBod, new TypeScript.ASTList(), new TypeScript.ASTList(), endingToken); + } else { + moduleDecl = new TypeScript.ModuleDeclaration(name, moduleBody, this.topVarList(), this.topScopeList(), endingToken); + moduleDecl.preComments = preComments; + this.popDeclLists(); + } + if(this.parsingDeclareFile || svAmbient || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + moduleDecl.modFlags |= TypeScript.ModuleFlags.Ambient; + } + if(svAmbient || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { + moduleDecl.modFlags |= TypeScript.ModuleFlags.Exported; + } + if(isDynamicMod) { + moduleDecl.modFlags |= TypeScript.ModuleFlags.IsDynamic; + } + this.ambientModule = svAmbient; + this.topLevel = svTopLevel; + moduleDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; + moduleDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; + moduleDecl.limChar = moduleBody.limChar; + return moduleDecl; + }; + Parser.prototype.parseTypeReferenceTail = function (errorRecoverySet, minChar, term) { + var result = new TypeScript.TypeReference(term, 0); + result.minChar = minChar; + while(this.currentToken.tokenId == TypeScript.TokenID.OpenBracket) { + this.currentToken = this.scanner.scan(); + result.arrayCount++; + this.checkCurrentToken(TypeScript.TokenID.CloseBracket, errorRecoverySet | TypeScript.ErrorRecoverySet.LBrack); + } + result.limChar = this.scanner.lastTokenLimChar(); + return result; + }; + Parser.prototype.parseNamedType = function (errorRecoverySet, minChar, term, tail) { + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.Dot) { + var curpos = this.scanner.pos; + this.currentToken = this.scanner.scan(); + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || ((!this.errorRecovery || !this.scanner.lastTokenHadNewline()) && TypeScript.convertTokToID(this.currentToken, this.strictMode))) { + var op2 = TypeScript.Identifier.fromToken(this.currentToken); + op2.minChar = this.scanner.startPos; + op2.limChar = this.scanner.pos; + var dotNode = new TypeScript.BinaryExpression(TypeScript.NodeType.Dot, term, op2); + dotNode.minChar = term.minChar; + dotNode.limChar = op2.limChar; + return this.parseNamedType(errorRecoverySet, minChar, dotNode, tail); + } else { + this.reportParseError("need identifier after '.'"); + if(this.errorRecovery) { + term.flags |= TypeScript.ASTFlags.DotLHS; + term.limChar = this.scanner.lastTokenLimChar(); + return term; + } else { + var eop2 = new TypeScript.MissingIdentifier(); + eop2.minChar = this.scanner.pos; + eop2.limChar = this.scanner.pos; + var edotNode = new TypeScript.BinaryExpression(TypeScript.NodeType.Dot, term, eop2); + edotNode.flags |= TypeScript.ASTFlags.Error; + edotNode.minChar = term.minChar; + edotNode.limChar = eop2.limChar; + return this.parseNamedType(errorRecoverySet, minChar, edotNode, tail); + } + } + } else { + if(tail) { + return this.parseTypeReferenceTail(errorRecoverySet, minChar, term); + } else { + return term; + } + } + }; + Parser.prototype.parseTypeReference = function (errorRecoverySet, allowVoid) { + var minChar = this.scanner.startPos; + var isConstructorMember = false; + switch(this.currentToken.tokenId) { + case TypeScript.TokenID.Void: { + if(!allowVoid) { + this.reportParseError("void not a valid type in this context"); + } + + } + case TypeScript.TokenID.Any: + case TypeScript.TokenID.Number: + case TypeScript.TokenID.Bool: + case TypeScript.TokenID.String: { + var text = TypeScript.tokenTable[this.currentToken.tokenId].text; + var predefinedIdentifier = new TypeScript.Identifier(text); + predefinedIdentifier.minChar = minChar; + predefinedIdentifier.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + return this.parseTypeReferenceTail(errorRecoverySet, minChar, predefinedIdentifier); + } + + case TypeScript.TokenID.Identifier: { + var ident = this.createRef(this.currentToken.getText(), (this.currentToken).hasEscapeSequence, minChar); + ident.limChar = this.scanner.pos; + return this.parseNamedType(errorRecoverySet, minChar, ident, true); + + } + case TypeScript.TokenID.OpenBrace: { + return this.parseObjectType(minChar, errorRecoverySet); + + } + case TypeScript.TokenID.New: { + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId != TypeScript.TokenID.OpenParen) { + this.reportParseError("Expected '('"); + } else { + isConstructorMember = true; + } + + } + case TypeScript.TokenID.OpenParen: { + var formals = new TypeScript.ASTList(); + var variableArgList = this.parseFormalParameterList(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, formals, false, true, false, false, false, false, null, true); + this.checkCurrentToken(TypeScript.TokenID.EqualsGreaterThan, errorRecoverySet); + var returnType = this.parseTypeReference(errorRecoverySet, true); + var funcDecl = new TypeScript.FuncDecl(null, null, false, formals, null, null, null, TypeScript.NodeType.FuncDecl); + funcDecl.returnTypeAnnotation = returnType; + funcDecl.variableArgList = variableArgList; + funcDecl.fncFlags |= TypeScript.FncFlags.Signature; + if(isConstructorMember) { + funcDecl.fncFlags |= TypeScript.FncFlags.ConstructMember; + funcDecl.hint = "_construct"; + funcDecl.classDecl = null; + } + funcDecl.minChar = minChar; + return this.parseTypeReferenceTail(errorRecoverySet, minChar, funcDecl); + } + + default: { + this.reportParseError("Expected type name"); + var etr = new TypeScript.TypeReference(null, 0); + etr.flags |= TypeScript.ASTFlags.Error; + etr.minChar = this.scanner.pos; + etr.limChar = this.scanner.pos; + return etr; + + } + } + }; + Parser.prototype.parseObjectType = function (minChar, errorRecoverySet) { + this.currentToken = this.scanner.scan(); + var members = new TypeScript.ASTList(); + members.minChar = minChar; + var prevInInterfaceDecl = this.inInterfaceDecl; + this.inInterfaceDecl = true; + this.parseTypeMemberList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, members); + this.inInterfaceDecl = prevInInterfaceDecl; + this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); + var interfaceDecl = new TypeScript.InterfaceDeclaration(this.anonId, members, null, null); + interfaceDecl.minChar = minChar; + interfaceDecl.limChar = members.limChar; + return this.parseTypeReferenceTail(errorRecoverySet, minChar, interfaceDecl); + }; + Parser.prototype.parseFunctionBlock = function (errorRecoverySet, allowedElements, parentModifiers, bod, bodMinChar) { + this.state = ParseState.StartStatementList; + this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); + var savedInFunction = this.inFunction; + this.inFunction = true; + this.parseStatementList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly | TypeScript.ErrorRecoverySet.StmtStart, bod, true, false, allowedElements, parentModifiers); + bod.minChar = bodMinChar; + bod.limChar = this.scanner.pos; + this.inFunction = savedInFunction; + var ec = new TypeScript.EndCode(); + ec.minChar = bod.limChar; + ec.limChar = ec.minChar; + bod.append(ec); + }; + Parser.prototype.parseFunctionStatements = function (errorRecoverySet, name, isConstructor, isMethod, args, allowedElements, minChar, requiresSignature, parentModifiers) { + this.pushDeclLists(); + var svStmtStack = this.statementInfoStack; + this.resetStmtStack(); + var bod = null; + var wasShorthand = false; + var isAnonLambda = false; + var limChar; + if(requiresSignature) { + limChar = this.scanner.pos; + if(this.currentToken.tokenId === TypeScript.TokenID.OpenBrace) { + this.reportParseError("Function declarations are not permitted within interfaces, ambient modules or classes"); + bod = new TypeScript.ASTList(); + var bodMinChar = this.scanner.startPos; + this.parseFunctionBlock(errorRecoverySet, allowedElements, parentModifiers, bod, bodMinChar); + this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); + if(this.currentToken.tokenId === TypeScript.TokenID.Semicolon) { + this.currentToken = this.scanner.scan(); + } + } else { + this.checkCurrentToken(TypeScript.TokenID.Semicolon, errorRecoverySet, "Expected ';'"); + } + } else { + bod = new TypeScript.ASTList(); + var bodMinChar = this.scanner.startPos; + if(this.currentToken.tokenId == TypeScript.TokenID.EqualsGreaterThan) { + if(isMethod) { + this.reportParseError("'=>' may not be used for class methods"); + } + wasShorthand = true; + this.currentToken = this.scanner.scan(); + } + if(wasShorthand && this.currentToken.tokenId != TypeScript.TokenID.OpenBrace) { + var retExpr = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.Assignment, true, TypeContext.NoTypes); + var retStmt = new TypeScript.ReturnStatement(); + retStmt.returnExpression = retExpr; + retStmt.minChar = retExpr.minChar; + retStmt.limChar = retExpr.limChar; + bod.minChar = bodMinChar; + bod.append(retStmt); + } else { + isAnonLambda = wasShorthand; + this.parseFunctionBlock(errorRecoverySet, allowedElements, parentModifiers, bod, bodMinChar); + } + limChar = this.scanner.pos; + } + var funcDecl = new TypeScript.FuncDecl(name, bod, isConstructor, args, this.topVarList(), this.topScopeList(), this.topStaticsList(), TypeScript.NodeType.FuncDecl); + this.popDeclLists(); + var scopeList = this.topScopeList(); + scopeList.append(funcDecl); + var staticFuncDecl = false; + if(!requiresSignature) { + if(!wasShorthand || isAnonLambda) { + funcDecl.endingToken = new TypeScript.ASTSpan(); + funcDecl.endingToken.minChar = this.scanner.startPos; + funcDecl.endingToken.limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); + if(isAnonLambda) { + funcDecl.fncFlags |= TypeScript.FncFlags.IsFatArrowFunction; + } + } else { + funcDecl.fncFlags |= TypeScript.FncFlags.IsFatArrowFunction; + funcDecl.endingToken = new TypeScript.ASTSpan(); + funcDecl.endingToken.minChar = bod.members[0].minChar; + funcDecl.endingToken.limChar = bod.members[0].limChar; + } + } + funcDecl.minChar = minChar; + funcDecl.limChar = limChar; + if(!requiresSignature) { + funcDecl.fncFlags |= TypeScript.FncFlags.Definition; + } + this.statementInfoStack = svStmtStack; + return funcDecl; + }; + Parser.prototype.transformAnonymousArgsIntoFormals = function (formals, argList) { + var _this = this; + var translateBinExOperand = function (operand) { + if(operand.nodeType == TypeScript.NodeType.Comma) { + return _this.transformAnonymousArgsIntoFormals(formals, operand); + } else { + if(operand.nodeType == TypeScript.NodeType.Name || operand.nodeType == TypeScript.NodeType.Asg) { + var opArg = operand.nodeType == TypeScript.NodeType.Asg ? (operand).operand1 : operand; + var arg = new TypeScript.ArgDecl(opArg); + arg.preComments = opArg.preComments; + arg.postComments = opArg.postComments; + arg.minChar = operand.minChar; + arg.limChar = operand.limChar; + if(TypeScript.hasFlag(opArg.flags, TypeScript.ASTFlags.PossibleOptionalParameter)) { + arg.isOptional = true; + } + if(operand.nodeType == TypeScript.NodeType.Asg) { + arg.init = (operand).operand2; + } + formals.append(arg); + return arg.isOptional || arg.init; + } else { + _this.reportParseError("Invalid lambda argument"); + } + } + return false; + }; + if(argList) { + if(argList.nodeType == TypeScript.NodeType.Comma) { + var commaList = argList; + if(commaList.operand1.isParenthesized) { + this.reportParseError("Invalid lambda argument", commaList.operand1.minChar, commaList.operand1.limChar); + } + if(commaList.operand2.isParenthesized) { + this.reportParseError("Invalid lambda argument", commaList.operand2.minChar, commaList.operand2.limChar); + } + var isOptional = translateBinExOperand(commaList.operand1); + isOptional = translateBinExOperand(commaList.operand2) || isOptional; + return isOptional; + } else { + return translateBinExOperand(argList); + } + } + }; + Parser.prototype.parseFormalParameterList = function (errorRecoverySet, formals, isClassConstr, isSig, isIndexer, isGetter, isSetter, isLambda, preProcessedLambdaArgs, expectClosingRParen) { + formals.minChar = this.scanner.startPos; + if(isIndexer) { + this.currentToken = this.scanner.scan(); + } else { + if(!isLambda) { + this.checkCurrentToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.RParen); + } + } + var sawEllipsis = false; + var firstArg = true; + var hasOptional = false; + var haveFirstArgID = false; + if(isLambda && preProcessedLambdaArgs && preProcessedLambdaArgs.nodeType != TypeScript.NodeType.EmptyExpr) { + hasOptional = this.transformAnonymousArgsIntoFormals(formals, preProcessedLambdaArgs); + haveFirstArgID = true; + } + while(true) { + var munchedArg = false; + var argFlags = TypeScript.VarFlags.None; + var argMinChar = this.scanner.startPos; + if(this.inferPropertiesFromThisAssignment && this.currentToken.tokenId == TypeScript.TokenID.This) { + if(!isClassConstr) { + this.reportParseError("Instance property declarations using 'this' may only be used in class constructors"); + } + this.currentToken = this.scanner.scan(); + argFlags |= (TypeScript.VarFlags.Public | TypeScript.VarFlags.Property); + if(this.currentClassDefinition) { + this.currentClassDefinition.varFlags |= TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor; + } + } + if(this.currentToken.tokenId == TypeScript.TokenID.Public) { + argFlags |= (TypeScript.VarFlags.Public | TypeScript.VarFlags.Property); + if(this.currentClassDefinition) { + this.currentClassDefinition.varFlags |= TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor; + } + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.Private) { + argFlags |= (TypeScript.VarFlags.Private | TypeScript.VarFlags.Property); + if(this.currentClassDefinition) { + this.currentClassDefinition.varFlags |= TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor; + } + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.Static && isClassConstr) { + this.reportParseError("Static properties can not be declared as parameter properties"); + this.currentToken = this.scanner.scan(); + } + } + } + if(argFlags != TypeScript.VarFlags.None) { + if(!isClassConstr) { + this.reportParseError("only constructor parameters can be properties"); + } + this.currentToken = this.scanner.scan(); + if(TypeScript.isModifier(this.currentToken)) { + this.reportParseError("Multiple modifiers may not be applied to parameters"); + this.currentToken = this.scanner.scan(); + } + if(this.inferPropertiesFromThisAssignment && this.currentToken.tokenId == TypeScript.TokenID.This) { + if(!isClassConstr) { + this.reportParseError("Instance property declarations using 'this' may only be used in class constructors"); + } + this.currentToken = this.scanner.scan(); + this.currentToken = this.scanner.scan(); + } + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.DotDotDot) { + sawEllipsis = true; + this.currentToken = this.scanner.scan(); + if(!(this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + this.reportParseError("'...' parameters require both a parameter name and an array type annotation to be specified"); + sawEllipsis = false; + } + } + } + var argId = null; + if(!haveFirstArgID && (this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + argId = TypeScript.Identifier.fromToken(this.currentToken); + argId.minChar = this.scanner.startPos; + argId.limChar = this.scanner.pos; + } + if(haveFirstArgID || argId) { + munchedArg = true; + var type = null; + var arg = null; + if(haveFirstArgID && formals.members.length) { + arg = formals.members[formals.members.length - 1]; + if(arg.isOptional) { + hasOptional = true; + } + } else { + arg = new TypeScript.ArgDecl(argId); + if(isGetter) { + this.reportParseError("Property getters may not take any arguments"); + } + if(isSetter && !firstArg) { + this.reportParseError("Property setters may only take one argument"); + } + arg.minChar = argMinChar; + arg.preComments = this.parseComments(); + this.currentToken = this.scanner.scan(); + } + if(this.currentToken.tokenId == TypeScript.TokenID.Question) { + arg.isOptional = true; + hasOptional = true; + this.currentToken = this.scanner.scan(); + } + if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { + this.currentToken = this.scanner.scan(); + type = this.parseTypeReference(errorRecoverySet, false); + } + if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { + if(isSig) { + this.reportParseError("Arguments in signatures may not have default values"); + } + hasOptional = true; + this.currentToken = this.scanner.scan(); + arg.init = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, false, TypeContext.NoTypes); + } + if(hasOptional && !arg.isOptionalArg() && !sawEllipsis) { + this.reportParseError("Optional parameters may only be followed by other optional parameters"); + } + if(sawEllipsis && arg.isOptionalArg()) { + this.reportParseError("Varargs may not be optional or have default parameters"); + } + if(sawEllipsis && !type) { + this.reportParseError("'...' parameters require both a parameter name and an array type annotation to be specified"); + } + arg.postComments = this.parseComments(); + arg.typeExpr = type; + arg.limChar = this.scanner.lastTokenLimChar(); + arg.varFlags |= argFlags; + if(!haveFirstArgID) { + formals.append(arg); + } else { + haveFirstArgID = false; + } + } + firstArg = false; + if(this.currentToken.tokenId == TypeScript.TokenID.Comma) { + if((munchedArg) && (!sawEllipsis)) { + this.currentToken = this.scanner.scan(); + continue; + } else { + this.reportParseError("Unexpected ',' in argument list"); + if(this.errorRecovery) { + this.currentToken = this.scanner.scan(); + continue; + } + } + } else { + break; + } + } + if(isIndexer) { + this.checkCurrentToken(TypeScript.TokenID.CloseBracket, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly | TypeScript.ErrorRecoverySet.SColon); + } else { + if(expectClosingRParen) { + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly | TypeScript.ErrorRecoverySet.SColon); + } + } + formals.limChar = this.scanner.lastTokenLimChar(); + return sawEllipsis; + }; + Parser.prototype.parseFncDecl = function (errorRecoverySet, isDecl, requiresSignature, isMethod, methodName, indexer, isStatic, markedAsAmbient, modifiers, lambdaArgContext, expectClosingRParen) { + var leftCurlyCount = this.scanner.leftCurlyCount; + var rightCurlyCount = this.scanner.rightCurlyCount; + var prevInConstr = this.parsingClassConstructorDefinition; + this.parsingClassConstructorDefinition = false; + var name = null; + var fnMin = this.scanner.startPos; + var minChar = this.scanner.pos; + var prevNestingLevel = this.nestingLevel; + var preComments = this.parseComments(); + var isLambda = !!lambdaArgContext; + this.nestingLevel = 0; + if((!this.style_funcInLoop) && this.inLoop()) { + this.reportParseStyleError("function declaration in loop"); + } + if(!isMethod && !isStatic && !indexer && !lambdaArgContext) { + this.currentToken = this.scanner.scan(); + this.state = ParseState.StartFncDecl; + if((this.currentToken.tokenId != TypeScript.TokenID.Identifier) && (!TypeScript.convertTokToID(this.currentToken, this.strictMode))) { + if(isDecl) { + this.reportParseError("Function declaration must include identifier"); + this.nestingLevel = prevNestingLevel; + return new TypeScript.IncompleteAST(fnMin, this.scanner.pos); + } + } else { + name = TypeScript.Identifier.fromToken(this.currentToken); + name.minChar = this.scanner.startPos; + name.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + } + } else { + if(methodName) { + name = methodName; + } + } + this.state = ParseState.FncDeclName; + var args = new TypeScript.ASTList(); + var variableArgList = false; + var isOverload = false; + var isGetter = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter); + var isSetter = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Setter); + if((this.currentToken.tokenId == TypeScript.TokenID.OpenParen) || (indexer && (this.currentToken.tokenId == TypeScript.TokenID.OpenBracket)) || (lambdaArgContext && (lambdaArgContext.preProcessedLambdaArgs || this.currentToken.tokenId == TypeScript.TokenID.DotDotDot))) { + variableArgList = this.parseFormalParameterList(errorRecoverySet, args, false, requiresSignature, indexer, isGetter, isSetter, isLambda, lambdaArgContext ? lambdaArgContext.preProcessedLambdaArgs : null, expectClosingRParen); + } + this.state = ParseState.FncDeclArgs; + var returnType = null; + if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { + this.currentToken = this.scanner.scan(); + if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Setter)) { + this.reportParseError("Property setters may not declare a return type"); + } + returnType = this.parseTypeReference(errorRecoverySet, true); + } + if(indexer && args.members.length == 0) { + this.reportParseError("Index signatures require a parameter type to be specified"); + } + this.state = ParseState.FncDeclReturnType; + if(isLambda && this.currentToken.tokenId != TypeScript.TokenID.EqualsGreaterThan) { + this.reportParseError("Expected '=>'"); + } + if(isDecl && !(this.parsingDeclareFile || markedAsAmbient) && (!isMethod || !(this.ambientModule || this.ambientClass || this.inInterfaceDecl)) && this.currentToken.tokenId == TypeScript.TokenID.Semicolon) { + isOverload = true; + isDecl = false; + requiresSignature = true; + } + var svInFncDecl = this.inFncDecl; + this.inFncDecl = true; + var funcDecl = this.parseFunctionStatements(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, name, false, isMethod, args, TypeScript.AllowedElements.None, minChar, requiresSignature, TypeScript.Modifiers.None); + this.inFncDecl = svInFncDecl; + funcDecl.variableArgList = variableArgList; + funcDecl.isOverload = isOverload; + if(!requiresSignature) { + funcDecl.fncFlags |= TypeScript.FncFlags.Definition; + } + if(isStatic) { + funcDecl.fncFlags |= TypeScript.FncFlags.Static; + } + if(requiresSignature) { + funcDecl.fncFlags |= TypeScript.FncFlags.Signature; + } + if(indexer) { + funcDecl.fncFlags |= TypeScript.FncFlags.IndexerMember; + } + funcDecl.returnTypeAnnotation = returnType; + if(isMethod) { + funcDecl.fncFlags |= TypeScript.FncFlags.Method; + funcDecl.fncFlags |= TypeScript.FncFlags.ClassPropertyMethodExported; + } + funcDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; + funcDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; + this.nestingLevel = prevNestingLevel; + this.parsingClassConstructorDefinition = prevInConstr; + funcDecl.preComments = preComments; + return funcDecl; + }; + Parser.prototype.convertToTypeReference = function (ast) { + var result; + switch(ast.nodeType) { + case TypeScript.NodeType.TypeRef: { + return ast; + + } + case TypeScript.NodeType.Name: { + result = new TypeScript.TypeReference(ast, 0); + result.minChar = ast.minChar; + result.limChar = ast.limChar; + return result; + + } + case TypeScript.NodeType.Index: { + var expr = ast; + result = this.convertToTypeReference(expr.operand1); + if(result) { + result.arrayCount++; + result.minChar = expr.minChar; + result.limChar = expr.limChar; + return result; + } else { + var etr = new TypeScript.AST(TypeScript.NodeType.Error); + return etr; + } + } + + } + return null; + }; + Parser.prototype.parseArgList = function (errorRecoverySet) { + var args = new TypeScript.ASTList(); + args.minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId !== TypeScript.TokenID.CloseParen) { + while(true) { + if(args.members.length > 65535) { + this.reportParseError("max number of args exceeded"); + break; + } + var arg = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); + args.append(arg); + if(this.currentToken.tokenId != TypeScript.TokenID.Comma) { + break; + } + this.currentToken = this.scanner.scan(); + } + } + args.limChar = this.scanner.pos; + return args; + }; + Parser.prototype.parseBaseList = function (extendsList, implementsList, errorRecoverySet, isClass) { + var keyword = true; + var currentList = extendsList; + for(; ; ) { + if(keyword) { + if(this.currentToken.tokenId === TypeScript.TokenID.Implements) { + currentList = implementsList; + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.Extends && !this.requiresExtendsBlock) { + this.requiresExtendsBlock = isClass; + } + } + this.currentToken = this.scanner.scan(); + keyword = false; + } + var baseName = null; + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + var minChar = this.scanner.startPos; + baseName = TypeScript.Identifier.fromToken(this.currentToken); + baseName.minChar = minChar; + baseName.limChar = this.scanner.pos; + baseName = this.parseNamedType(errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly, minChar, baseName, false); + } else { + this.reportParseError("Expected base name"); + if(this.errorRecovery) { + baseName = new TypeScript.MissingIdentifier(); + baseName.minChar = this.scanner.pos; + baseName.limChar = this.scanner.pos; + baseName.flags |= TypeScript.ASTFlags.Error; + } + } + if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { + if(isClass) { + this.reportParseError("Base classes may only be initialized via a 'super' call within the constructor body"); + } else { + this.reportParseError("Interfaces may not be extended with a call expression"); + } + } else { + currentList.append(baseName); + } + if(isClass && currentList == extendsList && extendsList.members.length > 1) { + this.reportParseError("A class may only extend one other class"); + } + if(this.currentToken.tokenId == TypeScript.TokenID.Comma) { + this.currentToken = this.scanner.scan(); + continue; + } else { + if((this.currentToken.tokenId == TypeScript.TokenID.Extends) || (this.currentToken.tokenId == TypeScript.TokenID.Implements)) { + if(this.currentToken.tokenId == TypeScript.TokenID.Extends && !this.requiresExtendsBlock) { + this.requiresExtendsBlock = isClass; + } + currentList = extendsList; + keyword = true; + continue; + } + } + break; + } + }; + Parser.prototype.parseClassDecl = function (errorRecoverySet, minChar, modifiers) { + var leftCurlyCount = this.scanner.leftCurlyCount; + var rightCurlyCount = this.scanner.rightCurlyCount; + if((modifiers & TypeScript.Modifiers.Readonly) != TypeScript.Modifiers.None) { + this.reportParseError("const modifier is implicit for class"); + } + if(this.parsingDeclareFile || this.ambientModule) { + modifiers |= TypeScript.Modifiers.Ambient; + modifiers |= TypeScript.Modifiers.Exported; + } + var classIsMarkedAsAmbient = this.parsingDeclareFile || (modifiers & TypeScript.Modifiers.Ambient) != TypeScript.Modifiers.None; + var svAmbientClass = this.ambientClass; + this.ambientClass = classIsMarkedAsAmbient; + this.currentToken = this.scanner.scan(); + var name = null; + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || (!TypeScript.isPrimitiveTypeToken(this.currentToken) && TypeScript.convertTokToID(this.currentToken, this.strictMode))) { + name = TypeScript.Identifier.fromToken(this.currentToken); + name.minChar = this.scanner.startPos; + name.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + } else { + this.reportParseError("class missing name"); + if(this.errorRecovery) { + name = new TypeScript.MissingIdentifier(); + name.minChar = this.scanner.pos; + name.limChar = this.scanner.pos; + name.flags |= TypeScript.ASTFlags.Error; + } + } + var extendsList = null; + var implementsList = null; + var requiresSignature = false; + if((this.currentToken.tokenId == TypeScript.TokenID.Extends) || (this.currentToken.tokenId == TypeScript.TokenID.Implements)) { + extendsList = new TypeScript.ASTList(); + implementsList = new TypeScript.ASTList(); + this.parseBaseList(extendsList, implementsList, errorRecoverySet, true); + } + var classDecl = new TypeScript.ClassDeclaration(name, new TypeScript.ASTList(), extendsList, implementsList); + this.currentClassDefinition = classDecl; + this.parseClassElements(classDecl, errorRecoverySet, modifiers); + if(this.ambientModule || this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { + classDecl.varFlags |= TypeScript.VarFlags.Exported; + } + if(this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + classDecl.varFlags |= TypeScript.VarFlags.Ambient; + } + classDecl.varFlags |= TypeScript.VarFlags.Class; + this.ambientClass = svAmbientClass; + classDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; + classDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; + return classDecl; + }; + Parser.prototype.parseClassElements = function (classDecl, errorRecoverySet, parentModifiers) { + var modifiers = parentModifiers; + var resetModifiers = false; + var membersMinChar = this.scanner.startPos; + this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet); + this.nestingLevel++; + var currentMemberMinChar = this.scanner.startPos; + var wasGetOrSetId = false; + while(!(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace || this.currentToken.tokenId == TypeScript.TokenID.EndOfFile)) { + var scanNext = true; + var publicOrPrivateFlags = TypeScript.Modifiers.Public | TypeScript.Modifiers.Private; + if(this.currentToken.tokenId == TypeScript.TokenID.Get) { + if(modifiers & TypeScript.Modifiers.Getter) { + this.reportParseError("Duplicate 'get' declaration in class body"); + } + if(modifiers & TypeScript.Modifiers.Setter) { + this.reportParseError("Getter already marked as a setter"); + } + modifiers |= TypeScript.Modifiers.Getter; + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.Set) { + if(modifiers & TypeScript.Modifiers.Setter) { + this.reportParseError("Duplicate 'set' declaration in class body"); + } + if(modifiers & TypeScript.Modifiers.Getter) { + this.reportParseError("Setter already marked as a getter"); + } + modifiers |= TypeScript.Modifiers.Setter; + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.Private) { + if(modifiers & publicOrPrivateFlags) { + this.reportParseError("Multiple modifiers may not be applied to class members"); + } + modifiers |= TypeScript.Modifiers.Private; + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.Public) { + if(modifiers & publicOrPrivateFlags) { + this.reportParseError("Multiple modifiers may not be applied to class members"); + } + modifiers |= TypeScript.Modifiers.Public; + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.Static) { + if(modifiers & TypeScript.Modifiers.Static) { + this.reportParseError("Multiple modifiers may not be applied to class members"); + } + modifiers |= TypeScript.Modifiers.Static; + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.Constructor) { + if(modifiers != parentModifiers) { + this.reportParseError("Constructors may not have modifiers"); + } + this.parseClassConstructorDeclaration(currentMemberMinChar, errorRecoverySet, modifiers); + scanNext = false; + resetModifiers = true; + } else { + if(wasGetOrSetId || this.currentToken.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToIDName(this.currentToken)) { + var idText = wasGetOrSetId ? ((modifiers & TypeScript.Modifiers.Getter) ? "get" : "set") : this.currentToken.getText(); + var id = wasGetOrSetId ? new TypeScript.Identifier(idText) : TypeScript.Identifier.fromToken(this.currentToken); + id.minChar = this.scanner.startPos; + id.limChar = this.scanner.pos; + if(wasGetOrSetId) { + modifiers = modifiers ^ ((modifiers & TypeScript.Modifiers.Getter) ? TypeScript.Modifiers.Getter : TypeScript.Modifiers.Setter); + wasGetOrSetId = false; + } else { + this.currentToken = this.scanner.scan(); + } + if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { + this.parseClassMemberFunctionDeclaration(id, currentMemberMinChar, errorRecoverySet, modifiers); + scanNext = false; + } else { + if(modifiers & TypeScript.Modifiers.Getter || modifiers & TypeScript.Modifiers.Setter) { + this.reportParseError("Property accessors must be functions"); + } + var varDecl = this.parseClassMemberVariableDeclaration(id, currentMemberMinChar, false, errorRecoverySet, modifiers); + if(varDecl.init && varDecl.init.nodeType == TypeScript.NodeType.FuncDecl) { + if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { + scanNext = false; + } + } else { + if(varDecl.init && varDecl.init.nodeType == TypeScript.NodeType.ObjectLit && this.currentToken.tokenId != TypeScript.TokenID.Semicolon) { + scanNext = false; + varDecl.init.flags |= TypeScript.ASTFlags.AutomaticSemicolon; + } else { + if(this.currentToken.tokenId != TypeScript.TokenID.Semicolon) { + this.reportParseError("Expected ';'"); + scanNext = false; + } + } + } + } + resetModifiers = true; + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.Super) { + this.reportParseError("Base class initializers must be the first statement in a class definition"); + } else { + if(!wasGetOrSetId && ((modifiers & TypeScript.Modifiers.Getter) || (modifiers & TypeScript.Modifiers.Setter)) && ((this.currentToken.tokenId == TypeScript.TokenID.OpenParen) || (this.currentToken.tokenId == TypeScript.TokenID.Equals) || (this.currentToken.tokenId == TypeScript.TokenID.Colon) || (this.currentToken.tokenId == TypeScript.TokenID.Semicolon))) { + wasGetOrSetId = true; + scanNext = false; + } else { + if(this.currentToken.tokenId != TypeScript.TokenID.Semicolon) { + this.reportParseError("Unexpected '" + this.currentToken.getText() + "' in class definition"); + resetModifiers = true; + } + } + } + } + } + } + } + } + } + } + if(scanNext) { + this.currentToken = this.scanner.scan(); + } + if(resetModifiers) { + modifiers = parentModifiers; + currentMemberMinChar = this.scanner.startPos; + resetModifiers = false; + } + } + var membersLimChar = this.scanner.pos; + if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { + classDecl.endingToken = new TypeScript.ASTSpan(); + classDecl.endingToken.minChar = this.scanner.startPos; + classDecl.endingToken.limChar = this.scanner.pos; + if(!this.currentClassDefinition.members.members.length) { + this.currentClassDefinition.preComments = this.parseComments(); + } + this.currentToken = this.scanner.scan(); + } + this.nestingLevel--; + this.currentClassDefinition.members.minChar = membersMinChar; + this.currentClassDefinition.members.limChar = membersLimChar; + this.currentClassDefinition.limChar = membersLimChar; + this.currentClassDefinition = null; + }; + Parser.prototype.parseClassConstructorDeclaration = function (minChar, errorRecoverySet, modifiers) { + this.parsingClassConstructorDefinition = true; + var isAmbient = this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient); + var args = new TypeScript.ASTList(); + var variableArgList = false; + var preComments = this.parseComments(); + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { + variableArgList = this.parseFormalParameterList(errorRecoverySet, args, true, isAmbient, false, false, false, false, null, true); + if(args.members.length > 0) { + var lastArg = args.members[args.members.length - 1]; + } + } + var requiresSignature = isAmbient || this.currentToken.tokenId == TypeScript.TokenID.Semicolon; + if(requiresSignature) { + for(var i = 0; i < args.members.length; i++) { + var arg = args.members[i]; + if(TypeScript.hasFlag(arg.varFlags, TypeScript.VarFlags.Property)) { + this.reportParseError("Overload or ambient signatures may not specify parameter properties", arg.minChar, arg.limChar); + } + } + } + if(!requiresSignature) { + this.currentClassDefinition.constructorNestingLevel = this.nestingLevel + 1; + } + var constructorFuncDecl = this.parseFunctionStatements(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, this.currentClassDefinition.name, true, false, args, TypeScript.AllowedElements.Properties, minChar, requiresSignature, modifiers); + constructorFuncDecl.preComments = preComments; + if(requiresSignature && !isAmbient) { + constructorFuncDecl.isOverload = true; + } + constructorFuncDecl.variableArgList = variableArgList; + this.currentClassDecl = null; + constructorFuncDecl.returnTypeAnnotation = this.convertToTypeReference(this.currentClassDefinition.name); + constructorFuncDecl.classDecl = this.currentClassDefinition; + if(isAmbient) { + constructorFuncDecl.fncFlags |= TypeScript.FncFlags.Ambient; + } + if(requiresSignature) { + constructorFuncDecl.fncFlags |= TypeScript.FncFlags.Signature; + } + if(this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { + constructorFuncDecl.fncFlags |= TypeScript.FncFlags.Exported; + } + if(this.currentClassDefinition.constructorDecl) { + if(!isAmbient && !this.currentClassDefinition.constructorDecl.isSignature() && !constructorFuncDecl.isSignature()) { + this.reportParseError("Duplicate constructor definition"); + } + } + if(isAmbient || !constructorFuncDecl.isSignature()) { + this.currentClassDefinition.constructorDecl = constructorFuncDecl; + } + constructorFuncDecl.fncFlags |= TypeScript.FncFlags.ClassMethod; + this.currentClassDefinition.members.members[this.currentClassDefinition.members.members.length] = constructorFuncDecl; + this.parsingClassConstructorDefinition = false; + return constructorFuncDecl; + }; + Parser.prototype.parseClassMemberVariableDeclaration = function (text, minChar, isDeclaredInConstructor, errorRecoverySet, modifiers) { + var varDecl = new TypeScript.VarDecl(text, this.nestingLevel); + varDecl.minChar = minChar; + var isStatic = false; + varDecl.preComments = this.parseComments(); + if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { + this.currentToken = this.scanner.scan(); + varDecl.typeExpr = this.parseTypeReference(errorRecoverySet | TypeScript.ErrorRecoverySet.Asg | TypeScript.ErrorRecoverySet.Comma, false); + if(varDecl.typeExpr && varDecl.typeExpr.nodeType == TypeScript.NodeType.TypeRef) { + var typeExpr = (varDecl.typeExpr); + if(typeExpr.term && typeExpr.term.nodeType == TypeScript.NodeType.FuncDecl) { + typeExpr.term.preComments = varDecl.preComments; + } + } + } + if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { + if(this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + this.reportParseError("context does not permit variable initializer"); + if(this.errorRecovery) { + this.skip(errorRecoverySet); + varDecl.flags |= TypeScript.ASTFlags.Error; + varDecl.limChar = this.scanner.lastTokenLimChar(); + return varDecl; + } + } + this.currentToken = this.scanner.scan(); + varDecl.init = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); + varDecl.limChar = varDecl.init.limChar; + if(!(modifiers & TypeScript.Modifiers.Static)) { + this.currentClassDefinition.varFlags |= TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor; + } + } else { + varDecl.limChar = this.scanner.pos; + } + if(modifiers & TypeScript.Modifiers.Static) { + varDecl.varFlags |= TypeScript.VarFlags.Static; + isStatic = true; + } + if((modifiers & TypeScript.Modifiers.Private) != TypeScript.Modifiers.None) { + varDecl.varFlags |= TypeScript.VarFlags.Private; + } else { + varDecl.varFlags |= TypeScript.VarFlags.Public; + } + varDecl.varFlags |= TypeScript.VarFlags.Property; + if(isDeclaredInConstructor) { + varDecl.varFlags |= TypeScript.VarFlags.ClassConstructorProperty; + } + if(!isDeclaredInConstructor && !isStatic) { + varDecl.varFlags |= TypeScript.VarFlags.ClassBodyProperty; + } + this.currentClassDefinition.knownMemberNames[text.actualText] = true; + if(!isDeclaredInConstructor) { + this.currentClassDefinition.members.members[this.currentClassDefinition.members.members.length] = varDecl; + } + varDecl.postComments = this.parseComments(); + return varDecl; + }; + Parser.prototype.parseClassMemberFunctionDeclaration = function (methodName, minChar, errorRecoverySet, modifiers) { + var wasAccessorID = this.prevIDTok != null; + var isAccessor = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter) || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Setter); + var isStatic = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Static); + var isAmbient = this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient); + errorRecoverySet |= TypeScript.ErrorRecoverySet.RParen; + if(isAccessor && (modifiers & TypeScript.Modifiers.Ambient)) { + this.reportParseError("Property accessors may not be declared in ambient classes"); + } + var ast = this.parseFncDecl(errorRecoverySet, true, isAmbient, true, methodName, false, isStatic, isAmbient, modifiers, null, true); + if(ast.nodeType == TypeScript.NodeType.Error) { + return ast; + } + var funcDecl = ast; + funcDecl.minChar = minChar; + if(funcDecl.bod !== null) { + funcDecl.limChar = funcDecl.bod.limChar; + } + if(modifiers & TypeScript.Modifiers.Private) { + funcDecl.fncFlags |= TypeScript.FncFlags.Private; + } else { + funcDecl.fncFlags |= TypeScript.FncFlags.Public; + } + if(isStatic) { + funcDecl.fncFlags |= TypeScript.FncFlags.Static; + } + if(isAccessor) { + if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter)) { + funcDecl.fncFlags |= TypeScript.FncFlags.GetAccessor; + funcDecl.hint = "get" + funcDecl.name.actualText; + } else { + funcDecl.fncFlags |= TypeScript.FncFlags.SetAccessor; + funcDecl.hint = "set" + funcDecl.name.actualText; + } + funcDecl.fncFlags |= TypeScript.FncFlags.IsFunctionExpression; + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("Property accessors are only available when targeting ES5 or greater", funcDecl.minChar, funcDecl.limChar); + } + } + funcDecl.fncFlags |= TypeScript.FncFlags.ClassMethod; + this.currentClassDefinition.knownMemberNames[methodName.actualText] = true; + this.currentClassDefinition.members.members[this.currentClassDefinition.members.members.length] = funcDecl; + return funcDecl; + }; + Parser.prototype.parseTypeMember = function (errorRecoverySet) { + var minChar = this.scanner.startPos; + var propertyDecl = this.parsePropertyDeclaration(errorRecoverySet, TypeScript.Modifiers.Public, true, false); + if(propertyDecl) { + propertyDecl.minChar = minChar; + if(propertyDecl.nodeType == TypeScript.NodeType.VarDecl) { + this.checkCurrentToken(TypeScript.TokenID.Semicolon, errorRecoverySet); + } + } + return propertyDecl; + }; + Parser.prototype.parseTypeMemberList = function (errorRecoverySet, members) { + errorRecoverySet |= TypeScript.ErrorRecoverySet.TypeScriptS; + while(true) { + switch(this.currentToken.tokenId) { + case TypeScript.TokenID.CloseBrace: + case TypeScript.TokenID.EndOfFile: { + members.limChar = this.scanner.pos; + return; + + } + } + var element = this.parseTypeMember(errorRecoverySet); + if(element) { + members.append(element); + } + } + }; + Parser.prototype.parseInterfaceDecl = function (errorRecoverySet, modifiers) { + var leftCurlyCount = this.scanner.leftCurlyCount; + var rightCurlyCount = this.scanner.rightCurlyCount; + this.currentToken = this.scanner.scan(); + var minChar = this.scanner.pos; + var name = null; + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || (!TypeScript.isPrimitiveTypeToken(this.currentToken) && TypeScript.convertTokToID(this.currentToken, this.strictMode))) { + name = TypeScript.Identifier.fromToken(this.currentToken); + name.minChar = this.scanner.startPos; + name.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + } else { + this.reportParseError("interface missing name"); + if(this.errorRecovery) { + name = new TypeScript.MissingIdentifier(); + name.minChar = this.scanner.pos; + name.limChar = this.scanner.pos; + name.flags |= TypeScript.ASTFlags.Error; + } + } + var extendsList = null; + var implementsList = null; + if(this.currentToken.tokenId === TypeScript.TokenID.Extends || this.currentToken.tokenId === TypeScript.TokenID.Implements) { + if(this.currentToken.tokenId === TypeScript.TokenID.Implements) { + this.reportParseError("Expected 'extends'"); + } + extendsList = new TypeScript.ASTList(); + implementsList = new TypeScript.ASTList(); + extendsList.minChar = this.scanner.startPos; + this.parseBaseList(extendsList, implementsList, errorRecoverySet, false); + } + var membersMinChar = this.scanner.startPos; + this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.TypeScriptS); + var members = new TypeScript.ASTList(); + members.minChar = membersMinChar; + var prevInInterfaceDecl = this.inInterfaceDecl; + this.inInterfaceDecl = true; + this.parseTypeMemberList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, members); + this.inInterfaceDecl = prevInInterfaceDecl; + this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); + var interfaceDecl = new TypeScript.InterfaceDeclaration(name, members, extendsList, null); + if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Private)) { + interfaceDecl.varFlags |= TypeScript.VarFlags.Private; + } + if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Public)) { + interfaceDecl.varFlags |= TypeScript.VarFlags.Public; + } + if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { + interfaceDecl.varFlags |= TypeScript.VarFlags.Exported; + } + interfaceDecl.limChar = members.limChar; + interfaceDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; + interfaceDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; + return interfaceDecl; + }; + Parser.prototype.makeVarDecl = function (id, nest) { + var varDecl = new TypeScript.VarDecl(id, nest); + var currentVarList = this.topVarList(); + if(currentVarList) { + currentVarList.append(varDecl); + } + return varDecl; + }; + Parser.prototype.parsePropertyDeclaration = function (errorRecoverySet, modifiers, requireSignature, isStatic) { + var text = null; + var minChar = this.scanner.startPos; + var nameLimChar = minChar; + var isNew = false; + var isIndexer = false; + var wasAccessorID = this.prevIDTok != null; + var isAccessor = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter) || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Setter); + if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + requireSignature = true; + } + if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen && !wasAccessorID) { + if(!requireSignature && !isStatic) { + this.reportParseError("Expected identifier in property declaration"); + if(this.errorRecovery) { + this.skip(errorRecoverySet); + text = new TypeScript.MissingIdentifier(); + } + } + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.New) { + if(requireSignature) { + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { + isNew = true; + } + } + if(!isNew) { + if(!requireSignature) { + this.currentToken = this.scanner.scan(); + } + text = new TypeScript.Identifier("new"); + text.minChar = this.scanner.pos - 3; + text.limChar = this.scanner.pos; + nameLimChar = this.scanner.pos; + } + } else { + if((this.currentToken.tokenId == TypeScript.TokenID.OpenBracket) && requireSignature) { + isIndexer = true; + text = new TypeScript.Identifier("__item"); + } else { + if((this.currentToken.tokenId != TypeScript.TokenID.Identifier) && (!TypeScript.convertTokToIDName(this.currentToken)) && !wasAccessorID) { + this.reportParseError("Expected identifier in property declaration"); + if(this.errorRecovery) { + var eminChar = this.scanner.startPos; + var curpos = this.scanner.pos; + this.skip(errorRecoverySet & (~TypeScript.ErrorRecoverySet.Comma)); + if(this.scanner.pos == curpos) { + this.currentToken = this.scanner.scan(); + } + var epd = new TypeScript.VarDecl(new TypeScript.MissingIdentifier(), this.nestingLevel); + epd.flags |= TypeScript.ASTFlags.Error; + epd.minChar = eminChar; + epd.limChar = this.scanner.lastTokenLimChar(); + return epd; + } + } else { + if(wasAccessorID) { + text = TypeScript.Identifier.fromToken(this.prevIDTok); + text.minChar = this.scanner.lastTokenLimChar() - 3; + text.limChar = this.scanner.lastTokenLimChar(); + nameLimChar = text.limChar; + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("Property accessors are only available when targeting ES5 or greater"); + } + if(this.currentToken.getText() == text.actualText && this.currentToken != this.prevIDTok) { + this.currentToken = this.scanner.scan(); + } + this.prevIDTok = null; + } else { + text = TypeScript.Identifier.fromToken(this.currentToken); + text.minChar = this.scanner.startPos; + text.limChar = this.scanner.pos; + nameLimChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + } + } + } + } + } + if(this.currentToken.tokenId == TypeScript.TokenID.Question) { + if(this.inInterfaceDecl && text) { + text.flags |= TypeScript.ASTFlags.OptionalName; + } else { + this.reportParseError("Optional properties may only be declared on interface or object types"); + } + this.currentToken = this.scanner.scan(); + } + if((this.currentToken.tokenId == TypeScript.TokenID.OpenParen) || (isIndexer && (this.currentToken.tokenId == TypeScript.TokenID.OpenBracket))) { + var ers = errorRecoverySet | TypeScript.ErrorRecoverySet.RParen; + if(isIndexer) { + ers = errorRecoverySet | TypeScript.ErrorRecoverySet.RBrack; + } + var ast = this.parseFncDecl(ers, true, requireSignature, !this.inFncDecl, text, isIndexer, isStatic, (this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)), modifiers, null, true); + var funcDecl; + if(ast.nodeType == TypeScript.NodeType.Error) { + return ast; + } else { + funcDecl = ast; + } + if(funcDecl.name) { + funcDecl.name.minChar = minChar; + funcDecl.name.limChar = nameLimChar; + } + if((modifiers & TypeScript.Modifiers.Public) != TypeScript.Modifiers.None) { + funcDecl.fncFlags |= TypeScript.FncFlags.Public; + } + if((modifiers & TypeScript.Modifiers.Private) != TypeScript.Modifiers.None) { + funcDecl.fncFlags |= TypeScript.FncFlags.Private; + } + if(isStatic) { + funcDecl.fncFlags |= TypeScript.FncFlags.Static; + } + if(this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + funcDecl.fncFlags |= TypeScript.FncFlags.Ambient; + } + if(isAccessor) { + if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter)) { + funcDecl.fncFlags |= TypeScript.FncFlags.GetAccessor; + funcDecl.hint = "get" + funcDecl.name.actualText; + } else { + funcDecl.fncFlags |= TypeScript.FncFlags.SetAccessor; + funcDecl.hint = "set" + funcDecl.name.actualText; + } + funcDecl.fncFlags |= TypeScript.FncFlags.IsFunctionExpression; + if(modifiers & TypeScript.Modifiers.Ambient) { + this.reportParseError("Property accessors may not be declared in ambient types"); + } + } + if(text == null) { + if(isNew) { + funcDecl.fncFlags |= TypeScript.FncFlags.ConstructMember; + funcDecl.hint = "_construct"; + funcDecl.classDecl = this.currentClassDecl; + } else { + funcDecl.hint = "_call"; + funcDecl.fncFlags |= TypeScript.FncFlags.CallMember; + } + } + return funcDecl; + } else { + var varDecl = new TypeScript.VarDecl(text, this.nestingLevel); + varDecl.preComments = this.parseComments(); + varDecl.minChar = minChar; + if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { + this.currentToken = this.scanner.scan(); + varDecl.typeExpr = this.parseTypeReference(errorRecoverySet | TypeScript.ErrorRecoverySet.Asg | TypeScript.ErrorRecoverySet.Comma, false); + if(varDecl.typeExpr && varDecl.typeExpr.nodeType == TypeScript.NodeType.TypeRef) { + var typeExpr = (varDecl.typeExpr); + if(typeExpr.term && typeExpr.term.nodeType == TypeScript.NodeType.FuncDecl) { + typeExpr.term.preComments = varDecl.preComments; + } + } + } + if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { + if(requireSignature) { + this.reportParseError("context does not permit variable initializer"); + if(this.errorRecovery) { + this.skip(errorRecoverySet); + varDecl.flags |= TypeScript.ASTFlags.Error; + varDecl.limChar = this.scanner.lastTokenLimChar(); + return varDecl; + } + } + this.currentToken = this.scanner.scan(); + varDecl.init = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); + varDecl.limChar = varDecl.init.limChar; + if(varDecl.init.nodeType == TypeScript.NodeType.FuncDecl) { + var funcDecl = varDecl.init; + funcDecl.hint = varDecl.id.text; + funcDecl.boundToProperty = varDecl; + } else { + if(isAccessor) { + this.reportParseError("Accessors may only be functions"); + } + } + } else { + varDecl.limChar = this.scanner.pos; + } + if((modifiers & TypeScript.Modifiers.Readonly) != TypeScript.Modifiers.None) { + varDecl.varFlags |= TypeScript.VarFlags.Readonly; + } + if(isStatic) { + varDecl.varFlags |= TypeScript.VarFlags.Static; + } + if((modifiers & TypeScript.Modifiers.Public) != TypeScript.Modifiers.None) { + varDecl.varFlags |= TypeScript.VarFlags.Public; + } + if((modifiers & TypeScript.Modifiers.Private) != TypeScript.Modifiers.None) { + varDecl.varFlags |= TypeScript.VarFlags.Private; + } + varDecl.varFlags |= TypeScript.VarFlags.Property; + return varDecl; + } + }; + Parser.prototype.parseVariableDeclaration = function (errorRecoverySet, modifiers, allowIn, isStatic) { + var isConst = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Readonly); + var minChar = this.scanner.startPos; + var varDecl = null; + var declList = null; + var multivar = false; + this.currentToken = this.scanner.scan(); + var varDeclPreComments = this.parseComments(); + while(true) { + if((this.currentToken.tokenId != TypeScript.TokenID.Identifier) && (!TypeScript.convertTokToID(this.currentToken, this.strictMode))) { + this.reportParseError("Expected identifier in variable declaration"); + if(this.errorRecovery) { + varDecl = new TypeScript.VarDecl(new TypeScript.MissingIdentifier(), this.nestingLevel); + varDecl.minChar = minChar; + this.skip(errorRecoverySet); + varDecl.flags |= TypeScript.ASTFlags.Error; + varDecl.limChar = this.scanner.lastTokenLimChar(); + return varDecl; + } + } + var varDeclName = TypeScript.Identifier.fromToken(this.currentToken); + if(this.strictMode && (varDeclName.text == "eval")) { + this.reportParseError("'eval' may not name a variable in strict mode"); + } + varDecl = this.makeVarDecl(varDeclName, this.nestingLevel); + varDecl.id.minChar = this.scanner.startPos; + varDecl.id.limChar = this.scanner.pos; + varDecl.preComments = varDeclPreComments; + if(isStatic) { + varDecl.varFlags |= TypeScript.VarFlags.Static; + } + if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Readonly)) { + varDecl.varFlags |= TypeScript.VarFlags.Readonly; + } + if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + varDecl.varFlags |= TypeScript.VarFlags.Ambient; + } + if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { + varDecl.varFlags |= TypeScript.VarFlags.Exported; + } + varDecl.minChar = minChar; + if(declList) { + declList.append(varDecl); + } + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { + this.currentToken = this.scanner.scan(); + var prevInFncDecl = this.inFncDecl; + this.inFncDecl = false; + varDecl.typeExpr = this.parseTypeReference(errorRecoverySet | TypeScript.ErrorRecoverySet.Asg | TypeScript.ErrorRecoverySet.Comma, false); + this.inFncDecl = prevInFncDecl; + } + if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { + if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Ambient)) { + this.reportParseError("Ambient variable can not have an initializer"); + } + this.currentToken = this.scanner.scan(); + varDecl.init = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, allowIn, TypeContext.NoTypes); + varDecl.limChar = varDecl.init.limChar; + if(varDecl.init.nodeType == TypeScript.NodeType.FuncDecl) { + var funcDecl = varDecl.init; + funcDecl.hint = varDecl.id.actualText; + } + } else { + if(isConst) { + this.reportParseError("const declaration requires initializer"); + } + varDecl.limChar = this.scanner.pos; + } + varDecl.postComments = this.parseCommentsForLine(this.scanner.line); + if(this.currentToken.tokenId != TypeScript.TokenID.Comma) { + if(declList) { + declList.limChar = varDecl.limChar; + return declList; + } else { + return varDecl; + } + } + if(!multivar) { + declList = new TypeScript.ASTList(); + declList.minChar = varDecl.minChar; + declList.append(varDecl); + multivar = true; + } + this.currentToken = this.scanner.scan(); + minChar = this.scanner.startPos; + } + }; + Parser.prototype.parseMemberList = function (errorRecoverySet) { + var elements = new TypeScript.ASTList(); + if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { + return elements; + } + var idHint = null; + var memberName = null; + var memberExpr = null; + var member = null; + var minChar = this.scanner.startPos; + var isSet = false; + var skippedTokenForGetSetId = false; + var getSetTok = null; + var getSetStartPos = 0; + var getSetPos = 0; + for(; ; ) { + var accessorPattern = false; + if(this.currentToken.tokenId == TypeScript.TokenID.Get || this.currentToken.tokenId == TypeScript.TokenID.Set) { + isSet = this.currentToken.tokenId == TypeScript.TokenID.Set; + getSetTok = this.currentToken; + getSetStartPos = this.scanner.startPos; + getSetPos = this.scanner.pos; + this.currentToken = this.scanner.scan(); + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToIDName(this.currentToken)) { + idHint = isSet ? "set" : "get"; + idHint = idHint + this.currentToken.getText(); + memberName = TypeScript.Identifier.fromToken(this.currentToken); + memberName.minChar = this.scanner.startPos; + accessorPattern = true; + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("Property accessors are only available when targeting ES5 or greater"); + } + } else { + if(this.currentToken.tokenId != TypeScript.TokenID.Colon) { + this.reportParseError("Expected identifier, string or number as accessor name"); + } else { + skippedTokenForGetSetId = true; + memberName = TypeScript.Identifier.fromToken(getSetTok); + memberName.minChar = getSetStartPos; + memberName.limChar = getSetPos; + } + } + } else { + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToIDName(this.currentToken)) { + idHint = this.currentToken.getText(); + memberName = TypeScript.Identifier.fromToken(this.currentToken); + memberName.minChar = this.scanner.startPos; + memberName.limChar = this.scanner.pos; + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.StringLiteral) { + idHint = this.currentToken.getText(); + memberName = new TypeScript.StringLiteral(idHint); + memberName.minChar = this.scanner.startPos; + memberName.limChar = this.scanner.pos; + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.NumberLiteral) { + var ntok = this.currentToken; + idHint = ntok.value.toString(); + memberName = new TypeScript.StringLiteral(idHint); + memberName.minChar = this.scanner.startPos; + memberName.limChar = this.scanner.pos; + } else { + this.reportParseError("Expected identifier, string or number as member name"); + if(this.errorRecovery) { + memberName = new TypeScript.MissingIdentifier(); + memberName.minChar = this.scanner.startPos; + memberName.flags |= TypeScript.ASTFlags.Error; + this.skip(errorRecoverySet | TypeScript.ErrorRecoverySet.Comma); + memberName.limChar = this.scanner.lastTokenLimChar(); + } + } + } + } + } + if(!skippedTokenForGetSetId) { + this.currentToken = this.scanner.scan(); + } else { + skippedTokenForGetSetId = false; + } + if(this.currentToken.tokenId == TypeScript.TokenID.Question) { + memberName.flags |= TypeScript.ASTFlags.OptionalName; + this.currentToken = this.scanner.scan(); + } + if(accessorPattern) { + var args = new TypeScript.ASTList(); + this.parseFormalParameterList(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, args, false, true, false, !isSet, isSet, false, null, true); + var funcDecl = this.parseFunctionStatements(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, memberName, false, true, args, TypeScript.AllowedElements.None, this.scanner.startPos, false, TypeScript.Modifiers.None); + if(isSet && funcDecl.returnTypeAnnotation) { + this.reportParseError("Property setters may not declare a return type"); + } + funcDecl.fncFlags |= isSet ? TypeScript.FncFlags.SetAccessor : TypeScript.FncFlags.GetAccessor; + funcDecl.fncFlags |= TypeScript.FncFlags.IsFunctionExpression; + funcDecl.hint = idHint; + memberExpr = funcDecl; + member = new TypeScript.BinaryExpression(TypeScript.NodeType.Member, memberName, memberExpr); + member.minChar = memberName.minChar; + if(memberExpr.nodeType == TypeScript.NodeType.FuncDecl) { + var funcDecl = memberExpr; + funcDecl.hint = idHint; + } + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { + this.currentToken = this.scanner.scan(); + memberExpr = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); + if(memberExpr.nodeType == TypeScript.NodeType.TypeRef) { + this.reportParseError("Expected 'new' on array declaration in member definition"); + } + member = new TypeScript.BinaryExpression(TypeScript.NodeType.Member, memberName, memberExpr); + member.minChar = memberName.minChar; + if(memberExpr.nodeType == TypeScript.NodeType.FuncDecl) { + var funcDecl = memberExpr; + funcDecl.hint = idHint; + } + } else { + this.reportParseError("Expected ':' in member definition"); + if(this.errorRecovery) { + this.skip(errorRecoverySet); + elements.flags |= TypeScript.ASTFlags.Error; + elements.minChar = minChar; + elements.limChar = this.scanner.lastTokenLimChar(); + return elements; + } + } + } + idHint = null; + elements.append(member); + member.limChar = this.scanner.lastTokenLimChar(); + if(this.currentToken.tokenId != TypeScript.TokenID.Comma) { + break; + } else { + this.currentToken = this.scanner.scan(); + } + if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { + break; + } + } + if(member) { + elements.limChar = member.limChar; + } + elements.minChar = minChar; + return elements; + }; + Parser.prototype.parseArrayList = function (errorRecoverySet) { + var elements = null; + if(this.currentToken.tokenId == TypeScript.TokenID.CloseBracket) { + return elements; + } else { + elements = new TypeScript.ASTList(); + elements.minChar = this.scanner.startPos; + } + var arg; + for(; ; ) { + if((this.currentToken.tokenId == TypeScript.TokenID.Comma) || (this.currentToken.tokenId == TypeScript.TokenID.CloseBracket)) { + arg = new TypeScript.AST(TypeScript.NodeType.EmptyExpr); + } else { + arg = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); + } + elements.append(arg); + if(this.currentToken.tokenId != TypeScript.TokenID.Comma) { + break; + } + this.currentToken = this.scanner.scan(); + } + elements.limChar = this.scanner.lastTokenLimChar(); + return elements; + }; + Parser.prototype.parseArrayLiteral = function (errorRecoverySet) { + var arrayLiteral = null; + arrayLiteral = new TypeScript.UnaryExpression(TypeScript.NodeType.ArrayLit, this.parseArrayList(errorRecoverySet)); + return arrayLiteral; + }; + Parser.prototype.parseTerm = function (errorRecoverySet, allowCall, typeContext, inCast) { + var ast = null; + var sawId = false; + var inNew = false; + var minChar = this.scanner.startPos; + var limChar = this.scanner.pos; + var parseAsLambda = false; + var expectlambdaRParen = false; + switch(this.currentToken.tokenId) { + case TypeScript.TokenID.Number: + case TypeScript.TokenID.Bool: + case TypeScript.TokenID.Any: + case TypeScript.TokenID.String: { + var tid = new TypeScript.Identifier(TypeScript.tokenTable[this.currentToken.tokenId].text); + if(TypeScript.hasFlag(typeContext, TypeContext.Primitive)) { + ast = new TypeScript.TypeReference(tid, 0); + sawId = true; + } else { + ast = tid; + sawId = true; + } + ast.minChar = minChar; + this.currentToken = this.scanner.scan(); + limChar = this.scanner.lastTokenLimChar(); + break; + + } + case TypeScript.TokenID.This: { + ast = new TypeScript.AST(TypeScript.NodeType.This); + ast.minChar = minChar; + this.currentToken = this.scanner.scan(); + limChar = this.scanner.lastTokenLimChar(); + break; + + } + case TypeScript.TokenID.Super: { + ast = new TypeScript.AST(TypeScript.NodeType.Super); + ast.minChar = minChar; + this.currentToken = this.scanner.scan(); + limChar = this.scanner.lastTokenLimChar(); + break; + + } + case TypeScript.TokenID.True: { + ast = new TypeScript.AST(TypeScript.NodeType.True); + this.currentToken = this.scanner.scan(); + ast.minChar = minChar; + break; + + } + case TypeScript.TokenID.False: { + ast = new TypeScript.AST(TypeScript.NodeType.False); + this.currentToken = this.scanner.scan(); + ast.minChar = minChar; + break; + + } + case TypeScript.TokenID.Null: { + ast = new TypeScript.AST(TypeScript.NodeType.Null); + this.currentToken = this.scanner.scan(); + ast.minChar = minChar; + break; + + } + case TypeScript.TokenID.New: { + minChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + var target = this.parseTerm(errorRecoverySet, false, TypeContext.AllSimpleTypes, inCast); + if(target.nodeType == TypeScript.NodeType.Error || (target.nodeType == TypeScript.NodeType.Index && (target).operand1.nodeType == TypeScript.NodeType.TypeRef)) { + this.reportParseError("Cannot invoke 'new' on this expression"); + } else { + ast = new TypeScript.CallExpression(TypeScript.NodeType.New, target, null); + ast.minChar = minChar; + limChar = this.scanner.lastTokenLimChar(); + inNew = true; + } + break; + + } + case TypeScript.TokenID.Function: { + minChar = this.scanner.pos; + ast = this.parseFncDecl(errorRecoverySet, false, false, false, null, false, false, false, TypeScript.Modifiers.None, null, true); + (ast).fncFlags |= TypeScript.FncFlags.IsFunctionExpression; + ast.minChar = minChar; + limChar = this.scanner.lastTokenLimChar(); + ast.limChar = limChar; + break; + + } + } + if(ast == null) { + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + var idText = this.currentToken.getText(); + ast = this.createRef(idText, (this.currentToken).hasEscapeSequence, minChar); + sawId = true; + ast.minChar = minChar; + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.Question) { + ast.flags |= TypeScript.ASTFlags.PossibleOptionalParameter; + } + limChar = this.scanner.lastTokenLimChar(); + } + } + if(inCast) { + this.checkCurrentToken(TypeScript.TokenID.GreaterThan, errorRecoverySet); + } + if(ast == null) { + switch(this.currentToken.tokenId) { + case TypeScript.TokenID.OpenParen: { + minChar = this.scanner.pos; + var prevTokId = this.scanner.previousToken().tokenId; + this.currentToken = this.scanner.scan(); + var couldBeLambda = prevTokId == TypeScript.TokenID.OpenParen || prevTokId == TypeScript.TokenID.Comma || prevTokId == TypeScript.TokenID.EqualsEquals || prevTokId == TypeScript.TokenID.Colon; + if(couldBeLambda && this.currentToken.tokenId == TypeScript.TokenID.CloseParen) { + parseAsLambda = true; + expectlambdaRParen = false; + this.currentToken = this.scanner.scan(); + } else { + if(couldBeLambda && this.currentToken.tokenId == TypeScript.TokenID.DotDotDot) { + parseAsLambda = true; + expectlambdaRParen = true; + } else { + ast = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes, couldBeLambda); + limChar = this.scanner.lastTokenLimChar(); + parseAsLambda = couldBeLambda && (ast.nodeType == TypeScript.NodeType.Name || ast.nodeType == TypeScript.NodeType.Comma) && (this.currentToken.tokenId == TypeScript.TokenID.Colon || this.currentToken.tokenId == TypeScript.TokenID.Question); + expectlambdaRParen = true; + } + } + if((ast && !parseAsLambda)) { + if(TypeScript.hasFlag(ast.flags, TypeScript.ASTFlags.SkipNextRParen)) { + ast.flags = ast.flags & (~(TypeScript.ASTFlags.SkipNextRParen)); + break; + } + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet); + ast.isParenthesized = true; + } + break; + + } + case TypeScript.TokenID.NumberLiteral: { + var numTok = this.currentToken; + this.currentToken = this.scanner.scan(); + ast = new TypeScript.NumberLiteral(numTok.value, numTok.hasEmptyFraction); + ast.minChar = minChar; + limChar = this.scanner.lastTokenLimChar(); + break; + } + + case TypeScript.TokenID.StringLiteral: { + ast = new TypeScript.StringLiteral(this.currentToken.getText()); + this.currentToken = this.scanner.scan(); + ast.minChar = minChar; + limChar = this.scanner.lastTokenLimChar(); + break; + + } + case TypeScript.TokenID.RegularExpressionLiteral: { + var rtok = this.currentToken; + ast = new TypeScript.RegexLiteral(rtok.regex); + this.currentToken = this.scanner.scan(); + ast.minChar = minChar; + limChar = this.scanner.lastTokenLimChar(); + break; + } + + case TypeScript.TokenID.OpenBracket: { + minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + ast = this.parseArrayLiteral(TypeScript.ErrorRecoverySet.RBrack | errorRecoverySet); + ast.minChar = minChar; + limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseBracket, errorRecoverySet); + break; + + } + case TypeScript.TokenID.OpenBrace: { + minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + var members = this.parseMemberList(TypeScript.ErrorRecoverySet.RCurly | errorRecoverySet); + this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); + ast = new TypeScript.UnaryExpression(TypeScript.NodeType.ObjectLit, members); + ast.minChar = minChar; + limChar = this.scanner.lastTokenLimChar(); + members.minChar = minChar; + members.limChar = limChar; + break; + + } + case TypeScript.TokenID.LessThan: { + minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + var term = this.parseTypeReference(TypeScript.ErrorRecoverySet.BinOp, false); + this.checkCurrentToken(TypeScript.TokenID.GreaterThan, errorRecoverySet); + ast = new TypeScript.UnaryExpression(TypeScript.NodeType.TypeAssertion, this.parseExpr(errorRecoverySet, TypeScript.OperatorPrecedence.Unary, false, TypeContext.NoTypes)); + (ast).castTerm = term; + break; + + } + default: { + if(this.prevExpr && TypeScript.hasFlag(this.prevExpr.flags, TypeScript.ASTFlags.PossibleOptionalParameter)) { + parseAsLambda = true; + ast = this.prevExpr; + } else { + this.reportParseError("Check format of expression term"); + if(this.errorRecovery) { + var ident = new TypeScript.MissingIdentifier(); + ident.minChar = minChar; + ident.flags |= TypeScript.ASTFlags.Error; + this.skip(errorRecoverySet | TypeScript.ErrorRecoverySet.Postfix); + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + ident.setText(this.currentToken.getText(), (this.currentToken).hasEscapeSequence); + this.currentToken = this.scanner.scan(); + limChar = this.scanner.lastTokenLimChar(); + } else { + limChar = this.scanner.lastTokenLimChar(); + } + ast = ident; + } + } + + } + } + } + if(parseAsLambda) { + if(this.currentToken.tokenId == TypeScript.TokenID.Colon || this.currentToken.tokenId == TypeScript.TokenID.Comma || this.currentToken.tokenId == TypeScript.TokenID.CloseParen || this.currentToken.tokenId == TypeScript.TokenID.DotDotDot) { + ast = this.parseLambdaExpr(errorRecoverySet, ast, true, expectlambdaRParen); + ast.minChar = minChar; + limChar = this.scanner.lastTokenLimChar(); + ast.limChar = limChar; + } else { + if(ast) { + ast.isParenthesized = true; + } + } + } + if(sawId && (typeContext != TypeContext.NoTypes)) { + typeContext |= TypeContext.ArraySuffix; + } + var postFix = this.parsePostfixOperators(errorRecoverySet, ast, allowCall, inNew, typeContext, minChar, limChar); + if(postFix) { + if(sawId && (postFix.nodeType == TypeScript.NodeType.Index)) { + var binExpr = postFix; + if(binExpr.operand2 == null) { + postFix = this.convertToTypeReference(postFix); + } + } + postFix.minChar = minChar; + postFix.limChar = TypeScript.max(postFix.limChar, this.scanner.lastTokenLimChar()); + return postFix; + } else { + return new TypeScript.AST(TypeScript.NodeType.Error); + } + }; + Parser.prototype.parseLambdaExpr = function (errorRecoverySet, lambdaArgs, skipNextRParen, expectClosingRParen) { + var ast = this.parseFncDecl(errorRecoverySet, false, false, false, null, false, false, false, TypeScript.Modifiers.None, { + preProcessedLambdaArgs: lambdaArgs + }, expectClosingRParen); + (ast).fncFlags |= TypeScript.FncFlags.IsFunctionExpression; + (ast).fncFlags |= TypeScript.FncFlags.IsFatArrowFunction; + if(!skipNextRParen) { + ast.flags |= TypeScript.ASTFlags.SkipNextRParen; + } + ast.limChar = this.scanner.lastTokenLimChar(); + ; ; + return ast; + }; + Parser.prototype.parseExpr = function (errorRecoverySet, minPrecedence, allowIn, typeContext, possiblyInLambda) { + if (typeof possiblyInLambda === "undefined") { possiblyInLambda = false; } + var ast = null; + var tokenInfo = TypeScript.lookupToken(this.currentToken.tokenId); + var canAssign = true; + var idHint = null; + var minChar = this.scanner.startPos; + var preComments = this.parseComments(); + var exprIsAnonLambda = false; + if((tokenInfo != undefined) && (tokenInfo.unopNodeType != TypeScript.NodeType.None)) { + canAssign = false; + this.currentToken = this.scanner.scan(); + var tempExpr = this.parseExpr(TypeScript.ErrorRecoverySet.BinOp | errorRecoverySet, tokenInfo.unopPrecedence, allowIn, TypeContext.NoTypes); + if((tokenInfo.unopNodeType == TypeScript.NodeType.Pos) && (tempExpr.nodeType == TypeScript.NodeType.NumberLit)) { + ast = tempExpr; + } else { + if((tokenInfo.unopNodeType == TypeScript.NodeType.Neg) && (tempExpr.nodeType == TypeScript.NodeType.NumberLit)) { + var numLit = tempExpr; + numLit.value = (-numLit.value); + if(numLit.value == 0) { + numLit.isNegativeZero = true; + } + ast = tempExpr; + } else { + ast = new TypeScript.UnaryExpression(tokenInfo.unopNodeType, tempExpr); + ast.limChar = tempExpr.limChar; + } + } + ast.minChar = minChar; + } else { + ast = this.parseTerm(TypeScript.ErrorRecoverySet.BinOp | TypeScript.ErrorRecoverySet.AddOp | errorRecoverySet, true, typeContext, false); + var id; + var temp; + if(ast.nodeType == TypeScript.NodeType.Name) { + id = ast; + idHint = id.actualText; + } else { + if(ast.nodeType == TypeScript.NodeType.Dot) { + var subsumedExpr = false; + if(this.inferPropertiesFromThisAssignment && (this.currentToken.tokenId == TypeScript.TokenID.Colon || this.currentToken.tokenId == TypeScript.TokenID.Equals) && this.parsingClassConstructorDefinition && this.nestingLevel == this.currentClassDefinition.constructorNestingLevel && (ast).operand1.nodeType == TypeScript.NodeType.This) { + if((ast).operand2.nodeType == TypeScript.NodeType.Name) { + var op2ID = ((ast).operand2); + if(!this.currentClassDefinition.knownMemberNames[op2ID.actualText]) { + ast = this.parseClassMemberVariableDeclaration(op2ID, ast.minChar, true, errorRecoverySet, TypeScript.Modifiers.Public); + subsumedExpr = true; + } + } + } + if(!subsumedExpr) { + temp = ast; + while(temp.nodeType == TypeScript.NodeType.Dot) { + var binExpr = temp; + temp = binExpr.operand2; + } + if(temp.nodeType == TypeScript.NodeType.Name) { + id = temp; + idHint = id.actualText; + } + } + } + } + if((!this.scanner.lastTokenHadNewline()) && ((this.currentToken.tokenId == TypeScript.TokenID.PlusPlus) || (this.currentToken.tokenId == TypeScript.TokenID.MinusMinus))) { + canAssign = false; + var operand = ast; + ast = new TypeScript.UnaryExpression((this.currentToken.tokenId == TypeScript.TokenID.PlusPlus) ? TypeScript.NodeType.IncPost : TypeScript.NodeType.DecPost, operand); + ast.limChar = this.scanner.pos; + ast.minChar = operand.minChar; + this.currentToken = this.scanner.scan(); + } + } + for(; ; ) { + tokenInfo = TypeScript.lookupToken(this.currentToken.tokenId); + if((tokenInfo == undefined) || (tokenInfo.binopNodeType == TypeScript.NodeType.None)) { + break; + } + if((!allowIn) && (tokenInfo.binopNodeType == TypeScript.NodeType.In)) { + break; + } + if(tokenInfo.binopPrecedence == TypeScript.OperatorPrecedence.Assignment) { + if(tokenInfo.binopPrecedence < minPrecedence) { + break; + } + if(!canAssign) { + this.reportParseError("illegal assignment"); + } + } else { + if(tokenInfo.binopPrecedence <= minPrecedence) { + break; + } + } + if(possiblyInLambda && this.currentToken.tokenId == TypeScript.TokenID.Comma && this.scanner.getLookAheadToken().tokenId == TypeScript.TokenID.DotDotDot) { + exprIsAnonLambda = true; + canAssign = false; + ast = this.parseLambdaExpr(errorRecoverySet, ast, false, true); + break; + } + this.currentToken = this.scanner.scan(); + canAssign = false; + if(tokenInfo.binopNodeType == TypeScript.NodeType.ConditionalExpression) { + if(possiblyInLambda && (this.currentToken.tokenId == TypeScript.TokenID.Equals || this.currentToken.tokenId == TypeScript.TokenID.Colon || this.currentToken.tokenId == TypeScript.TokenID.CloseParen || this.currentToken.tokenId == TypeScript.TokenID.Comma)) { + exprIsAnonLambda = true; + canAssign = true; + } else { + this.prevExpr = ast; + var whenTrue = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.Colon, TypeScript.OperatorPrecedence.Assignment, allowIn, TypeContext.NoTypes); + this.prevExpr = null; + this.checkCurrentToken(TypeScript.TokenID.Colon, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); + var whenFalse = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.BinOp, TypeScript.OperatorPrecedence.Assignment, allowIn, TypeContext.NoTypes); + ast = new TypeScript.ConditionalExpression(ast, whenTrue, whenFalse); + } + } else { + var tc = TypeContext.NoTypes; + var binExpr2; + binExpr2 = new TypeScript.BinaryExpression(tokenInfo.binopNodeType, ast, this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.BinOp, tokenInfo.binopPrecedence, allowIn, TypeContext.NoTypes, possiblyInLambda)); + if(binExpr2.operand2.nodeType == TypeScript.NodeType.FuncDecl) { + var funcDecl = binExpr2.operand2; + funcDecl.hint = idHint; + } + binExpr2.minChar = ast.minChar; + binExpr2.limChar = this.scanner.lastTokenLimChar(); + idHint = null; + ast = binExpr2; + } + } + if(canAssign) { + ast.flags |= TypeScript.ASTFlags.Writeable; + } + if(!exprIsAnonLambda) { + ast.minChar = minChar; + ast.limChar = TypeScript.max(ast.limChar, this.scanner.lastTokenLimChar()); + ast.preComments = preComments; + ast.postComments = this.parseCommentsForLine(this.scanner.line); + } + return ast; + }; + Parser.prototype.parsePostfixOperators = function (errorRecoverySet, ast, allowCall, inNew, typeContext, lhsMinChar, lhsLimChar) { + var count = 0; + if(!ast) { + ast = new TypeScript.AST(TypeScript.NodeType.EmptyExpr); + ast.isParenthesized = true; + } + ast.minChar = lhsMinChar; + ast.limChar = lhsLimChar; + for(; ; ) { + switch(this.currentToken.tokenId) { + case TypeScript.TokenID.OpenParen: { + if(inNew) { + var callExpr = ast; + callExpr.arguments = this.parseArgList(errorRecoverySet); + inNew = false; + } else { + if(!allowCall) { + return ast; + } + ast = new TypeScript.CallExpression(TypeScript.NodeType.Call, ast, this.parseArgList(errorRecoverySet)); + ast.minChar = lhsMinChar; + } + ast.limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet); + break; + + } + case TypeScript.TokenID.OpenBracket: { + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.CloseBracket) { + if(TypeScript.hasFlag(typeContext, TypeContext.ArraySuffix)) { + this.currentToken = this.scanner.scan(); + if(ast.nodeType == TypeScript.NodeType.TypeRef) { + var typeRef = ast; + typeRef.arrayCount++; + } else { + ast = new TypeScript.BinaryExpression(TypeScript.NodeType.Index, ast, null); + } + ast.limChar = this.scanner.pos; + break; + } + } + ast = new TypeScript.BinaryExpression(TypeScript.NodeType.Index, ast, this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RBrack, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes)); + ast.minChar = lhsMinChar; + ast.limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseBracket, errorRecoverySet); + break; + + } + case TypeScript.TokenID.Dot: { + var name = null; + var curpos = this.scanner.pos; + this.currentToken = this.scanner.scan(); + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || ((!this.errorRecovery || !this.scanner.lastTokenHadNewline()) && TypeScript.convertTokToIDName(this.currentToken))) { + ast.flags |= TypeScript.ASTFlags.DotLHS; + name = this.createRef(this.currentToken.getText(), (this.currentToken).hasEscapeSequence, this.scanner.startPos); + name.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + } else { + this.reportParseError("Expected identifier following dot"); + if(this.errorRecovery) { + this.skip(errorRecoverySet); + ast.flags |= (TypeScript.ASTFlags.Error | TypeScript.ASTFlags.DotLHS); + return ast; + } else { + name = new TypeScript.MissingIdentifier(); + } + } + ast = new TypeScript.BinaryExpression(TypeScript.NodeType.Dot, ast, name); + ast.minChar = lhsMinChar; + ast.limChar = this.scanner.lastTokenLimChar(); + break; + } + + case TypeScript.TokenID.EqualsGreaterThan: { + ast = this.parseFncDecl(errorRecoverySet, false, false, false, null, false, false, false, TypeScript.Modifiers.None, { + preProcessedLambdaArgs: ast + }, false); + (ast).fncFlags |= TypeScript.FncFlags.IsFunctionExpression; + ast.minChar = lhsMinChar; + ast.limChar = this.scanner.lastTokenLimChar(); + break; + + } + default: { + return ast; + + } + } + } + }; + Parser.prototype.parseTry = function (tryNode, errorRecoverySet, parentModifiers) { + var minChar = this.scanner.startPos; + var preComments = this.parseComments(); + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId != TypeScript.TokenID.OpenBrace) { + this.reportParseError("Expected '{'"); + if(this.errorRecovery) { + var etryNode = tryNode; + etryNode.minChar = minChar; + etryNode.limChar = this.scanner.lastTokenLimChar(); + etryNode.flags |= TypeScript.ASTFlags.Error; + return etryNode; + } + } + tryNode.body = this.parseStatement(errorRecoverySet, TypeScript.AllowedElements.None, parentModifiers); + tryNode.minChar = minChar; + tryNode.limChar = tryNode.body.limChar; + tryNode.preComments = preComments; + tryNode.postComments = this.parseComments(); + return tryNode; + }; + Parser.prototype.parseCatch = function (errorRecoverySet, parentModifiers) { + var catchMinChar = this.scanner.startPos; + var preComments = this.parseComments(); + this.currentToken = this.scanner.scan(); + this.checkCurrentToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); + if((this.currentToken.tokenId != TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + this.reportParseError("Expected identifier in catch header"); + if(this.errorRecovery) { + this.skip(errorRecoverySet); + var ecatch = new TypeScript.Catch(new TypeScript.VarDecl(new TypeScript.MissingIdentifier(), this.nestingLevel), new TypeScript.Statement(TypeScript.NodeType.Empty)); + ecatch.statement.minChar = catchMinChar; + ecatch.statement.limChar = this.scanner.pos; + ecatch.minChar = this.scanner.startPos; + ecatch.limChar = this.scanner.pos; + ecatch.flags |= TypeScript.ASTFlags.Error; + return ecatch; + } + } + var param = new TypeScript.VarDecl(TypeScript.Identifier.fromToken(this.currentToken), this.nestingLevel); + param.id.minChar = this.scanner.startPos; + param.id.limChar = this.scanner.pos; + param.minChar = param.id.minChar; + param.limChar = param.id.limChar; + this.currentToken = this.scanner.scan(); + var statementPos = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); + if(this.currentToken.tokenId != TypeScript.TokenID.OpenBrace) { + this.reportParseError("Expected '{' to start catch body"); + if(this.errorRecovery) { + this.skip(errorRecoverySet); + var ecatch = new TypeScript.Catch(new TypeScript.VarDecl(new TypeScript.MissingIdentifier(), this.nestingLevel), new TypeScript.Statement(TypeScript.NodeType.Empty)); + ecatch.statement.minChar = catchMinChar; + ecatch.statement.limChar = statementPos; + ecatch.minChar = this.scanner.startPos; + ecatch.limChar = this.scanner.pos; + ecatch.flags |= TypeScript.ASTFlags.Error; + return ecatch; + } + } + var catchStmt = this.parseStatement(errorRecoverySet, TypeScript.AllowedElements.None, parentModifiers); + var catchNode = new TypeScript.Catch(param, catchStmt); + catchNode.statement.minChar = catchMinChar; + catchNode.statement.limChar = statementPos; + catchNode.minChar = catchMinChar; + catchNode.limChar = catchStmt.limChar; + catchNode.preComments = preComments; + catchNode.postComments = this.parseComments(); + return catchNode; + }; + Parser.prototype.parseFinally = function (errorRecoverySet, parentModifiers) { + var finMinChar = this.scanner.startPos; + var preComments = this.parseComments(); + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId != TypeScript.TokenID.OpenBrace) { + this.reportParseError("Expected '{' to start body of finally statement"); + if(this.errorRecovery) { + this.skip(errorRecoverySet); + var efin = new TypeScript.Finally(new TypeScript.Statement(TypeScript.NodeType.Empty)); + efin.flags |= TypeScript.ASTFlags.Error; + efin.minChar = this.scanner.startPos; + efin.limChar = this.scanner.pos; + return efin; + } + } + var finBody = this.parseStatement(errorRecoverySet, TypeScript.AllowedElements.None, parentModifiers); + var fin = new TypeScript.Finally(finBody); + fin.minChar = finMinChar; + fin.limChar = fin.body.limChar; + fin.preComments = preComments; + fin.postComments = this.parseComments(); + return fin; + }; + Parser.prototype.parseTryCatchFinally = function (errorRecoverySet, parentModifiers, labelList) { + var tryPart = new TypeScript.Try(null); + var tryMinChar = this.scanner.startPos; + this.pushStmt(tryPart, labelList); + this.parseTry(tryPart, errorRecoverySet | TypeScript.ErrorRecoverySet.Catch, parentModifiers); + this.popStmt(); + var tc = null; + var tf = null; + if(this.currentToken.tokenId == TypeScript.TokenID.Catch) { + var catchPart = this.parseCatch(errorRecoverySet | TypeScript.ErrorRecoverySet.Catch, parentModifiers); + tc = new TypeScript.TryCatch(tryPart, catchPart); + tc.minChar = tryPart.minChar; + tc.limChar = catchPart.limChar; + } + if(this.currentToken.tokenId != TypeScript.TokenID.Finally) { + if(tc == null) { + this.reportParseError("try with neither catch nor finally"); + if(this.errorRecovery) { + var etf = new TypeScript.TryFinally(tryPart, new TypeScript.Finally(new TypeScript.AST(TypeScript.NodeType.Empty))); + etf.flags |= TypeScript.ASTFlags.Error; + etf.minChar = this.scanner.startPos; + etf.limChar = this.scanner.pos; + return etf; + } + return new TypeScript.TryFinally(tryPart, new TypeScript.Finally(new TypeScript.AST(TypeScript.NodeType.Empty))); + } else { + return tc; + } + } else { + if(tc) { + tryPart = tc; + } + var finallyPart = this.parseFinally(errorRecoverySet, parentModifiers); + tf = new TypeScript.TryFinally(tryPart, finallyPart); + tf.minChar = tryMinChar; + tf.limChar = finallyPart.limChar; + return tf; + } + }; + Parser.prototype.parseStatement = function (errorRecoverySet, allowedElements, parentModifiers) { + var ast = null; + var labelList = null; + var astList = null; + var temp; + var modifiers = TypeScript.Modifiers.None; + var minChar = this.scanner.startPos; + var forInOk = false; + var needTerminator = false; + var fnOrVar = null; + var preComments = this.parseComments(); + this.state = ParseState.StartStatement; + function isAmbient() { + return TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient) || TypeScript.hasFlag(parentModifiers, TypeScript.Modifiers.Ambient); + } + function mayNotBeExported() { + if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { + this.reportError("Statement may not be exported"); + } + } + for(; ; ) { + switch(this.currentToken.tokenId) { + case TypeScript.TokenID.EndOfFile: { + ast = new TypeScript.AST(TypeScript.NodeType.Error); + ast.minChar = minChar; + ast.limChar = this.scanner.pos; + break; + + } + case TypeScript.TokenID.Function: { + if(this.parsingDeclareFile || isAmbient() || this.ambientModule) { + this.currentToken = this.scanner.scan(); + fnOrVar = this.parsePropertyDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, modifiers, true, false); + if(fnOrVar.nodeType == TypeScript.NodeType.VarDecl) { + this.reportParseError("function keyword can only introduce function declaration"); + } else { + if((fnOrVar.nodeType == TypeScript.NodeType.FuncDecl) && ((fnOrVar).fncFlags , TypeScript.FncFlags.IsFatArrowFunction)) { + needTerminator = true; + } + } + ast = fnOrVar; + if(this.parsingDeclareFile || this.ambientModule && ast.nodeType == TypeScript.NodeType.FuncDecl) { + (ast).fncFlags |= TypeScript.FncFlags.Exported; + } + } else { + ast = this.parseFncDecl(errorRecoverySet, true, false, false, null, false, false, isAmbient(), modifiers, null, true); + if(TypeScript.hasFlag((ast).fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { + needTerminator = true; + } + if(this.ambientModule) { + this.reportParseError("function declaration not permitted within ambient module"); + } + if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { + (ast).fncFlags |= TypeScript.FncFlags.Exported; + } + } + break; + + } + case TypeScript.TokenID.Module: { + if((allowedElements & TypeScript.AllowedElements.ModuleDeclarations) == TypeScript.AllowedElements.None) { + this.reportParseError("module not allowed in this context"); + this.currentToken = this.scanner.scan(); + ast = new TypeScript.AST(TypeScript.NodeType.Error); + ast.minChar = minChar; + ast.limChar = this.scanner.lastTokenLimChar(); + } else { + ast = this.parseModuleDecl(errorRecoverySet, modifiers, preComments); + preComments = null; + } + break; + + } + case TypeScript.TokenID.Import: { + if((allowedElements & TypeScript.AllowedElements.ModuleDeclarations) == TypeScript.AllowedElements.None) { + this.reportParseError("module not allowed in this context"); + this.currentToken = this.scanner.scan(); + ast = new TypeScript.AST(TypeScript.NodeType.Error); + ast.minChar = minChar; + ast.limChar = this.scanner.lastTokenLimChar(); + } else { + if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { + this.reportParseError("export keyword not permitted on import declaration"); + } + ast = this.parseImportDeclaration(errorRecoverySet, modifiers); + needTerminator = true; + } + break; + + } + case TypeScript.TokenID.Export: { + if((allowedElements & TypeScript.AllowedElements.ModuleDeclarations) == TypeScript.AllowedElements.None) { + this.reportParseError("'export' statements are only allowed at the global and module levels"); + this.currentToken = this.scanner.scan(); + ast = new TypeScript.AST(TypeScript.NodeType.Error); + ast.minChar = minChar; + ast.limChar = this.scanner.lastTokenLimChar(); + } + if(this.topLevel) { + this.hasTopLevelImportOrExport = true; + } + modifiers |= TypeScript.Modifiers.Exported; + this.currentToken = this.scanner.scan(); + break; + + } + case TypeScript.TokenID.Private: { + modifiers |= TypeScript.Modifiers.Private; + this.currentToken = this.scanner.scan(); + if(this.parsingClassConstructorDefinition) { + if(!this.inferPropertiesFromThisAssignment) { + this.reportParseError("Property declarations are not permitted within constructor bodies"); + } + minChar = this.scanner.pos; + if(this.inferPropertiesFromThisAssignment && (this.currentToken.tokenId != TypeScript.TokenID.This || (this.currentToken = this.scanner.scan()).tokenId != TypeScript.TokenID.Dot)) { + this.reportParseError("Expected 'this.' for property declaration"); + this.currentToken = this.scanner.scan(); + ast = new TypeScript.AST(TypeScript.NodeType.Error); + ast.minChar = minChar; + ast.limChar = this.scanner.lastTokenLimChar(); + } else { + this.currentToken = this.scanner.scan(); + var id = TypeScript.Identifier.fromToken(this.currentToken); + id.minChar = this.scanner.startPos; + id.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + ast = this.parseClassMemberVariableDeclaration(id, minChar, this.parsingClassConstructorDefinition, errorRecoverySet, modifiers); + } + } else { + if(this.currentToken.tokenId != TypeScript.TokenID.Interface) { + if(this.currentToken.tokenId == TypeScript.TokenID.Get) { + this.prevIDTok = this.currentToken; + this.currentToken = this.scanner.scan(); + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("Property accessors are only available when targeting ES5 or greater"); + } + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + modifiers |= TypeScript.Modifiers.Getter; + this.prevIDTok = null; + } + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.Set) { + this.prevIDTok = this.currentToken; + this.currentToken = this.scanner.scan(); + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("Property accessors are only available when targeting ES5 or greater"); + } + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + modifiers |= TypeScript.Modifiers.Setter; + this.prevIDTok = null; + } + } + } + fnOrVar = this.parsePropertyDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, modifiers, isAmbient(), false); + if((fnOrVar.nodeType == TypeScript.NodeType.VarDecl) || ((fnOrVar.nodeType == TypeScript.NodeType.FuncDecl) && (TypeScript.hasFlag((fnOrVar).fncFlags, TypeScript.FncFlags.IsFatArrowFunction)))) { + needTerminator = true; + } + ast = fnOrVar; + } + } + break; + + } + case TypeScript.TokenID.Public: { + if(this.parsingClassConstructorDefinition) { + if(!this.inferPropertiesFromThisAssignment) { + this.reportParseError("Property declarations are not permitted within constructor bodies"); + } + this.currentToken = this.scanner.scan(); + minChar = this.scanner.pos; + modifiers |= TypeScript.Modifiers.Public; + if(this.inferPropertiesFromThisAssignment && (this.currentToken.tokenId != TypeScript.TokenID.This || (this.currentToken = this.scanner.scan()).tokenId != TypeScript.TokenID.Dot)) { + this.reportParseError("Expected 'this.' for property declaration"); + this.currentToken = this.scanner.scan(); + ast = new TypeScript.AST(TypeScript.NodeType.Error); + ast.minChar = minChar; + ast.limChar = this.scanner.lastTokenLimChar(); + } else { + this.currentToken = this.scanner.scan(); + var id = TypeScript.Identifier.fromToken(this.currentToken); + id.minChar = this.scanner.startPos; + id.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + ast = this.parseClassMemberVariableDeclaration(id, minChar, this.parsingClassConstructorDefinition, errorRecoverySet, modifiers); + } + } else { + if((allowedElements & TypeScript.AllowedElements.Properties) == TypeScript.AllowedElements.None) { + this.reportParseError("'property' statements are only allowed within classes"); + this.currentToken = this.scanner.scan(); + ast = new TypeScript.AST(TypeScript.NodeType.Error); + ast.minChar = minChar; + ast.limChar = this.scanner.lastTokenLimChar(); + } else { + modifiers |= TypeScript.Modifiers.Public; + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.Get) { + this.prevIDTok = this.currentToken; + this.currentToken = this.scanner.scan(); + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("Property accessors are only available when targeting ES5 or greater"); + } + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + modifiers |= TypeScript.Modifiers.Getter; + this.prevIDTok = null; + } + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.Set) { + this.prevIDTok = this.currentToken; + this.currentToken = this.scanner.scan(); + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("Property accessors are only available when targeting ES5 or greater"); + } + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + modifiers |= TypeScript.Modifiers.Setter; + this.prevIDTok = null; + } + } + } + fnOrVar = this.parsePropertyDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, modifiers, isAmbient(), false); + if((fnOrVar.nodeType == TypeScript.NodeType.VarDecl) || ((fnOrVar.nodeType == TypeScript.NodeType.FuncDecl) && TypeScript.hasFlag((fnOrVar).fncFlags, TypeScript.FncFlags.IsFatArrowFunction))) { + needTerminator = true; + } + ast = fnOrVar; + } + } + break; + + } + case TypeScript.TokenID.Declare: { + if(!(allowedElements & TypeScript.AllowedElements.AmbientDeclarations)) { + this.reportParseError("Ambient declarations are only allowed at the top-level or module scopes"); + } + if(!this.parsingDeclareFile && TypeScript.hasFlag(parentModifiers, TypeScript.Modifiers.Ambient)) { + this.reportParseError("Duplicate ambient declaration in this context. (Is the enclosing module or class already ambient?)"); + } + modifiers |= TypeScript.Modifiers.Ambient; + this.currentToken = this.scanner.scan(); + break; + + } + case TypeScript.TokenID.Class: { + if((allowedElements & TypeScript.AllowedElements.ClassDeclarations) == TypeScript.AllowedElements.None) { + this.reportParseError("class not allowed in this context"); + this.currentToken = this.scanner.scan(); + ast = new TypeScript.AST(TypeScript.NodeType.Error); + ast.minChar = minChar; + ast.limChar = this.scanner.lastTokenLimChar(); + } else { + ast = this.parseClassDecl(errorRecoverySet, minChar, modifiers); + } + break; + + } + case TypeScript.TokenID.Interface: { + if((allowedElements & TypeScript.AllowedElements.InterfaceDeclarations) == TypeScript.AllowedElements.None) { + this.reportParseError("interface not allowed in this context"); + this.currentToken = this.scanner.scan(); + ast = new TypeScript.AST(TypeScript.NodeType.Error); + ast.minChar = minChar; + ast.limChar = this.scanner.lastTokenLimChar(); + } else { + ast = this.parseInterfaceDecl(errorRecoverySet, modifiers); + } + break; + + } + case TypeScript.TokenID.Var: { + var declAst = this.parseVariableDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart, modifiers, true, false); + if(declAst.nodeType == TypeScript.NodeType.VarDecl) { + ast = declAst; + } else { + ast = new TypeScript.Block(declAst, false); + } + needTerminator = true; + break; + + } + case TypeScript.TokenID.Static: { + if(this.currentClassDecl == null) { + this.reportParseError("Statics may only be class members"); + } + mayNotBeExported(); + modifiers |= TypeScript.Modifiers.Public; + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.Get) { + this.prevIDTok = this.currentToken; + this.currentToken = this.scanner.scan(); + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("Property accessors are only available when targeting ES5 or greater"); + } + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + modifiers |= TypeScript.Modifiers.Getter; + this.prevIDTok = null; + } + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.Set) { + this.currentToken = this.scanner.scan(); + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("Property accessors are only available when targeting ES5 or greater"); + } + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + modifiers |= TypeScript.Modifiers.Setter; + } + } + } + if(isAmbient()) { + modifiers |= TypeScript.Modifiers.Ambient; + } + fnOrVar = this.parsePropertyDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, modifiers, this.parsingDeclareFile || (modifiers & TypeScript.Modifiers.Ambient) != TypeScript.Modifiers.None, true); + var staticsList = this.topStaticsList(); + if(staticsList && fnOrVar.nodeType == TypeScript.NodeType.VarDecl) { + staticsList.append(fnOrVar); + } + if(fnOrVar.nodeType == TypeScript.NodeType.VarDecl || ((fnOrVar.nodeType == TypeScript.NodeType.FuncDecl) && TypeScript.hasFlag((fnOrVar).fncFlags, TypeScript.FncFlags.IsFatArrowFunction))) { + needTerminator = true; + } + ast = fnOrVar; + break; + + } + case TypeScript.TokenID.For: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("syntax error: for statement does not take modifiers"); + } + minChar = this.scanner.startPos; + this.checkNextToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart | TypeScript.ErrorRecoverySet.Var); + this.state = ParseState.ForInit; + forInOk = true; + switch(this.currentToken.tokenId) { + case TypeScript.TokenID.Var: { + temp = this.parseVariableDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon | TypeScript.ErrorRecoverySet.In, TypeScript.Modifiers.None, false, false); + break; + + } + case TypeScript.TokenID.Semicolon: { + temp = null; + this.state = ParseState.ForCondStart; + break; + + } + default: { + temp = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon | TypeScript.ErrorRecoverySet.In, TypeScript.OperatorPrecedence.None, false, TypeContext.NoTypes); + break; + + } + } + this.state = ParseState.ForInitAfterVar; + if(this.currentToken.tokenId == TypeScript.TokenID.In) { + if((temp == null) || (!forInOk)) { + this.reportParseError("malformed for statement"); + if(this.errorRecovery) { + this.skip(errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); + ast = new TypeScript.AST(TypeScript.NodeType.Empty); + ast.flags |= TypeScript.ASTFlags.Error; + } + } else { + this.currentToken = this.scanner.scan(); + var forInStmt = new TypeScript.ForInStatement(temp, this.parseExpr(TypeScript.ErrorRecoverySet.RParen | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, false, TypeContext.NoTypes)); + forInStmt.limChar = this.scanner.pos; + forInStmt.statement.minChar = minChar; + forInStmt.statement.limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseParen, TypeScript.ErrorRecoverySet.StmtStart | errorRecoverySet); + this.pushStmt(forInStmt, labelList); + forInStmt.body = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); + this.popStmt(); + forInStmt.minChar = minChar; + ast = forInStmt; + } + } else { + var forStmt = new TypeScript.ForStatement(temp); + forStmt.minChar = minChar; + this.checkCurrentToken(TypeScript.TokenID.Semicolon, errorRecoverySet); + if(this.currentToken.tokenId == TypeScript.TokenID.Semicolon) { + forStmt.cond = null; + } else { + forStmt.cond = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); + if(this.currentToken.tokenId != TypeScript.TokenID.Semicolon) { + this.skip(errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); + ast = forStmt; + ast.flags |= TypeScript.ASTFlags.Error; + } + } + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.CloseParen) { + forStmt.incr = null; + } else { + forStmt.incr = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); + } + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly); + this.pushStmt(forStmt, labelList); + forStmt.body = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); + this.popStmt(); + forStmt.limChar = forStmt.body.limChar; + ast = forStmt; + } + break; + + } + case TypeScript.TokenID.With: { + { + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("'with' statements are only available in ES5 codegen mode or better"); + } + if(this.strictMode) { + this.reportParseError("'with' statements are not available in strict mode"); + } + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("'with' statement does not take modifiers"); + } + minChar = this.scanner.startPos; + this.checkNextToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart | TypeScript.ErrorRecoverySet.Var); + var expr = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.Colon, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly); + var withStmt = new TypeScript.WithStatement(expr); + withStmt.body = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); + withStmt.minChar = minChar; + withStmt.limChar = withStmt.body.limChar; + ast = withStmt; + } + break; + + } + case TypeScript.TokenID.Switch: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("'switch' statement does not take modifiers"); + } + this.checkNextToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); + var switchStmt = new TypeScript.SwitchStatement(this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes)); + switchStmt.statement.minChar = minChar; + switchStmt.statement.limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly); + var caseListMinChar = this.scanner.startPos; + this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.SCase); + switchStmt.defaultCase = null; + switchStmt.caseList = new TypeScript.ASTList(); + var caseStmt = null; + this.pushStmt(switchStmt, labelList); + for(; ; ) { + if((this.currentToken.tokenId == TypeScript.TokenID.Case) || (this.currentToken.tokenId == TypeScript.TokenID.Default)) { + var isDefault = (this.currentToken.tokenId == TypeScript.TokenID.Default); + caseStmt = new TypeScript.CaseStatement(); + caseStmt.minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + if(isDefault) { + switchStmt.defaultCase = caseStmt; + } else { + caseStmt.expr = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.Colon, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); + } + this.checkCurrentToken(TypeScript.TokenID.Colon, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); + caseStmt.body = new TypeScript.ASTList(); + this.parseStatementList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, caseStmt.body, false, true, allowedElements, modifiers); + caseStmt.limChar = caseStmt.body.limChar; + switchStmt.caseList.append(caseStmt); + } else { + break; + } + } + switchStmt.caseList.minChar = caseListMinChar; + switchStmt.caseList.limChar = this.scanner.pos; + switchStmt.limChar = switchStmt.caseList.limChar; + this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); + this.popStmt(); + ast = switchStmt; + break; + } + + case TypeScript.TokenID.While: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("'while' statement does not take modifiers"); + } + minChar = this.scanner.startPos; + this.checkNextToken(TypeScript.TokenID.OpenParen, TypeScript.ErrorRecoverySet.ExprStart | errorRecoverySet); + var whileStmt = new TypeScript.WhileStatement(this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes)); + whileStmt.minChar = minChar; + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); + this.pushStmt(whileStmt, labelList); + whileStmt.body = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); + whileStmt.limChar = whileStmt.body.limChar; + this.popStmt(); + ast = whileStmt; + break; + } + + case TypeScript.TokenID.Do: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("'do' statement does not take modifiers"); + } + minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + var doStmt = new TypeScript.DoWhileStatement(); + doStmt.minChar = minChar; + this.pushStmt(doStmt, labelList); + doStmt.body = this.parseStatement(errorRecoverySet | TypeScript.ErrorRecoverySet.While, allowedElements, parentModifiers); + this.popStmt(); + doStmt.whileAST = new TypeScript.Identifier("while"); + doStmt.whileAST.minChar = this.scanner.startPos; + this.checkCurrentToken(TypeScript.TokenID.While, errorRecoverySet | TypeScript.ErrorRecoverySet.LParen); + doStmt.whileAST.limChar = doStmt.whileAST.minChar + 5; + this.checkCurrentToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); + doStmt.cond = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); + doStmt.limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet); + ast = doStmt; + if(this.currentToken.tokenId == TypeScript.TokenID.Semicolon) { + this.currentToken = this.scanner.scan(); + } + break; + } + + case TypeScript.TokenID.If: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("if statement does not take modifiers"); + } + minChar = this.scanner.startPos; + this.checkNextToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); + var ifStmt = new TypeScript.IfStatement(this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.LParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes)); + ifStmt.minChar = minChar; + ifStmt.statement.minChar = minChar; + ifStmt.statement.limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); + this.pushStmt(ifStmt, labelList); + ifStmt.thenBod = this.parseStatement(TypeScript.ErrorRecoverySet.Else | errorRecoverySet, allowedElements, parentModifiers); + ifStmt.limChar = ifStmt.thenBod.limChar; + if(this.currentToken.tokenId == TypeScript.TokenID.Else) { + this.currentToken = this.scanner.scan(); + ifStmt.elseBod = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); + ifStmt.limChar = ifStmt.elseBod.limChar; + } + this.popStmt(); + ast = ifStmt; + break; + } + + case TypeScript.TokenID.Try: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("try statement does not take modifiers"); + } + minChar = this.scanner.startPos; + ast = this.parseTryCatchFinally(errorRecoverySet, parentModifiers, labelList); + break; + } + + case TypeScript.TokenID.OpenBrace: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("block does not take modifiers"); + } + minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + var block = new TypeScript.Block(new TypeScript.ASTList(), true); + this.pushStmt(block, labelList); + this.parseStatementList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, block.statements, false, false, TypeScript.AllowedElements.None, modifiers); + this.popStmt(); + block.statements.minChar = minChar; + block.statements.limChar = this.scanner.pos; + block.minChar = block.statements.minChar; + block.limChar = block.statements.limChar; + this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); + ast = block; + break; + } + + case TypeScript.TokenID.Semicolon: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("modifier can not appear here"); + } + ast = new TypeScript.AST(TypeScript.NodeType.Empty); + this.currentToken = this.scanner.scan(); + break; + + } + case TypeScript.TokenID.Break: + case TypeScript.TokenID.Continue: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("modifiers can not appear before jump statement"); + } + var jump = new TypeScript.Jump((this.currentToken.tokenId == TypeScript.TokenID.Break) ? TypeScript.NodeType.Break : TypeScript.NodeType.Continue); + this.currentToken = this.scanner.scan(); + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) && (!this.scanner.lastTokenHadNewline())) { + jump.target = this.currentToken.getText(); + this.currentToken = this.scanner.scan(); + } + this.resolveJumpTarget(jump); + ast = jump; + needTerminator = true; + break; + } + + case TypeScript.TokenID.Return: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("modifiers can not appear before return statement"); + } + if(!this.inFunction) { + this.reportParseError("return statement outside of function body"); + } + minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + var retStmt = new TypeScript.ReturnStatement(); + retStmt.minChar = minChar; + if((this.currentToken.tokenId != TypeScript.TokenID.Semicolon) && (this.currentToken.tokenId != TypeScript.TokenID.CloseBrace) && (!(this.scanner.lastTokenHadNewline()))) { + retStmt.returnExpression = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); + } + needTerminator = true; + retStmt.limChar = this.scanner.lastTokenLimChar(); + ast = retStmt; + break; + } + + case TypeScript.TokenID.Throw: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("modifiers can not appear before a throw statement"); + } + minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + if((this.currentToken.tokenId != TypeScript.TokenID.Semicolon) && (this.currentToken.tokenId != TypeScript.TokenID.CloseBrace) && (!(this.scanner.lastTokenHadNewline()))) { + temp = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); + } else { + this.reportParseError("throw with no target"); + temp = null; + } + ast = new TypeScript.UnaryExpression(TypeScript.NodeType.Throw, temp); + ast.limChar = this.scanner.lastTokenLimChar(); + needTerminator = true; + break; + + } + case TypeScript.TokenID.Enum: { + this.currentToken = this.scanner.scan(); + ast = this.parseEnumDecl(errorRecoverySet, modifiers); + ast.minChar = minChar; + ast.limChar = this.scanner.lastTokenLimChar(); + if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + (ast).modFlags |= TypeScript.ModuleFlags.Ambient; + } + if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { + (ast).modFlags |= TypeScript.ModuleFlags.Exported; + } + break; + + } + case TypeScript.TokenID.Debugger: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("modifiers can not appear before debugger statement"); + } + minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + var debuggerStmt = new TypeScript.DebuggerStatement(); + debuggerStmt.minChar = minChar; + needTerminator = true; + debuggerStmt.limChar = this.scanner.lastTokenLimChar(); + ast = debuggerStmt; + break; + + } + default: { + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("modifiers can not appear before an expression statement or label"); + } + minChar = this.scanner.startPos; + var svPos = this.scanner.pos; + temp = this.parseExpr(TypeScript.ErrorRecoverySet.Colon | TypeScript.ErrorRecoverySet.StmtStart | errorRecoverySet, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); + if(this.scanner.pos == svPos) { + this.currentToken = this.scanner.scan(); + ast = temp; + } else { + if((this.currentToken.tokenId == TypeScript.TokenID.Colon) && (!this.scanner.lastTokenHadNewline()) && temp && (temp.nodeType == TypeScript.NodeType.Name)) { + if(labelList == null) { + labelList = new TypeScript.ASTList(); + } + labelList.append(new TypeScript.Label(temp)); + this.currentToken = this.scanner.scan(); + } else { + ast = temp; + needTerminator = true; + } + } + + } + } + if(ast) { + break; + } + } + if(needTerminator) { + switch(this.currentToken.tokenId) { + case TypeScript.TokenID.Semicolon: { + this.currentToken = this.scanner.scan(); + ast.flags |= TypeScript.ASTFlags.ExplicitSemicolon; + break; + + } + case TypeScript.TokenID.EndOfFile: { + ast.limChar = this.scanner.pos; + + } + case TypeScript.TokenID.CloseBrace: { + ast.flags |= TypeScript.ASTFlags.AutomaticSemicolon; + if(this.style_requireSemi) { + this.reportParseStyleError("no automatic semicolon"); + } + break; + + } + default: { + if(!this.scanner.lastTokenHadNewline()) { + this.reportParseError("Expected ';'"); + } else { + ast.flags |= TypeScript.ASTFlags.AutomaticSemicolon; + if(this.style_requireSemi) { + this.reportParseStyleError("no automatic semicolon"); + } + } + break; + + } + } + } + if(labelList) { + ast = new TypeScript.LabeledStatement(labelList, ast); + } + ast.minChar = minChar; + ast.limChar = TypeScript.max(ast.limChar, this.scanner.lastTokenLimChar()); + if(preComments) { + ast.preComments = preComments; + } + if(this.ambientModule && (!this.okAmbientModuleMember(ast))) { + this.reportParseError("statement not permitted within ambient module"); + } + ast.flags |= TypeScript.ASTFlags.IsStatement; + return ast; + }; + Parser.prototype.okAmbientModuleMember = function (ast) { + var nt = ast.nodeType; + return (nt == TypeScript.NodeType.ClassDeclaration) || (nt == TypeScript.NodeType.ImportDeclaration) || (nt == TypeScript.NodeType.InterfaceDeclaration) || (nt == TypeScript.NodeType.ModuleDeclaration) || (nt == TypeScript.NodeType.Empty) || (nt == TypeScript.NodeType.VarDecl) || ((nt == TypeScript.NodeType.Block) && !(ast).isStatementBlock) || ((nt == TypeScript.NodeType.FuncDecl) && ((ast).isMethod())); + }; + Parser.prototype.parseStatementList = function (errorRecoverySet, statements, sourceElms, noLeadingCase, allowedElements, parentModifiers) { + var directivePrologue = sourceElms; + statements.minChar = this.scanner.startPos; + var limChar = this.scanner.pos; + var innerStmts = (allowedElements & TypeScript.AllowedElements.ModuleDeclarations) == TypeScript.AllowedElements.None; + var classNope = (allowedElements & TypeScript.AllowedElements.ClassDeclarations) == TypeScript.AllowedElements.None; + errorRecoverySet |= TypeScript.ErrorRecoverySet.TypeScriptS | TypeScript.ErrorRecoverySet.RCurly; + this.state = ParseState.StartStatementList; + var oldStrictMode = this.strictMode; + this.nestingLevel++; + for(; ; ) { + if((this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) || (noLeadingCase && ((this.currentToken.tokenId == TypeScript.TokenID.Case) || (this.currentToken.tokenId == TypeScript.TokenID.Default))) || (innerStmts && (this.currentToken.tokenId == TypeScript.TokenID.Export)) || (classNope && (this.currentToken.tokenId == TypeScript.TokenID.Class)) || (this.currentToken.tokenId == TypeScript.TokenID.EndOfFile)) { + this.state = ParseState.EndStmtList; + statements.limChar = limChar; + if(statements.members.length == 0) { + statements.preComments = this.parseComments(); + } else { + statements.postComments = this.parseComments(); + } + this.strictMode = oldStrictMode; + this.nestingLevel--; + return; + } + var stmt = this.parseStatement(errorRecoverySet & (~(TypeScript.ErrorRecoverySet.Else | TypeScript.ErrorRecoverySet.RParen | TypeScript.ErrorRecoverySet.Catch | TypeScript.ErrorRecoverySet.Colon)), allowedElements, parentModifiers); + if(stmt) { + stmt.postComments = this.combineComments(stmt.postComments, this.parseCommentsForLine(this.scanner.prevLine)); + statements.append(stmt); + limChar = stmt.limChar; + if(directivePrologue) { + if(stmt.nodeType == TypeScript.NodeType.QString) { + var qstring = stmt; + if(qstring.text == "\"use strict\"") { + statements.flags |= TypeScript.ASTFlags.StrictMode; + this.strictMode = true; + } else { + directivePrologue = false; + } + } else { + directivePrologue = false; + } + } + } + } + }; + Parser.prototype.quickParse = function (sourceText, filename, unitIndex) { + var svGenTarget = TypeScript.moduleGenTarget; + try { + TypeScript.moduleGenTarget = TypeScript.ModuleGenTarget.Local; + var script = this.parse(sourceText, filename, unitIndex, TypeScript.AllowedElements.QuickParse); + return new QuickParseResult(script, this.scanner.lexState); + }finally { + TypeScript.moduleGenTarget = svGenTarget; + } + }; + Parser.prototype.parse = function (sourceText, filename, unitIndex, allowedElements) { + if (typeof allowedElements === "undefined") { allowedElements = TypeScript.AllowedElements.Global; } + var _this = this; + this.ambientModule = false; + this.topLevel = true; + this.hasTopLevelImportOrExport = false; + this.requiresExtendsBlock = false; + this.fname = filename; + this.currentUnitIndex = unitIndex; + this.amdDependencies = []; + this.scanner.resetComments(); + this.scanner.setErrorHandler(function (message) { + return _this.reportParseError(message); + }); + this.scanner.setSourceText(sourceText, TypeScript.LexMode.File); + var leftCurlyCount = this.scanner.leftCurlyCount; + var rightCurlyCount = this.scanner.rightCurlyCount; + var minChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + this.pushDeclLists(); + var bod = new TypeScript.ASTList(); + bod.minChar = minChar; + this.state = ParseState.StartScript; + this.parsingDeclareFile = TypeScript.isDSTRFile(filename) || TypeScript.isDTSFile(filename); + while(true) { + this.parseStatementList(TypeScript.ErrorRecoverySet.EOF | TypeScript.ErrorRecoverySet.Func, bod, true, false, allowedElements, TypeScript.Modifiers.None); + if(this.currentToken.tokenId === TypeScript.TokenID.EndOfFile) { + break; + } + var badToken = TypeScript.tokenTable[this.currentToken.tokenId]; + this.reportParseError("Unexpected statement block terminator '" + badToken.text + "'"); + this.currentToken = this.scanner.scan(); + } + this.state = ParseState.EndScript; + bod.limChar = this.scanner.pos; + var topLevelMod = null; + if(TypeScript.moduleGenTarget != TypeScript.ModuleGenTarget.Local && this.hasTopLevelImportOrExport) { + var correctedFileName = TypeScript.switchToForwardSlashes(filename); + var id = new TypeScript.Identifier(correctedFileName); + topLevelMod = new TypeScript.ModuleDeclaration(id, bod, this.topVarList(), this.topScopeList(), null); + topLevelMod.modFlags |= TypeScript.ModuleFlags.IsDynamic; + topLevelMod.modFlags |= TypeScript.ModuleFlags.IsWholeFile; + topLevelMod.modFlags |= TypeScript.ModuleFlags.Exported; + if(this.parsingDeclareFile) { + topLevelMod.modFlags |= TypeScript.ModuleFlags.Ambient; + } + topLevelMod.minChar = minChar; + topLevelMod.limChar = this.scanner.pos; + topLevelMod.prettyName = TypeScript.getPrettyName(correctedFileName); + topLevelMod.containsUnicodeChar = this.scanner.seenUnicodeChar; + topLevelMod.containsUnicodeCharInComment = this.scanner.seenUnicodeCharInComment; + topLevelMod.amdDependencies = this.amdDependencies; + bod = new TypeScript.ASTList(); + bod.minChar = topLevelMod.minChar; + bod.limChar = topLevelMod.limChar; + bod.append(topLevelMod); + } + var script = new TypeScript.Script(this.topVarList(), this.topScopeList()); + script.bod = bod; + this.popDeclLists(); + script.minChar = minChar; + script.limChar = this.scanner.pos; + script.locationInfo = new TypeScript.LocationInfo(filename, this.scanner.lineMap, unitIndex); + script.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; + script.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; + script.isDeclareFile = this.parsingDeclareFile; + script.topLevelMod = topLevelMod; + script.containsUnicodeChar = this.scanner.seenUnicodeChar; + script.containsUnicodeCharInComment = this.scanner.seenUnicodeCharInComment; + script.requiresExtendsBlock = this.requiresExtendsBlock; + return script; + }; + return Parser; + })(); + TypeScript.Parser = Parser; + function quickParse(logger, scopeStartAST, sourceText, minChar, limChar, errorCapture) { + var fragment = sourceText.getText(minChar, limChar); + logger.log("Quick parse range (" + minChar + "," + limChar + "): \"" + TypeScript.stringToLiteral(fragment, 100) + "\""); + var quickParser = new Parser(); + quickParser.setErrorRecovery(null); + quickParser.errorCallback = errorCapture; + var quickClassDecl = new TypeScript.ClassDeclaration(null, null, null, null); + quickParser.currentClassDecl = quickClassDecl; + var result = quickParser.quickParse(new TypeScript.StringSourceText(fragment), "", 0); + return result; + } + TypeScript.quickParse = quickParse; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var PrintContext = (function () { + function PrintContext(outfile, parser) { + this.outfile = outfile; + this.parser = parser; + this.builder = ""; + this.indent1 = " "; + this.indentStrings = []; + this.indentAmt = 0; + } + PrintContext.prototype.increaseIndent = function () { + this.indentAmt++; + }; + PrintContext.prototype.decreaseIndent = function () { + this.indentAmt--; + }; + PrintContext.prototype.startLine = function () { + if(this.builder.length > 0) { + TypeScript.CompilerDiagnostics.Alert(this.builder); + } + var indentString = this.indentStrings[this.indentAmt]; + if(indentString === undefined) { + indentString = ""; + for(var i = 0; i < this.indentAmt; i++) { + indentString += this.indent1; + } + this.indentStrings[this.indentAmt] = indentString; + } + this.builder += indentString; + }; + PrintContext.prototype.write = function (s) { + this.builder += s; + }; + PrintContext.prototype.writeLine = function (s) { + this.builder += s; + this.outfile.WriteLine(this.builder); + this.builder = ""; + }; + return PrintContext; + })(); + TypeScript.PrintContext = PrintContext; + function prePrintAST(ast, parent, walker) { + var pc = walker.state; + ast.print(pc); + pc.increaseIndent(); + return ast; + } + TypeScript.prePrintAST = prePrintAST; + function postPrintAST(ast, parent, walker) { + var pc = walker.state; + pc.decreaseIndent(); + return ast; + } + TypeScript.postPrintAST = postPrintAST; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + TypeScript.LexEOF = (-1); + TypeScript.LexCodeNWL = 10; + TypeScript.LexCodeRET = 13; + TypeScript.LexCodeLS = 8232; + TypeScript.LexCodePS = 8233; + TypeScript.LexCodeTAB = 9; + TypeScript.LexCodeVTAB = 11; + TypeScript.LexCode_e = 'e'.charCodeAt(0); + TypeScript.LexCode_E = 'E'.charCodeAt(0); + TypeScript.LexCode_x = 'x'.charCodeAt(0); + TypeScript.LexCode_X = 'X'.charCodeAt(0); + TypeScript.LexCode_a = 'a'.charCodeAt(0); + TypeScript.LexCode_A = 'A'.charCodeAt(0); + TypeScript.LexCode_f = 'f'.charCodeAt(0); + TypeScript.LexCode_F = 'F'.charCodeAt(0); + TypeScript.LexCode_g = 'g'.charCodeAt(0); + TypeScript.LexCode_m = 'm'.charCodeAt(0); + TypeScript.LexCode_i = 'i'.charCodeAt(0); + TypeScript.LexCode_u = 'u'.charCodeAt(0); + TypeScript.LexCode_0 = '0'.charCodeAt(0); + TypeScript.LexCode_9 = '9'.charCodeAt(0); + TypeScript.LexCode_8 = '8'.charCodeAt(0); + TypeScript.LexCode_7 = '7'.charCodeAt(0); + TypeScript.LexCodeBSL = '\\'.charCodeAt(0); + TypeScript.LexCodeSHP = '#'.charCodeAt(0); + TypeScript.LexCodeBNG = '!'.charCodeAt(0); + TypeScript.LexCodeQUO = '"'.charCodeAt(0); + TypeScript.LexCodeAPO = '\''.charCodeAt(0); + TypeScript.LexCodePCT = '%'.charCodeAt(0); + TypeScript.LexCodeAMP = '&'.charCodeAt(0); + TypeScript.LexCodeLPR = '('.charCodeAt(0); + TypeScript.LexCodeRPR = ')'.charCodeAt(0); + TypeScript.LexCodePLS = '+'.charCodeAt(0); + TypeScript.LexCodeMIN = '-'.charCodeAt(0); + TypeScript.LexCodeMUL = '*'.charCodeAt(0); + TypeScript.LexCodeSLH = '/'.charCodeAt(0); + TypeScript.LexCodeXOR = '^'.charCodeAt(0); + TypeScript.LexCodeCMA = ','.charCodeAt(0); + TypeScript.LexCodeDOT = '.'.charCodeAt(0); + TypeScript.LexCodeLT = '<'.charCodeAt(0); + TypeScript.LexCodeEQ = '='.charCodeAt(0); + TypeScript.LexCodeGT = '>'.charCodeAt(0); + TypeScript.LexCodeQUE = '?'.charCodeAt(0); + TypeScript.LexCodeLBR = '['.charCodeAt(0); + TypeScript.LexCodeRBR = ']'.charCodeAt(0); + TypeScript.LexCodeUSC = '_'.charCodeAt(0); + TypeScript.LexCodeLC = '{'.charCodeAt(0); + TypeScript.LexCodeRC = '}'.charCodeAt(0); + TypeScript.LexCodeBAR = '|'.charCodeAt(0); + TypeScript.LexCodeTIL = '~'.charCodeAt(0); + TypeScript.LexCodeCOL = ':'.charCodeAt(0); + TypeScript.LexCodeSMC = ';'.charCodeAt(0); + TypeScript.LexCodeUnderscore = '_'.charCodeAt(0); + TypeScript.LexCodeDollar = '$'.charCodeAt(0); + TypeScript.LexCodeSpace = 32; + TypeScript.LexCodeAtSign = '@'.charCodeAt(0); + TypeScript.LexCodeASCIIChars = 128; + TypeScript.LexKeywordTable = undefined; + var autoToken = new Array(TypeScript.LexCodeASCIIChars); + var lexIdStartTable = new Array(TypeScript.LexCodeASCIIChars); + var unicodeES3IdStart = [ + 170, + 170, + 181, + 181, + 186, + 186, + 192, + 214, + 216, + 246, + 248, + 543, + 546, + 563, + 592, + 685, + 688, + 696, + 699, + 705, + 720, + 721, + 736, + 740, + 750, + 750, + 890, + 890, + 902, + 902, + 904, + 906, + 908, + 908, + 910, + 929, + 931, + 974, + 976, + 983, + 986, + 1011, + 1024, + 1153, + 1164, + 1220, + 1223, + 1224, + 1227, + 1228, + 1232, + 1269, + 1272, + 1273, + 1329, + 1366, + 1369, + 1369, + 1377, + 1415, + 1488, + 1514, + 1520, + 1522, + 1569, + 1594, + 1600, + 1610, + 1649, + 1747, + 1749, + 1749, + 1765, + 1766, + 1786, + 1788, + 1808, + 1808, + 1810, + 1836, + 1920, + 1957, + 2309, + 2361, + 2365, + 2365, + 2384, + 2384, + 2392, + 2401, + 2437, + 2444, + 2447, + 2448, + 2451, + 2472, + 2474, + 2480, + 2482, + 2482, + 2486, + 2489, + 2524, + 2525, + 2527, + 2529, + 2544, + 2545, + 2565, + 2570, + 2575, + 2576, + 2579, + 2600, + 2602, + 2608, + 2610, + 2611, + 2613, + 2614, + 2616, + 2617, + 2649, + 2652, + 2654, + 2654, + 2674, + 2676, + 2693, + 2699, + 2701, + 2701, + 2703, + 2705, + 2707, + 2728, + 2730, + 2736, + 2738, + 2739, + 2741, + 2745, + 2749, + 2749, + 2768, + 2768, + 2784, + 2784, + 2821, + 2828, + 2831, + 2832, + 2835, + 2856, + 2858, + 2864, + 2866, + 2867, + 2870, + 2873, + 2877, + 2877, + 2908, + 2909, + 2911, + 2913, + 2949, + 2954, + 2958, + 2960, + 2962, + 2965, + 2969, + 2970, + 2972, + 2972, + 2974, + 2975, + 2979, + 2980, + 2984, + 2986, + 2990, + 2997, + 2999, + 3001, + 3077, + 3084, + 3086, + 3088, + 3090, + 3112, + 3114, + 3123, + 3125, + 3129, + 3168, + 3169, + 3205, + 3212, + 3214, + 3216, + 3218, + 3240, + 3242, + 3251, + 3253, + 3257, + 3294, + 3294, + 3296, + 3297, + 3333, + 3340, + 3342, + 3344, + 3346, + 3368, + 3370, + 3385, + 3424, + 3425, + 3461, + 3478, + 3482, + 3505, + 3507, + 3515, + 3517, + 3517, + 3520, + 3526, + 3585, + 3632, + 3634, + 3635, + 3648, + 3654, + 3713, + 3714, + 3716, + 3716, + 3719, + 3720, + 3722, + 3722, + 3725, + 3725, + 3732, + 3735, + 3737, + 3743, + 3745, + 3747, + 3749, + 3749, + 3751, + 3751, + 3754, + 3755, + 3757, + 3760, + 3762, + 3763, + 3773, + 3773, + 3776, + 3780, + 3782, + 3782, + 3804, + 3805, + 3840, + 3840, + 3904, + 3911, + 3913, + 3946, + 3976, + 3979, + 4096, + 4129, + 4131, + 4135, + 4137, + 4138, + 4176, + 4181, + 4256, + 4293, + 4304, + 4342, + 4352, + 4441, + 4447, + 4514, + 4520, + 4601, + 4608, + 4614, + 4616, + 4678, + 4680, + 4680, + 4682, + 4685, + 4688, + 4694, + 4696, + 4696, + 4698, + 4701, + 4704, + 4742, + 4744, + 4744, + 4746, + 4749, + 4752, + 4782, + 4784, + 4784, + 4786, + 4789, + 4792, + 4798, + 4800, + 4800, + 4802, + 4805, + 4808, + 4814, + 4816, + 4822, + 4824, + 4846, + 4848, + 4878, + 4880, + 4880, + 4882, + 4885, + 4888, + 4894, + 4896, + 4934, + 4936, + 4954, + 5024, + 5108, + 5121, + 5740, + 5743, + 5750, + 5761, + 5786, + 5792, + 5866, + 6016, + 6067, + 6176, + 6263, + 6272, + 6312, + 7680, + 7835, + 7840, + 7929, + 7936, + 7957, + 7960, + 7965, + 7968, + 8005, + 8008, + 8013, + 8016, + 8023, + 8025, + 8025, + 8027, + 8027, + 8029, + 8029, + 8031, + 8061, + 8064, + 8116, + 8118, + 8124, + 8126, + 8126, + 8130, + 8132, + 8134, + 8140, + 8144, + 8147, + 8150, + 8155, + 8160, + 8172, + 8178, + 8180, + 8182, + 8188, + 8319, + 8319, + 8450, + 8450, + 8455, + 8455, + 8458, + 8467, + 8469, + 8469, + 8473, + 8477, + 8484, + 8484, + 8486, + 8486, + 8488, + 8488, + 8490, + 8493, + 8495, + 8497, + 8499, + 8505, + 8544, + 8579, + 12293, + 12295, + 12321, + 12329, + 12337, + 12341, + 12344, + 12346, + 12353, + 12436, + 12445, + 12446, + 12449, + 12538, + 12540, + 12542, + 12549, + 12588, + 12593, + 12686, + 12704, + 12727, + 13312, + 13312, + 19893, + 19893, + 19968, + 19968, + 40869, + 40869, + 40960, + 42124, + 44032, + 44032, + 55203, + 55203, + 63744, + 64045, + 64256, + 64262, + 64275, + 64279, + 64285, + 64285, + 64287, + 64296, + 64298, + 64310, + 64312, + 64316, + 64318, + 64318, + 64320, + 64321, + 64323, + 64324, + 64326, + 64433, + 64467, + 64829, + 64848, + 64911, + 64914, + 64967, + 65008, + 65019, + 65136, + 65138, + 65140, + 65140, + 65142, + 65276, + 65313, + 65338, + 65345, + 65370, + 65382, + 65470, + 65474, + 65479, + 65482, + 65487, + 65490, + 65495, + 65498, + 65500 + ]; + var unicodeES3IdCont = [ + 768, + 846, + 864, + 866, + 1155, + 1158, + 1425, + 1441, + 1443, + 1465, + 1467, + 1469, + 1471, + 1471, + 1473, + 1474, + 1476, + 1476, + 1611, + 1621, + 1632, + 1641, + 1648, + 1648, + 1750, + 1756, + 1759, + 1764, + 1767, + 1768, + 1770, + 1773, + 1776, + 1785, + 1809, + 1809, + 1840, + 1866, + 1958, + 1968, + 2305, + 2307, + 2364, + 2364, + 2366, + 2381, + 2385, + 2388, + 2402, + 2403, + 2406, + 2415, + 2433, + 2435, + 2492, + 2492, + 2494, + 2500, + 2503, + 2504, + 2507, + 2509, + 2519, + 2519, + 2530, + 2531, + 2534, + 2543, + 2562, + 2562, + 2620, + 2620, + 2622, + 2626, + 2631, + 2632, + 2635, + 2637, + 2662, + 2673, + 2689, + 2691, + 2748, + 2748, + 2750, + 2757, + 2759, + 2761, + 2763, + 2765, + 2790, + 2799, + 2817, + 2819, + 2876, + 2876, + 2878, + 2883, + 2887, + 2888, + 2891, + 2893, + 2902, + 2903, + 2918, + 2927, + 2946, + 2947, + 3006, + 3010, + 3014, + 3016, + 3018, + 3021, + 3031, + 3031, + 3047, + 3055, + 3073, + 3075, + 3134, + 3140, + 3142, + 3144, + 3146, + 3149, + 3157, + 3158, + 3174, + 3183, + 3202, + 3203, + 3262, + 3268, + 3270, + 3272, + 3274, + 3277, + 3285, + 3286, + 3302, + 3311, + 3330, + 3331, + 3390, + 3395, + 3398, + 3400, + 3402, + 3405, + 3415, + 3415, + 3430, + 3439, + 3458, + 3459, + 3530, + 3530, + 3535, + 3540, + 3542, + 3542, + 3544, + 3551, + 3570, + 3571, + 3633, + 3633, + 3636, + 3642, + 3655, + 3662, + 3664, + 3673, + 3761, + 3761, + 3764, + 3769, + 3771, + 3772, + 3784, + 3789, + 3792, + 3801, + 3864, + 3865, + 3872, + 3881, + 3893, + 3893, + 3895, + 3895, + 3897, + 3897, + 3902, + 3903, + 3953, + 3972, + 3974, + 3975, + 3984, + 3991, + 3993, + 4028, + 4038, + 4038, + 4140, + 4146, + 4150, + 4153, + 4160, + 4169, + 4182, + 4185, + 4969, + 4977, + 6068, + 6099, + 6112, + 6121, + 6160, + 6169, + 6313, + 6313, + 8255, + 8256, + 8400, + 8412, + 8417, + 8417, + 12330, + 12335, + 12441, + 12442, + 12539, + 12539, + 64286, + 64286, + 65056, + 65059, + 65075, + 65076, + 65101, + 65103, + 65296, + 65305, + 65343, + 65343, + 65381, + 65381 + ]; + var unicodeES5IdStart = [ + 170, + 170, + 181, + 181, + 186, + 186, + 192, + 214, + 216, + 246, + 248, + 705, + 710, + 721, + 736, + 740, + 748, + 748, + 750, + 750, + 880, + 884, + 886, + 887, + 890, + 893, + 902, + 902, + 904, + 906, + 908, + 908, + 910, + 929, + 931, + 1013, + 1015, + 1153, + 1162, + 1319, + 1329, + 1366, + 1369, + 1369, + 1377, + 1415, + 1488, + 1514, + 1520, + 1522, + 1568, + 1610, + 1646, + 1647, + 1649, + 1747, + 1749, + 1749, + 1765, + 1766, + 1774, + 1775, + 1786, + 1788, + 1791, + 1791, + 1808, + 1808, + 1810, + 1839, + 1869, + 1957, + 1969, + 1969, + 1994, + 2026, + 2036, + 2037, + 2042, + 2042, + 2048, + 2069, + 2074, + 2074, + 2084, + 2084, + 2088, + 2088, + 2112, + 2136, + 2208, + 2208, + 2210, + 2220, + 2308, + 2361, + 2365, + 2365, + 2384, + 2384, + 2392, + 2401, + 2417, + 2423, + 2425, + 2431, + 2437, + 2444, + 2447, + 2448, + 2451, + 2472, + 2474, + 2480, + 2482, + 2482, + 2486, + 2489, + 2493, + 2493, + 2510, + 2510, + 2524, + 2525, + 2527, + 2529, + 2544, + 2545, + 2565, + 2570, + 2575, + 2576, + 2579, + 2600, + 2602, + 2608, + 2610, + 2611, + 2613, + 2614, + 2616, + 2617, + 2649, + 2652, + 2654, + 2654, + 2674, + 2676, + 2693, + 2701, + 2703, + 2705, + 2707, + 2728, + 2730, + 2736, + 2738, + 2739, + 2741, + 2745, + 2749, + 2749, + 2768, + 2768, + 2784, + 2785, + 2821, + 2828, + 2831, + 2832, + 2835, + 2856, + 2858, + 2864, + 2866, + 2867, + 2869, + 2873, + 2877, + 2877, + 2908, + 2909, + 2911, + 2913, + 2929, + 2929, + 2947, + 2947, + 2949, + 2954, + 2958, + 2960, + 2962, + 2965, + 2969, + 2970, + 2972, + 2972, + 2974, + 2975, + 2979, + 2980, + 2984, + 2986, + 2990, + 3001, + 3024, + 3024, + 3077, + 3084, + 3086, + 3088, + 3090, + 3112, + 3114, + 3123, + 3125, + 3129, + 3133, + 3133, + 3160, + 3161, + 3168, + 3169, + 3205, + 3212, + 3214, + 3216, + 3218, + 3240, + 3242, + 3251, + 3253, + 3257, + 3261, + 3261, + 3294, + 3294, + 3296, + 3297, + 3313, + 3314, + 3333, + 3340, + 3342, + 3344, + 3346, + 3386, + 3389, + 3389, + 3406, + 3406, + 3424, + 3425, + 3450, + 3455, + 3461, + 3478, + 3482, + 3505, + 3507, + 3515, + 3517, + 3517, + 3520, + 3526, + 3585, + 3632, + 3634, + 3635, + 3648, + 3654, + 3713, + 3714, + 3716, + 3716, + 3719, + 3720, + 3722, + 3722, + 3725, + 3725, + 3732, + 3735, + 3737, + 3743, + 3745, + 3747, + 3749, + 3749, + 3751, + 3751, + 3754, + 3755, + 3757, + 3760, + 3762, + 3763, + 3773, + 3773, + 3776, + 3780, + 3782, + 3782, + 3804, + 3807, + 3840, + 3840, + 3904, + 3911, + 3913, + 3948, + 3976, + 3980, + 4096, + 4138, + 4159, + 4159, + 4176, + 4181, + 4186, + 4189, + 4193, + 4193, + 4197, + 4198, + 4206, + 4208, + 4213, + 4225, + 4238, + 4238, + 4256, + 4293, + 4295, + 4295, + 4301, + 4301, + 4304, + 4346, + 4348, + 4680, + 4682, + 4685, + 4688, + 4694, + 4696, + 4696, + 4698, + 4701, + 4704, + 4744, + 4746, + 4749, + 4752, + 4784, + 4786, + 4789, + 4792, + 4798, + 4800, + 4800, + 4802, + 4805, + 4808, + 4822, + 4824, + 4880, + 4882, + 4885, + 4888, + 4954, + 4992, + 5007, + 5024, + 5108, + 5121, + 5740, + 5743, + 5759, + 5761, + 5786, + 5792, + 5866, + 5870, + 5872, + 5888, + 5900, + 5902, + 5905, + 5920, + 5937, + 5952, + 5969, + 5984, + 5996, + 5998, + 6000, + 6016, + 6067, + 6103, + 6103, + 6108, + 6108, + 6176, + 6263, + 6272, + 6312, + 6314, + 6314, + 6320, + 6389, + 6400, + 6428, + 6480, + 6509, + 6512, + 6516, + 6528, + 6571, + 6593, + 6599, + 6656, + 6678, + 6688, + 6740, + 6823, + 6823, + 6917, + 6963, + 6981, + 6987, + 7043, + 7072, + 7086, + 7087, + 7098, + 7141, + 7168, + 7203, + 7245, + 7247, + 7258, + 7293, + 7401, + 7404, + 7406, + 7409, + 7413, + 7414, + 7424, + 7615, + 7680, + 7957, + 7960, + 7965, + 7968, + 8005, + 8008, + 8013, + 8016, + 8023, + 8025, + 8025, + 8027, + 8027, + 8029, + 8029, + 8031, + 8061, + 8064, + 8116, + 8118, + 8124, + 8126, + 8126, + 8130, + 8132, + 8134, + 8140, + 8144, + 8147, + 8150, + 8155, + 8160, + 8172, + 8178, + 8180, + 8182, + 8188, + 8305, + 8305, + 8319, + 8319, + 8336, + 8348, + 8450, + 8450, + 8455, + 8455, + 8458, + 8467, + 8469, + 8469, + 8473, + 8477, + 8484, + 8484, + 8486, + 8486, + 8488, + 8488, + 8490, + 8493, + 8495, + 8505, + 8508, + 8511, + 8517, + 8521, + 8526, + 8526, + 8544, + 8584, + 11264, + 11310, + 11312, + 11358, + 11360, + 11492, + 11499, + 11502, + 11506, + 11507, + 11520, + 11557, + 11559, + 11559, + 11565, + 11565, + 11568, + 11623, + 11631, + 11631, + 11648, + 11670, + 11680, + 11686, + 11688, + 11694, + 11696, + 11702, + 11704, + 11710, + 11712, + 11718, + 11720, + 11726, + 11728, + 11734, + 11736, + 11742, + 11823, + 11823, + 12293, + 12295, + 12321, + 12329, + 12337, + 12341, + 12344, + 12348, + 12353, + 12438, + 12445, + 12447, + 12449, + 12538, + 12540, + 12543, + 12549, + 12589, + 12593, + 12686, + 12704, + 12730, + 12784, + 12799, + 13312, + 13312, + 19893, + 19893, + 19968, + 19968, + 40908, + 40908, + 40960, + 42124, + 42192, + 42237, + 42240, + 42508, + 42512, + 42527, + 42538, + 42539, + 42560, + 42606, + 42623, + 42647, + 42656, + 42735, + 42775, + 42783, + 42786, + 42888, + 42891, + 42894, + 42896, + 42899, + 42912, + 42922, + 43000, + 43009, + 43011, + 43013, + 43015, + 43018, + 43020, + 43042, + 43072, + 43123, + 43138, + 43187, + 43250, + 43255, + 43259, + 43259, + 43274, + 43301, + 43312, + 43334, + 43360, + 43388, + 43396, + 43442, + 43471, + 43471, + 43520, + 43560, + 43584, + 43586, + 43588, + 43595, + 43616, + 43638, + 43642, + 43642, + 43648, + 43695, + 43697, + 43697, + 43701, + 43702, + 43705, + 43709, + 43712, + 43712, + 43714, + 43714, + 43739, + 43741, + 43744, + 43754, + 43762, + 43764, + 43777, + 43782, + 43785, + 43790, + 43793, + 43798, + 43808, + 43814, + 43816, + 43822, + 43968, + 44002, + 44032, + 44032, + 55203, + 55203, + 55216, + 55238, + 55243, + 55291, + 63744, + 64109, + 64112, + 64217, + 64256, + 64262, + 64275, + 64279, + 64285, + 64285, + 64287, + 64296, + 64298, + 64310, + 64312, + 64316, + 64318, + 64318, + 64320, + 64321, + 64323, + 64324, + 64326, + 64433, + 64467, + 64829, + 64848, + 64911, + 64914, + 64967, + 65008, + 65019, + 65136, + 65140, + 65142, + 65276, + 65313, + 65338, + 65345, + 65370, + 65382, + 65470, + 65474, + 65479, + 65482, + 65487, + 65490, + 65495, + 65498, + 65500 + ]; + var unicodeES5IdCont = [ + 768, + 879, + 1155, + 1159, + 1425, + 1469, + 1471, + 1471, + 1473, + 1474, + 1476, + 1477, + 1479, + 1479, + 1552, + 1562, + 1611, + 1641, + 1648, + 1648, + 1750, + 1756, + 1759, + 1764, + 1767, + 1768, + 1770, + 1773, + 1776, + 1785, + 1809, + 1809, + 1840, + 1866, + 1958, + 1968, + 1984, + 1993, + 2027, + 2035, + 2070, + 2073, + 2075, + 2083, + 2085, + 2087, + 2089, + 2093, + 2137, + 2139, + 2276, + 2302, + 2304, + 2307, + 2362, + 2364, + 2366, + 2383, + 2385, + 2391, + 2402, + 2403, + 2406, + 2415, + 2433, + 2435, + 2492, + 2492, + 2494, + 2500, + 2503, + 2504, + 2507, + 2509, + 2519, + 2519, + 2530, + 2531, + 2534, + 2543, + 2561, + 2563, + 2620, + 2620, + 2622, + 2626, + 2631, + 2632, + 2635, + 2637, + 2641, + 2641, + 2662, + 2673, + 2677, + 2677, + 2689, + 2691, + 2748, + 2748, + 2750, + 2757, + 2759, + 2761, + 2763, + 2765, + 2786, + 2787, + 2790, + 2799, + 2817, + 2819, + 2876, + 2876, + 2878, + 2884, + 2887, + 2888, + 2891, + 2893, + 2902, + 2903, + 2914, + 2915, + 2918, + 2927, + 2946, + 2946, + 3006, + 3010, + 3014, + 3016, + 3018, + 3021, + 3031, + 3031, + 3046, + 3055, + 3073, + 3075, + 3134, + 3140, + 3142, + 3144, + 3146, + 3149, + 3157, + 3158, + 3170, + 3171, + 3174, + 3183, + 3202, + 3203, + 3260, + 3260, + 3262, + 3268, + 3270, + 3272, + 3274, + 3277, + 3285, + 3286, + 3298, + 3299, + 3302, + 3311, + 3330, + 3331, + 3390, + 3396, + 3398, + 3400, + 3402, + 3405, + 3415, + 3415, + 3426, + 3427, + 3430, + 3439, + 3458, + 3459, + 3530, + 3530, + 3535, + 3540, + 3542, + 3542, + 3544, + 3551, + 3570, + 3571, + 3633, + 3633, + 3636, + 3642, + 3655, + 3662, + 3664, + 3673, + 3761, + 3761, + 3764, + 3769, + 3771, + 3772, + 3784, + 3789, + 3792, + 3801, + 3864, + 3865, + 3872, + 3881, + 3893, + 3893, + 3895, + 3895, + 3897, + 3897, + 3902, + 3903, + 3953, + 3972, + 3974, + 3975, + 3981, + 3991, + 3993, + 4028, + 4038, + 4038, + 4139, + 4158, + 4160, + 4169, + 4182, + 4185, + 4190, + 4192, + 4194, + 4196, + 4199, + 4205, + 4209, + 4212, + 4226, + 4237, + 4239, + 4253, + 4957, + 4959, + 5906, + 5908, + 5938, + 5940, + 5970, + 5971, + 6002, + 6003, + 6068, + 6099, + 6109, + 6109, + 6112, + 6121, + 6155, + 6157, + 6160, + 6169, + 6313, + 6313, + 6432, + 6443, + 6448, + 6459, + 6470, + 6479, + 6576, + 6592, + 6600, + 6601, + 6608, + 6617, + 6679, + 6683, + 6741, + 6750, + 6752, + 6780, + 6783, + 6793, + 6800, + 6809, + 6912, + 6916, + 6964, + 6980, + 6992, + 7001, + 7019, + 7027, + 7040, + 7042, + 7073, + 7085, + 7088, + 7097, + 7142, + 7155, + 7204, + 7223, + 7232, + 7241, + 7248, + 7257, + 7376, + 7378, + 7380, + 7400, + 7405, + 7405, + 7410, + 7412, + 7616, + 7654, + 7676, + 7679, + 8204, + 8205, + 8255, + 8256, + 8276, + 8276, + 8400, + 8412, + 8417, + 8417, + 8421, + 8432, + 11503, + 11505, + 11647, + 11647, + 11744, + 11775, + 12330, + 12335, + 12441, + 12442, + 42528, + 42537, + 42607, + 42607, + 42612, + 42621, + 42655, + 42655, + 42736, + 42737, + 43010, + 43010, + 43014, + 43014, + 43019, + 43019, + 43043, + 43047, + 43136, + 43137, + 43188, + 43204, + 43216, + 43225, + 43232, + 43249, + 43264, + 43273, + 43302, + 43309, + 43335, + 43347, + 43392, + 43395, + 43443, + 43456, + 43472, + 43481, + 43561, + 43574, + 43587, + 43587, + 43596, + 43597, + 43600, + 43609, + 43643, + 43643, + 43696, + 43696, + 43698, + 43700, + 43703, + 43704, + 43710, + 43711, + 43713, + 43713, + 43755, + 43759, + 43765, + 43766, + 44003, + 44010, + 44012, + 44013, + 44016, + 44025, + 64286, + 64286, + 65024, + 65039, + 65056, + 65062, + 65075, + 65076, + 65101, + 65103, + 65296, + 65305, + 65343, + 65343 + ]; + function LexLookUpUnicodeMap(code, map) { + var lo = 0; + var hi = map.length; + var mid; + while(lo + 1 < hi) { + mid = lo + (hi - lo) / 2; + mid -= mid % 2; + if(map[mid] <= code && code <= map[mid + 1]) { + return true; + } + if(code < map[mid]) { + hi = mid; + } else { + lo = mid + 2; + } + } + return false; + } + TypeScript.LexLookUpUnicodeMap = LexLookUpUnicodeMap; + function LexIsUnicodeDigit(code) { + if(TypeScript.codeGenTarget == TypeScript.CodeGenTarget.ES3) { + return LexLookUpUnicodeMap(code, unicodeES3IdCont); + } else { + return LexLookUpUnicodeMap(code, unicodeES5IdCont); + } + } + TypeScript.LexIsUnicodeDigit = LexIsUnicodeDigit; + function LexIsUnicodeIdStart(code) { + if(TypeScript.codeGenTarget == TypeScript.CodeGenTarget.ES3) { + return LexLookUpUnicodeMap(code, unicodeES3IdStart); + } else { + return LexLookUpUnicodeMap(code, unicodeES5IdStart); + } + } + TypeScript.LexIsUnicodeIdStart = LexIsUnicodeIdStart; + function LexInitialize() { + TypeScript.initializeStaticTokens(); + autoToken[TypeScript.LexCodeLPR] = TypeScript.staticTokens[TypeScript.TokenID.OpenParen]; + autoToken[TypeScript.LexCodeRPR] = TypeScript.staticTokens[TypeScript.TokenID.CloseParen]; + autoToken[TypeScript.LexCodeCMA] = TypeScript.staticTokens[TypeScript.TokenID.Comma]; + autoToken[TypeScript.LexCodeSMC] = TypeScript.staticTokens[TypeScript.TokenID.Semicolon]; + autoToken[TypeScript.LexCodeLBR] = TypeScript.staticTokens[TypeScript.TokenID.OpenBracket]; + autoToken[TypeScript.LexCodeRBR] = TypeScript.staticTokens[TypeScript.TokenID.CloseBracket]; + autoToken[TypeScript.LexCodeTIL] = TypeScript.staticTokens[TypeScript.TokenID.Tilde]; + autoToken[TypeScript.LexCodeQUE] = TypeScript.staticTokens[TypeScript.TokenID.Question]; + autoToken[TypeScript.LexCodeLC] = TypeScript.staticTokens[TypeScript.TokenID.OpenBrace]; + autoToken[TypeScript.LexCodeRC] = TypeScript.staticTokens[TypeScript.TokenID.CloseBrace]; + autoToken[TypeScript.LexCodeCOL] = TypeScript.staticTokens[TypeScript.TokenID.Colon]; + TypeScript.LexKeywordTable = new TypeScript.StringHashTable(); + for(var i in (TypeScript.TokenID)._map) { + if((i) <= TypeScript.TokenID.LimKeyword) { + TypeScript.LexKeywordTable.add((TypeScript.TokenID)._map[i].toLowerCase(), i); + } + } + for(var j = 0; j < TypeScript.LexCodeASCIIChars; j++) { + if(LexIsIdentifierStartChar(j)) { + lexIdStartTable[j] = true; + } else { + lexIdStartTable[j] = false; + } + } + } + TypeScript.LexInitialize = LexInitialize; + function LexAdjustIndent(code, indentAmt) { + if((code == TypeScript.LexCodeLBR) || (code == TypeScript.LexCodeLC) || (code == TypeScript.LexCodeLPR)) { + return indentAmt + 1; + } else { + if((code == TypeScript.LexCodeRBR) || (code == TypeScript.LexCodeRC) || (code == TypeScript.LexCodeRPR)) { + return indentAmt - 1; + } else { + return indentAmt; + } + } + } + TypeScript.LexAdjustIndent = LexAdjustIndent; + function LexIsIdentifierStartChar(code) { + return (((code >= 97) && (code <= 122)) || ((code >= 65) && (code <= 90)) || (code == TypeScript.LexCodeDollar) || (code == TypeScript.LexCodeUnderscore)); + } + TypeScript.LexIsIdentifierStartChar = LexIsIdentifierStartChar; + function LexIsDigit(code) { + return ((code >= 48) && (code <= 57)); + } + TypeScript.LexIsDigit = LexIsDigit; + function LexIsIdentifierChar(code) { + return lexIdStartTable[code] || LexIsDigit(code); + } + TypeScript.LexIsIdentifierChar = LexIsIdentifierChar; + function LexMatchingOpen(code) { + if(code == TypeScript.LexCodeRBR) { + return TypeScript.LexCodeLBR; + } else { + if(code == TypeScript.LexCodeRC) { + return TypeScript.LexCodeLC; + } else { + if(code == TypeScript.LexCodeRPR) { + return TypeScript.LexCodeLPR; + } else { + return 0; + } + } + } + } + TypeScript.LexMatchingOpen = LexMatchingOpen; + (function (NumberScanState) { + NumberScanState._map = []; + NumberScanState._map[0] = "Start"; + NumberScanState.Start = 0; + NumberScanState._map[1] = "InFraction"; + NumberScanState.InFraction = 1; + NumberScanState._map[2] = "InEmptyFraction"; + NumberScanState.InEmptyFraction = 2; + NumberScanState._map[3] = "InExponent"; + NumberScanState.InExponent = 3; + })(TypeScript.NumberScanState || (TypeScript.NumberScanState = {})); + var NumberScanState = TypeScript.NumberScanState; + (function (LexState) { + LexState._map = []; + LexState._map[0] = "Start"; + LexState.Start = 0; + LexState._map[1] = "InMultilineComment"; + LexState.InMultilineComment = 1; + LexState._map[2] = "InMultilineSingleQuoteString"; + LexState.InMultilineSingleQuoteString = 2; + LexState._map[3] = "InMultilineDoubleQuoteString"; + LexState.InMultilineDoubleQuoteString = 3; + })(TypeScript.LexState || (TypeScript.LexState = {})); + var LexState = TypeScript.LexState; + (function (LexMode) { + LexMode._map = []; + LexMode._map[0] = "Line"; + LexMode.Line = 0; + LexMode._map[1] = "File"; + LexMode.File = 1; + })(TypeScript.LexMode || (TypeScript.LexMode = {})); + var LexMode = TypeScript.LexMode; + (function (CommentStyle) { + CommentStyle._map = []; + CommentStyle._map[0] = "Line"; + CommentStyle.Line = 0; + CommentStyle._map[1] = "Block"; + CommentStyle.Block = 1; + })(TypeScript.CommentStyle || (TypeScript.CommentStyle = {})); + var CommentStyle = TypeScript.CommentStyle; + var StringSourceText = (function () { + function StringSourceText(text) { + this.text = text; + } + StringSourceText.prototype.getText = function (start, end) { + return this.text.substring(start, end); + }; + StringSourceText.prototype.getLength = function () { + return this.text.length; + }; + return StringSourceText; + })(); + TypeScript.StringSourceText = StringSourceText; + var SourceTextSegment = (function () { + function SourceTextSegment(segmentStart, segmentEnd, segment) { + this.segmentStart = segmentStart; + this.segmentEnd = segmentEnd; + this.segment = segment; + } + SourceTextSegment.prototype.charCodeAt = function (index) { + return this.segment.charCodeAt(index - this.segmentStart); + }; + SourceTextSegment.prototype.substring = function (start, end) { + return this.segment.substring(start - this.segmentStart, end - this.segmentStart); + }; + return SourceTextSegment; + })(); + TypeScript.SourceTextSegment = SourceTextSegment; + var AggerateSourceTextSegment = (function () { + function AggerateSourceTextSegment(seg1, seg2) { + this.seg1 = seg1; + this.seg2 = seg2; + } + AggerateSourceTextSegment.prototype.charCodeAt = function (index) { + if(this.seg1.segmentStart <= index && index < this.seg1.segmentEnd) { + return this.seg1.segment.charCodeAt(index - this.seg1.segmentStart); + } + return this.seg2.segment.charCodeAt(index - this.seg2.segmentStart); + }; + AggerateSourceTextSegment.prototype.substring = function (start, end) { + if(this.seg1.segmentStart <= start && end <= this.seg1.segmentEnd) { + return this.seg1.segment.substring(start - this.seg1.segmentStart, end - this.seg1.segmentStart); + } + return this.seg2.segment.substring(start - this.seg2.segmentStart) + this.seg1.segment.substring(0, end - this.seg1.segmentStart); + }; + return AggerateSourceTextSegment; + })(); + TypeScript.AggerateSourceTextSegment = AggerateSourceTextSegment; + var ScannerTextStream = (function () { + function ScannerTextStream(sourceText) { + this.sourceText = sourceText; + this.agg = new AggerateSourceTextSegment(ScannerTextStream.emptySegment, ScannerTextStream.emptySegment); + this.len = this.sourceText.getLength(); + } + ScannerTextStream.emptySegment = new SourceTextSegment(0, 0, ""); + ScannerTextStream.prototype.max = function (a, b) { + return a >= b ? a : b; + }; + ScannerTextStream.prototype.min = function (a, b) { + return a <= b ? a : b; + }; + ScannerTextStream.prototype.fetchSegment = function (start, end) { + if(this.agg.seg1.segmentStart <= start && end <= this.agg.seg1.segmentEnd) { + return this.agg.seg1; + } + if(this.agg.seg2.segmentStart <= start && end <= this.agg.seg1.segmentEnd) { + return this.agg; + } + var prev = this.agg.seg1; + var s = prev.segmentEnd; + var e = TypeScript.max(s + 512, end); + e = TypeScript.min(e, this.len); + var src = this.sourceText.getText(s, e); + var newSeg = new SourceTextSegment(s, e, src); + this.agg.seg2 = prev; + this.agg.seg1 = newSeg; + return this.agg; + }; + ScannerTextStream.prototype.charCodeAt = function (index) { + return this.fetchSegment(index, index + 1).charCodeAt(index); + }; + ScannerTextStream.prototype.substring = function (start, end) { + return this.fetchSegment(start, end).substring(start, end); + }; + return ScannerTextStream; + })(); + TypeScript.ScannerTextStream = ScannerTextStream; + var SavedTokens = (function () { + function SavedTokens() { + this.prevToken = null; + this.curSavedToken = null; + this.prevSavedToken = null; + this.prevToken = null; + this.currentToken = 0; + this.tokens = new Array(); + this.seenUnicodeChar = false; + this.seenUnicodeCharInComment = false; + this.prevLine = 1; + this.line = 1; + this.col = 0; + this.lexState = LexState.Start; + this.commentStack = new Array(); + this.lineMap = []; + } + SavedTokens.prototype.previousToken = function () { + return this.prevToken; + }; + SavedTokens.prototype.close = function () { + this.currentToken = 0; + }; + SavedTokens.prototype.addToken = function (tok, scanner) { + this.tokens[this.currentToken++] = new TypeScript.SavedToken(tok, scanner.startPos, scanner.pos); + }; + SavedTokens.prototype.scan = function () { + this.startLine = this.line; + this.startPos = this.col; + if(this.currentTokenIndex == this.currentTokens.length) { + if(this.line < this.lineMap.length) { + this.line++; + this.col = 0; + this.currentTokenIndex = 0; + this.currentTokens = this.tokensByLine[this.line]; + } else { + return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; + } + } + if(this.currentTokenIndex < this.currentTokens.length) { + this.prevToken = this.curSavedToken.tok; + this.prevSavedToken = this.curSavedToken; + this.curSavedToken = this.currentTokens[this.currentTokenIndex++]; + var curToken = this.curSavedToken.tok; + this.pos = this.curSavedToken.limChar; + this.col += (this.curSavedToken.limChar - this.curSavedToken.minChar); + this.startPos = this.curSavedToken.minChar; + this.prevLine = this.line; + return curToken; + } else { + return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; + } + }; + SavedTokens.prototype.syncToTok = function (offset) { + this.line = getLineNumberFromPosition(this.lineMap, offset); + this.currentTokenIndex = 0; + var tmpCol = offset - this.lineMap[this.line]; + while((this.lexStateByLine[this.line] == LexState.InMultilineComment) && (this.line > 0)) { + this.line--; + tmpCol = 0; + } + var lenMin1 = this.lineMap.length - 1; + this.currentTokens = this.tokensByLine[this.line]; + while((this.currentTokens.length == 0) && (this.line < lenMin1)) { + this.line++; + this.currentTokens = this.tokensByLine[this.line]; + tmpCol = 0; + } + if(this.line <= lenMin1) { + while((this.currentTokenIndex < this.currentTokens.length) && (tmpCol > this.currentTokens[this.currentTokenIndex].limChar)) { + this.currentTokenIndex++; + } + if(this.currentTokenIndex < this.currentTokens.length) { + this.col = this.currentTokens[this.currentTokenIndex].minChar; + return this.col + this.lineMap[this.line]; + } + } + return -1; + }; + SavedTokens.prototype.lastTokenLimChar = function () { + if(this.prevSavedToken !== null) { + return this.prevSavedToken.limChar; + } else { + return 0; + } + }; + SavedTokens.prototype.lastTokenHadNewline = function () { + return this.prevLine != this.startLine; + }; + SavedTokens.prototype.pushComment = function (comment) { + this.commentStack.push(comment); + }; + SavedTokens.prototype.getComments = function () { + var stack = this.commentStack; + this.commentStack = []; + return stack; + }; + SavedTokens.prototype.getCommentsForLine = function (line) { + var comments = null; + while((this.commentStack.length > 0) && (this.commentStack[0].line == line)) { + if(comments == null) { + comments = [ + this.commentStack.shift() + ]; + } else { + comments = comments.concat([ + this.commentStack.shift() + ]); + } + } + return comments; + }; + SavedTokens.prototype.resetComments = function () { + this.commentStack = []; + }; + SavedTokens.prototype.setSourceText = function (newSrc, textMode) { + }; + SavedTokens.prototype.setErrorHandler = function (reportError) { + }; + SavedTokens.prototype.getLookAheadToken = function () { + throw new Error("Invalid operation."); + }; + return SavedTokens; + })(); + TypeScript.SavedTokens = SavedTokens; + var Scanner = (function () { + function Scanner() { + this.prevLine = 1; + this.line = 1; + this.col = 0; + this.pos = 0; + this.startPos = 0; + this.len = 0; + this.lineMap = []; + this.ch = TypeScript.LexEOF; + this.lexState = LexState.Start; + this.mode = LexMode.File; + this.scanComments = true; + this.interveningWhitespace = false; + this.interveningWhitespacePos = 0; + this.leftCurlyCount = 0; + this.rightCurlyCount = 0; + this.commentStack = new Array(); + this.saveScan = null; + this.seenUnicodeChar = false; + this.seenUnicodeCharInComment = false; + this.prevTok = TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; + this.startCol = this.col; + this.startLine = this.line; + this.lineMap[1] = 0; + if(!TypeScript.LexKeywordTable) { + LexInitialize(); + } + } + Scanner.prototype.previousToken = function () { + return this.prevTok; + }; + Scanner.prototype.setSourceText = function (newSrc, textMode) { + this.mode = textMode; + this.scanComments = (this.mode === LexMode.Line); + this.pos = 0; + this.interveningWhitespacePos = 0; + this.startPos = 0; + this.line = 1; + this.col = 0; + this.startCol = this.col; + this.startLine = this.line; + this.len = 0; + this.src = newSrc.getText(0, newSrc.getLength()); + this.len = this.src.length; + this.lineMap = []; + this.lineMap[1] = 0; + this.commentStack = []; + this.leftCurlyCount = 0; + this.rightCurlyCount = 0; + this.seenUnicodeChar = false; + this.seenUnicodeCharInComment = false; + }; + Scanner.prototype.setErrorHandler = function (reportError) { + this.reportError = reportError; + }; + Scanner.prototype.setSaveScan = function (savedTokens) { + this.saveScan = savedTokens; + }; + Scanner.prototype.setText = function (newSrc, textMode) { + this.setSourceText(new StringSourceText(newSrc), textMode); + }; + Scanner.prototype.setScanComments = function (value) { + this.scanComments = value; + }; + Scanner.prototype.getLexState = function () { + return this.lexState; + }; + Scanner.prototype.tokenStart = function () { + this.startPos = this.pos; + this.startLine = this.line; + this.startCol = this.col; + this.interveningWhitespace = false; + }; + Scanner.prototype.peekChar = function () { + if(this.pos < this.len) { + return this.src.charCodeAt(this.pos); + } else { + return TypeScript.LexEOF; + } + }; + Scanner.prototype.peekCharAt = function (index) { + if(index < this.len) { + return this.src.charCodeAt(index); + } else { + return TypeScript.LexEOF; + } + }; + Scanner.prototype.IsHexDigit = function (c) { + return ((c >= TypeScript.LexCode_0) && (c <= TypeScript.LexCode_9)) || ((c >= TypeScript.LexCode_A) && (c <= TypeScript.LexCode_F)) || ((c >= TypeScript.LexCode_a) && (c <= TypeScript.LexCode_f)); + }; + Scanner.prototype.IsOctalDigit = function (c) { + return ((c >= TypeScript.LexCode_0) && (c <= TypeScript.LexCode_7)) || ((c >= TypeScript.LexCode_a) && (c <= TypeScript.LexCode_f)); + }; + Scanner.prototype.scanHexDigits = function () { + var atLeastOneDigit = false; + for(; ; ) { + if(this.IsHexDigit(this.ch)) { + this.nextChar(); + atLeastOneDigit = true; + } else { + if(atLeastOneDigit) { + return new TypeScript.NumberLiteralToken(parseInt(this.src.substring(this.startPos, this.pos))); + } else { + return null; + } + } + } + }; + Scanner.prototype.scanOctalDigits = function () { + var atLeastOneDigit = false; + for(; ; ) { + if(this.IsOctalDigit(this.ch)) { + this.nextChar(); + atLeastOneDigit = true; + } else { + if(atLeastOneDigit) { + return new TypeScript.NumberLiteralToken(parseInt(this.src.substring(this.startPos, this.pos))); + } else { + return null; + } + } + } + }; + Scanner.prototype.scanDecimalNumber = function (state) { + var atLeastOneDigit = false; + var svPos = this.pos; + var svCol = this.col; + for(; ; ) { + if(LexIsDigit(this.ch)) { + atLeastOneDigit = true; + if(this.ch != TypeScript.LexCode_0 && state == NumberScanState.InEmptyFraction) { + state = NumberScanState.InFraction; + } + this.nextChar(); + } else { + if(this.ch == TypeScript.LexCodeDOT) { + if(state == NumberScanState.Start) { + this.nextChar(); + state = NumberScanState.InEmptyFraction; + } else { + if(atLeastOneDigit) { + return new TypeScript.NumberLiteralToken(parseFloat(this.src.substring(this.startPos, this.pos)), state == NumberScanState.InEmptyFraction); + } else { + this.pos = svPos; + this.col = svCol; + return null; + } + } + } else { + if((this.ch == TypeScript.LexCode_e) || (this.ch == TypeScript.LexCode_E)) { + if(state == NumberScanState.Start) { + if(atLeastOneDigit) { + atLeastOneDigit = false; + this.nextChar(); + state = NumberScanState.InExponent; + } else { + this.pos = svPos; + this.col = svCol; + return null; + } + } else { + if(state == NumberScanState.InFraction || state == NumberScanState.InEmptyFraction) { + this.nextChar(); + state = NumberScanState.InExponent; + atLeastOneDigit = false; + } else { + if(atLeastOneDigit) { + return new TypeScript.NumberLiteralToken(parseFloat(this.src.substring(this.startPos, this.pos))); + } else { + this.pos = svPos; + this.col = svCol; + return null; + } + } + } + } else { + if((this.ch == TypeScript.LexCodePLS) || (this.ch == TypeScript.LexCodeMIN)) { + if(state == NumberScanState.InExponent) { + if(!atLeastOneDigit) { + this.nextChar(); + } else { + this.pos = svPos; + this.col = svCol; + return null; + } + } else { + if(state == NumberScanState.InEmptyFraction || state == NumberScanState.InFraction) { + return new TypeScript.NumberLiteralToken(parseFloat(this.src.substring(this.startPos, this.pos)), state == NumberScanState.InEmptyFraction); + } else { + if(!atLeastOneDigit) { + this.pos = svPos; + this.col = svCol; + return null; + } else { + return new TypeScript.NumberLiteralToken(parseFloat(this.src.substring(this.startPos, this.pos))); + } + } + } + } else { + if(!atLeastOneDigit) { + this.pos = svPos; + this.col = svCol; + return null; + } else { + return new TypeScript.NumberLiteralToken(parseFloat(this.src.substring(this.startPos, this.pos)), state == NumberScanState.InEmptyFraction); + } + } + } + } + } + } + }; + Scanner.prototype.scanNumber = function () { + if(this.peekChar() == TypeScript.LexCode_0) { + switch(this.peekCharAt(this.pos + 1)) { + case TypeScript.LexCode_x: + case TypeScript.LexCode_X: { + this.advanceChar(2); + return this.scanHexDigits(); + + } + case TypeScript.LexCode_8: + case TypeScript.LexCode_9: + case TypeScript.LexCodeDOT: { + return this.scanDecimalNumber(NumberScanState.Start); + + } + default: { + return this.scanOctalDigits(); + + } + } + } else { + return this.scanDecimalNumber(NumberScanState.Start); + } + }; + Scanner.prototype.scanFraction = function () { + return this.scanDecimalNumber(NumberScanState.InFraction); + }; + Scanner.prototype.newLine = function () { + this.col = 0; + if(this.mode == LexMode.File) { + this.line++; + this.lineMap[this.line] = this.pos + 1; + } + }; + Scanner.prototype.finishMultilineComment = function () { + var ch2; + this.lexState = LexState.InMultilineComment; + while(this.pos < this.len) { + if(this.ch == TypeScript.LexCodeMUL) { + ch2 = this.peekCharAt(this.pos + 1); + if(ch2 == TypeScript.LexCodeSLH) { + this.advanceChar(2); + if(this.mode == LexMode.File) { + this.tokenStart(); + } + this.lexState = LexState.Start; + return true; + } + } else { + if(this.ch == TypeScript.LexCodeNWL) { + this.newLine(); + if(this.mode == LexMode.Line) { + this.nextChar(); + return false; + } + } else { + if(this.ch >= TypeScript.LexCodeASCIIChars) { + this.seenUnicodeCharInComment = true; + } + } + } + this.nextChar(); + } + return false; + }; + Scanner.prototype.pushComment = function (comment) { + this.commentStack.push(comment); + }; + Scanner.prototype.getComments = function () { + var stack = this.commentStack; + this.commentStack = []; + return stack; + }; + Scanner.prototype.getCommentsForLine = function (line) { + var comments = null; + while((this.commentStack.length > 0) && (this.commentStack[0].line == line)) { + if(comments == null) { + comments = [ + this.commentStack.shift() + ]; + } else { + comments = comments.concat([ + this.commentStack.shift() + ]); + } + } + return comments; + }; + Scanner.prototype.resetComments = function () { + this.commentStack = []; + }; + Scanner.prototype.endsLine = function (c) { + return (c == TypeScript.LexCodeNWL) || (c == TypeScript.LexCodeRET) || (c == TypeScript.LexCodeLS) || (c == TypeScript.LexCodePS); + }; + Scanner.prototype.finishSinglelineComment = function () { + while(this.pos < this.len) { + if(this.endsLine(this.ch)) { + break; + } + if(this.ch >= TypeScript.LexCodeASCIIChars) { + this.seenUnicodeCharInComment = true; + } + this.nextChar(); + } + if(this.mode == LexMode.File) { + this.tokenStart(); + } + }; + Scanner.prototype.tokenText = function () { + return this.src.substring(this.startPos, this.pos); + }; + Scanner.prototype.findClosingSLH = function () { + var index = this.pos; + var ch2 = this.src.charCodeAt(index); + var prevCh = 0; + var liveEsc = false; + while(!this.endsLine(ch2) && (index < this.len)) { + if((ch2 == TypeScript.LexCodeSLH) && (!liveEsc)) { + return index; + } + prevCh = ch2; + index++; + if(liveEsc) { + liveEsc = false; + } else { + liveEsc = (prevCh == TypeScript.LexCodeBSL); + } + ch2 = this.src.charCodeAt(index); + } + return -1; + }; + Scanner.prototype.speculateRegex = function () { + if(TypeScript.noRegexTable[this.prevTok.tokenId] != undefined) { + return null; + } + var svPos = this.pos; + var svCol = this.col; + var index = this.findClosingSLH(); + if(index > 0) { + var pattern = this.src.substring(svPos, index); + var flags = ""; + this.pos = index + 1; + this.ch = this.peekChar(); + var flagsStart = this.pos; + while((this.ch == TypeScript.LexCode_i) || (this.ch == TypeScript.LexCode_g) || (this.ch == TypeScript.LexCode_m)) { + this.nextChar(); + } + if((this.pos - flagsStart) > 3) { + return null; + } else { + flags = this.src.substring(flagsStart, this.pos); + } + var regex = undefined; + try { + regex = new RegExp(pattern, flags); + } catch (regexException) { + } + if(regex) { + this.col = svCol + (this.pos - this.startPos); + return new TypeScript.RegularExpressionLiteralToken(regex); + } + } + this.pos = svPos; + this.col = svCol; + return null; + }; + Scanner.prototype.lastTokenHadNewline = function () { + return this.prevLine != this.startLine; + }; + Scanner.prototype.lastTokenLimChar = function () { + return this.interveningWhitespace ? this.interveningWhitespacePos : this.startPos; + }; + Scanner.prototype.advanceChar = function (amt) { + this.pos += amt; + this.col += amt; + this.ch = this.peekChar(); + }; + Scanner.prototype.nextChar = function () { + this.pos++; + this.col++; + this.ch = this.peekChar(); + }; + Scanner.prototype.getLookAheadToken = function () { + var prevLine = this.prevLine; + var line = this.line; + var col = this.col; + var pos = this.pos; + var startPos = this.startPos; + var startCol = this.startCol; + var startLine = this.startLine; + var ch = this.ch; + var prevTok = this.prevTok; + var lexState = this.lexState; + var interveningWhitespace = this.interveningWhitespace; + var interveningWhitespacePos = this.interveningWhitespacePos; + var leftCurlyCount = this.leftCurlyCount; + var rightCurlyCount = this.rightCurlyCount; + var seenUnicodeChar = this.seenUnicodeChar; + var seenUnicodeCharInComment = this.seenUnicodeCharInComment; + var commentStackLength = this.commentStack.length; + var lookAheadToken = this.scan(); + this.prevLine = prevLine; + this.line = line; + this.col = col; + this.pos = pos; + this.startPos = startPos; + this.startCol = startCol; + this.startLine = startLine; + this.ch = ch; + this.prevTok = prevTok; + this.lexState = lexState; + this.interveningWhitespace = interveningWhitespace; + this.interveningWhitespacePos = interveningWhitespacePos; + this.leftCurlyCount = leftCurlyCount; + this.rightCurlyCount = rightCurlyCount; + this.seenUnicodeChar = seenUnicodeChar; + this.seenUnicodeCharInComment = seenUnicodeCharInComment; + this.commentStack.length = commentStackLength; + return lookAheadToken; + }; + Scanner.prototype.scanInLine = function () { + if((this.lexState == LexState.InMultilineComment) && (this.scanComments)) { + this.ch = this.peekChar(); + var commentLine = this.line; + this.finishMultilineComment(); + if(this.startPos < this.pos) { + var commentText = this.src.substring(this.startPos, this.pos); + this.tokenStart(); + return new TypeScript.CommentToken(TypeScript.TokenID.Comment, commentText, true, this.startPos, commentLine, true); + } else { + return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; + } + } else { + if(this.lexState == LexState.InMultilineSingleQuoteString && this.pos < this.len) { + this.ch = TypeScript.LexCodeAPO; + this.lexState = LexState.Start; + return this.scanStringConstant(); + } else { + if(this.lexState == LexState.InMultilineDoubleQuoteString && this.pos < this.len) { + this.ch = TypeScript.LexCodeQUO; + this.lexState = LexState.Start; + return this.scanStringConstant(); + } + } + } + this.prevLine = this.line; + var prevTok = this.innerScan(); + if(prevTok.tokenId != TypeScript.TokenID.Whitespace) { + this.prevTok = prevTok; + } + return prevTok; + }; + Scanner.prototype.scan = function () { + this.prevLine = this.line; + this.prevTok = this.innerScan(); + if(this.saveScan) { + this.saveScan.addToken(this.prevTok, this); + } + return this.prevTok; + }; + Scanner.prototype.isValidUnicodeIdentifierChar = function () { + var valid = LexIsUnicodeIdStart(this.ch) || LexIsUnicodeDigit(this.ch); + this.seenUnicodeChar = this.seenUnicodeChar || valid; + return valid; + }; + Scanner.prototype.scanStringConstant = function () { + var endCode = this.ch; + this.nextChar(); + scanStringConstantLoop: +for(; ; ) { + switch(this.ch) { + case TypeScript.LexEOF: { + this.reportScannerError("Unterminated string constant"); + break scanStringConstantLoop; + + } + case TypeScript.LexCodeLS: + case TypeScript.LexCodePS: { + this.seenUnicodeChar = true; + + } + case TypeScript.LexCodeRET: + case TypeScript.LexCodeNWL: { + this.reportScannerError("Unterminated string constant"); + break scanStringConstantLoop; + + } + case TypeScript.LexCodeAPO: + case TypeScript.LexCodeQUO: { + if(this.ch == endCode) { + this.nextChar(); + break scanStringConstantLoop; + } + break; + + } + case TypeScript.LexCodeBSL: { + this.nextChar(); + switch(this.ch) { + case TypeScript.LexCodeAPO: + case TypeScript.LexCodeQUO: + case TypeScript.LexCodeBSL: { + this.nextChar(); + continue scanStringConstantLoop; + + } + case TypeScript.LexCodeLS: + case TypeScript.LexCodePS: { + this.seenUnicodeChar = true; + + } + case TypeScript.LexCodeRET: + case TypeScript.LexCodeNWL: { + if(this.ch == TypeScript.LexCodeRET && this.peekCharAt(this.pos + 1) == TypeScript.LexCodeNWL) { + this.nextChar(); + } + this.nextChar(); + this.newLine(); + if(this.mode == LexMode.Line) { + this.lexState = endCode == TypeScript.LexCodeAPO ? LexState.InMultilineSingleQuoteString : LexState.InMultilineDoubleQuoteString; + break scanStringConstantLoop; + } + break; + + } + case TypeScript.LexCode_x: + case TypeScript.LexCode_u: { + var expectedHexDigits = this.ch == TypeScript.LexCode_x ? 2 : 4; + this.nextChar(); + for(var i = 0; i < expectedHexDigits; i++) { + if(this.IsHexDigit(this.ch)) { + this.nextChar(); + } else { + this.reportScannerError("Invalid Unicode escape sequence"); + break; + } + } + continue scanStringConstantLoop; + + } + } + break; + + } + } + if(this.ch >= TypeScript.LexCodeASCIIChars) { + this.seenUnicodeChar = true; + } + this.nextChar(); + } + return new TypeScript.StringLiteralToken(this.src.substring(this.startPos, this.pos)); + }; + Scanner.prototype.scanIdentifier = function () { + var hasEscape = false; + var isFirstChar = (this.ch == TypeScript.LexCodeBSL); + var hasUnicode = false; + for(; ; ) { + while(lexIdStartTable[this.ch] || LexIsDigit(this.ch) || (this.ch >= TypeScript.LexCodeASCIIChars && this.isValidUnicodeIdentifierChar())) { + this.nextChar(); + } + if(this.ch == TypeScript.LexCodeBSL) { + this.nextChar(); + if(this.ch == TypeScript.LexCode_u) { + this.nextChar(); + for(var h = 0; h < 4; h++) { + if(this.IsHexDigit(this.ch)) { + this.nextChar(); + } else { + this.reportScannerError("Invalid Unicode escape sequence"); + return TypeScript.staticTokens[TypeScript.TokenID.Error]; + } + } + var hexChar = parseInt(this.src.substring(this.pos - 4, this.pos), 16); + if(lexIdStartTable[hexChar] || (!isFirstChar && LexIsDigit(hexChar)) || (hexChar >= TypeScript.LexCodeASCIIChars && (LexIsUnicodeIdStart(hexChar) || (!isFirstChar && LexIsUnicodeDigit(hexChar))))) { + } else { + this.reportScannerError("Invalid identifier character"); + return TypeScript.staticTokens[TypeScript.TokenID.Error]; + } + hasEscape = true; + isFirstChar = false; + continue; + } + this.reportScannerError("Invalid Unicode escape sequence"); + return TypeScript.staticTokens[TypeScript.TokenID.Error]; + } + break; + } + var id; + var text = this.src.substring(this.startPos, this.pos); + if(!hasEscape && (id = TypeScript.LexKeywordTable.lookup(text)) != null) { + return TypeScript.staticTokens[id]; + } else { + return new TypeScript.IdentifierToken(text, hasEscape); + } + }; + Scanner.prototype.innerScan = function () { + var rtok; + this.tokenStart(); + this.ch = this.peekChar(); + start: +while(this.pos < this.len) { + if(lexIdStartTable[this.ch] || this.ch == TypeScript.LexCodeBSL || (this.ch >= TypeScript.LexCodeASCIIChars && LexIsUnicodeIdStart(this.ch))) { + return this.scanIdentifier(); + } else { + if(this.ch == TypeScript.LexCodeSpace) { + if(!this.interveningWhitespace) { + this.interveningWhitespacePos = this.pos; + } + do { + this.nextChar(); + }while(this.ch == TypeScript.LexCodeSpace) + if(this.mode == LexMode.Line) { + var whitespaceText = this.src.substring(this.startPos, this.pos); + return new TypeScript.WhitespaceToken(TypeScript.TokenID.Whitespace, whitespaceText); + } else { + this.tokenStart(); + this.interveningWhitespace = true; + } + } else { + if(this.ch == TypeScript.LexCodeSLH) { + this.nextChar(); + var commentText; + if(this.ch == TypeScript.LexCodeSLH) { + if(!this.interveningWhitespace) { + this.interveningWhitespacePos = this.pos - 1; + } + var commentStartPos = this.pos - 1; + var commentStartLine = this.line; + this.finishSinglelineComment(); + var commentText = this.src.substring(commentStartPos, this.pos); + var commentToken = new TypeScript.CommentToken(TypeScript.TokenID.Comment, commentText, false, commentStartPos, commentStartLine, false); + if(this.scanComments) { + this.startPos = commentStartPos; + return commentToken; + } else { + this.pushComment(commentToken); + } + this.interveningWhitespace = true; + } else { + if(this.ch == TypeScript.LexCodeMUL) { + if(!this.interveningWhitespace) { + this.interveningWhitespacePos = this.pos - 1; + } + var commentStartPos = this.pos - 1; + var commentStartLine = this.line; + this.nextChar(); + this.finishMultilineComment(); + var commentText = this.src.substring(commentStartPos, this.pos); + var endsLine = this.endsLine(this.peekChar()); + var commentToken = new TypeScript.CommentToken(TypeScript.TokenID.Comment, commentText, true, commentStartPos, commentStartLine, endsLine); + if(this.scanComments) { + this.startPos = commentStartPos; + return commentToken; + } else { + this.pushComment(commentToken); + } + this.interveningWhitespace = true; + } else { + var regexTok = this.speculateRegex(); + if(regexTok) { + return regexTok; + } else { + if(this.peekCharAt(this.pos) == TypeScript.LexCodeEQ) { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.SlashEquals]; + } else { + return TypeScript.staticTokens[TypeScript.TokenID.Slash]; + } + } + } + } + } else { + if(this.ch == TypeScript.LexCodeSMC) { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Semicolon]; + } else { + if((this.ch == TypeScript.LexCodeAPO) || (this.ch == TypeScript.LexCodeQUO)) { + return this.scanStringConstant(); + } else { + if(autoToken[this.ch]) { + var atok = autoToken[this.ch]; + if(atok.tokenId == TypeScript.TokenID.OpenBrace) { + this.leftCurlyCount++; + } else { + if(atok.tokenId == TypeScript.TokenID.CloseBrace) { + this.rightCurlyCount++; + } + } + this.nextChar(); + return atok; + } else { + if((this.ch >= TypeScript.LexCode_0) && (this.ch <= TypeScript.LexCode_9)) { + rtok = this.scanNumber(); + if(rtok) { + return rtok; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Error]; + } + } else { + switch(this.ch) { + case TypeScript.LexCodeTAB: + case TypeScript.LexCodeVTAB: { + if(!this.interveningWhitespace) { + this.interveningWhitespacePos = this.pos; + } + if(this.mode == LexMode.Line) { + do { + this.nextChar(); + }while((this.ch == TypeScript.LexCodeSpace) || (this.ch == 9)) + var wsText = this.src.substring(this.startPos, this.pos); + return new TypeScript.WhitespaceToken(TypeScript.TokenID.Whitespace, wsText); + } else { + this.interveningWhitespace = true; + } + + } + case 255: + case 254: + case 239: + case 187: + case 191: + case TypeScript.LexCodeLS: + case TypeScript.LexCodePS: + case TypeScript.LexCodeNWL: + case TypeScript.LexCodeRET: { + if(this.ch == TypeScript.LexCodeNWL) { + this.newLine(); + if(this.mode == LexMode.Line) { + return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; + } + } + if(!this.interveningWhitespace) { + this.interveningWhitespacePos = this.pos; + } + this.nextChar(); + this.tokenStart(); + this.interveningWhitespace = true; + break; + + } + case TypeScript.LexCodeDOT: { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeDOT) { + if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeDOT) { + this.advanceChar(3); + return TypeScript.staticTokens[TypeScript.TokenID.DotDotDot]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Dot]; + } + } else { + this.nextChar(); + rtok = this.scanFraction(); + if(rtok) { + return rtok; + } else { + return TypeScript.staticTokens[TypeScript.TokenID.Dot]; + } + } + } + + case TypeScript.LexCodeEQ: { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeEQ) { + this.advanceChar(3); + return TypeScript.staticTokens[TypeScript.TokenID.EqualsEqualsEquals]; + } else { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.EqualsEquals]; + } + } else { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeGT) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.EqualsGreaterThan]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Equals]; + } + } + + } + case TypeScript.LexCodeBNG: { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeEQ) { + this.advanceChar(3); + return TypeScript.staticTokens[TypeScript.TokenID.ExclamationEqualsEquals]; + } else { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.ExclamationEquals]; + } + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Exclamation]; + } + + } + case TypeScript.LexCodePLS: { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.PlusEquals]; + } else { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodePLS) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.PlusPlus]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Plus]; + } + } + + } + case TypeScript.LexCodeMIN: { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.MinusEquals]; + } else { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeMIN) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.MinusMinus]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Minus]; + } + } + + } + case TypeScript.LexCodeMUL: { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.AsteriskEquals]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Asterisk]; + } + + } + case TypeScript.LexCodePCT: { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.PercentEquals]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Percent]; + } + + } + case TypeScript.LexCodeLT: { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeLT) { + if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeEQ) { + this.advanceChar(3); + return TypeScript.staticTokens[TypeScript.TokenID.LessThanLessThanEquals]; + } else { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.LessThanLessThan]; + } + } else { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.LessThanEquals]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.LessThan]; + } + } + + } + case TypeScript.LexCodeGT: { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeGT) { + if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeEQ) { + this.advanceChar(3); + return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanGreaterThanEquals]; + } else { + if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeGT) { + if(this.peekCharAt(this.pos + 3) == TypeScript.LexCodeEQ) { + this.advanceChar(4); + return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanGreaterThanGreaterThanEquals]; + } else { + this.advanceChar(3); + return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanGreaterThanGreaterThan]; + } + } else { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanGreaterThan]; + } + } + } else { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanEquals]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.GreaterThan]; + } + } + + } + case TypeScript.LexCodeXOR: { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.CaretEquals]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Caret]; + } + + } + case TypeScript.LexCodeBAR: { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.BarEquals]; + } else { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeBAR) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.BarBar]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Bar]; + } + } + + } + case TypeScript.LexCodeAMP: { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.AmpersandEquals]; + } else { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeAMP) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.AmpersandAmpersand]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.And]; + } + } + + } + default: { + this.reportScannerError("Invalid character"); + this.nextChar(); + continue start; + + } + } + } + } + } + } + } + } + } + } + return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; + }; + Scanner.prototype.reportScannerError = function (message) { + if(this.reportError) { + this.reportError(message); + } + }; + return Scanner; + })(); + TypeScript.Scanner = Scanner; + function convertTokToIDName(tok) { + return convertTokToIDBase(tok, true, false); + } + TypeScript.convertTokToIDName = convertTokToIDName; + function convertTokToID(tok, strictMode) { + return convertTokToIDBase(tok, false, strictMode); + } + TypeScript.convertTokToID = convertTokToID; + function convertTokToIDBase(tok, identifierName, strictMode) { + if(tok.tokenId <= TypeScript.TokenID.LimKeyword) { + var tokInfo = TypeScript.lookupToken(tok.tokenId); + if(tokInfo != undefined) { + var resFlags = TypeScript.Reservation.Javascript | TypeScript.Reservation.JavascriptFuture; + if(strictMode) { + resFlags |= TypeScript.Reservation.JavascriptFutureStrict; + } + if(identifierName || !TypeScript.hasFlag(tokInfo.reservation, resFlags)) { + return true; + } + } else { + return false; + } + } else { + return false; + } + } + function getLineNumberFromPosition(lineMap, position) { + if(position === -1) { + return 0; + } + var min = 0; + var max = lineMap.length - 1; + while(min < max) { + var med = (min + max) >> 1; + if(position < lineMap[med]) { + max = med - 1; + } else { + if(position < lineMap[med + 1]) { + min = max = med; + } else { + min = med + 1; + } + } + } + return min; + } + TypeScript.getLineNumberFromPosition = getLineNumberFromPosition; + function getSourceLineColFromMap(lineCol, minChar, lineMap) { + var line = getLineNumberFromPosition(lineMap, minChar); + if(line > 0) { + lineCol.line = line; + lineCol.col = (minChar - lineMap[line]); + } + } + TypeScript.getSourceLineColFromMap = getSourceLineColFromMap; + function getLineColumnFromPosition(script, position) { + var result = { + line: -1, + col: -1 + }; + getSourceLineColFromMap(result, position, script.locationInfo.lineMap); + if(result.col >= 0) { + result.col++; + } + return result; + } + TypeScript.getLineColumnFromPosition = getLineColumnFromPosition; + function getPositionFromLineColumn(script, line, column) { + return script.locationInfo.lineMap[line] + (column - 1); + } + TypeScript.getPositionFromLineColumn = getPositionFromLineColumn; + function isPrimitiveTypeToken(token) { + switch(token.tokenId) { + case TypeScript.TokenID.Any: + case TypeScript.TokenID.Bool: + case TypeScript.TokenID.Number: + case TypeScript.TokenID.String: { + return true; + + } + } + return false; + } + TypeScript.isPrimitiveTypeToken = isPrimitiveTypeToken; + function isModifier(token) { + switch(token.tokenId) { + case TypeScript.TokenID.Public: + case TypeScript.TokenID.Private: + case TypeScript.TokenID.Static: { + return true; + + } + } + return false; + } + TypeScript.isModifier = isModifier; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var AssignScopeContext = (function () { + function AssignScopeContext(scopeChain, typeFlow, modDeclChain) { + this.scopeChain = scopeChain; + this.typeFlow = typeFlow; + this.modDeclChain = modDeclChain; + } + return AssignScopeContext; + })(); + TypeScript.AssignScopeContext = AssignScopeContext; + function pushAssignScope(scope, context, type, classType, fnc) { + var chain = new TypeScript.ScopeChain(null, context.scopeChain, scope); + chain.thisType = type; + chain.classType = classType; + chain.fnc = fnc; + context.scopeChain = chain; + } + TypeScript.pushAssignScope = pushAssignScope; + function popAssignScope(context) { + context.scopeChain = context.scopeChain.previous; + } + TypeScript.popAssignScope = popAssignScope; + function instanceCompare(a, b) { + if(((a == null) || (!a.isInstanceProperty()))) { + return b; + } else { + return a; + } + } + TypeScript.instanceCompare = instanceCompare; + function instanceFilterStop(s) { + return s.isInstanceProperty(); + } + TypeScript.instanceFilterStop = instanceFilterStop; + var ScopeSearchFilter = (function () { + function ScopeSearchFilter(select, stop) { + this.select = select; + this.stop = stop; + this.result = null; + } + ScopeSearchFilter.prototype.reset = function () { + this.result = null; + }; + ScopeSearchFilter.prototype.update = function (b) { + this.result = this.select(this.result, b); + if(this.result) { + return this.stop(this.result); + } else { + return false; + } + }; + return ScopeSearchFilter; + })(); + TypeScript.ScopeSearchFilter = ScopeSearchFilter; + TypeScript.instanceFilter = new ScopeSearchFilter(instanceCompare, instanceFilterStop); + function preAssignModuleScopes(ast, context) { + var moduleDecl = ast; + var memberScope = null; + var aggScope = null; + if(moduleDecl.name && moduleDecl.mod) { + moduleDecl.name.sym = moduleDecl.mod.symbol; + } + var mod = moduleDecl.mod; + if(!mod) { + return; + } + memberScope = new TypeScript.SymbolTableScope(mod.members, mod.ambientMembers, mod.enclosedTypes, mod.ambientEnclosedTypes, mod.symbol); + mod.memberScope = memberScope; + context.modDeclChain.push(moduleDecl); + context.typeFlow.checker.currentModDecl = moduleDecl; + aggScope = new TypeScript.SymbolAggregateScope(mod.symbol); + aggScope.addParentScope(memberScope); + aggScope.addParentScope(context.scopeChain.scope); + pushAssignScope(aggScope, context, null, null, null); + mod.containedScope = aggScope; + if(mod.symbol) { + context.typeFlow.addLocalsFromScope(mod.containedScope, mod.symbol, moduleDecl.vars, mod.members.privateMembers, true); + } + } + TypeScript.preAssignModuleScopes = preAssignModuleScopes; + function preAssignClassScopes(ast, context) { + var classDecl = ast; + var memberScope = null; + var aggScope = null; + if(classDecl.name && classDecl.type) { + classDecl.name.sym = classDecl.type.symbol; + } + var classType = ast.type; + if(classType) { + var classSym = classType.symbol; + memberScope = context.typeFlow.checker.scopeOf(classType); + aggScope = new TypeScript.SymbolAggregateScope(classType.symbol); + aggScope.addParentScope(memberScope); + aggScope.addParentScope(context.scopeChain.scope); + classType.containedScope = aggScope; + classType.memberScope = memberScope; + var instanceType = classType.instanceType; + memberScope = context.typeFlow.checker.scopeOf(instanceType); + instanceType.memberScope = memberScope; + aggScope = new TypeScript.SymbolAggregateScope(instanceType.symbol); + aggScope.addParentScope(context.scopeChain.scope); + pushAssignScope(aggScope, context, instanceType, classType, null); + instanceType.containedScope = aggScope; + } else { + ast.type = context.typeFlow.anyType; + } + } + TypeScript.preAssignClassScopes = preAssignClassScopes; + function preAssignInterfaceScopes(ast, context) { + var interfaceDecl = ast; + var memberScope = null; + var aggScope = null; + if(interfaceDecl.name && interfaceDecl.type) { + interfaceDecl.name.sym = interfaceDecl.type.symbol; + } + var interfaceType = ast.type; + memberScope = context.typeFlow.checker.scopeOf(interfaceType); + interfaceType.memberScope = memberScope; + aggScope = new TypeScript.SymbolAggregateScope(interfaceType.symbol); + aggScope.addParentScope(memberScope); + aggScope.addParentScope(context.scopeChain.scope); + pushAssignScope(aggScope, context, null, null, null); + interfaceType.containedScope = aggScope; + } + TypeScript.preAssignInterfaceScopes = preAssignInterfaceScopes; + function preAssignWithScopes(ast, context) { + var withStmt = ast; + var withType = withStmt.type; + var members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + var ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + var withType = new TypeScript.Type(); + var withSymbol = new TypeScript.WithSymbol(withStmt.minChar, context.typeFlow.checker.locationInfo.unitIndex, withType); + withType.members = members; + withType.ambientMembers = ambientMembers; + withType.symbol = withSymbol; + withType.setHasImplementation(); + withStmt.type = withType; + var withScope = new TypeScript.SymbolScopeBuilder(withType.members, withType.ambientMembers, null, null, context.scopeChain.scope, withType.symbol); + pushAssignScope(withScope, context, null, null, null); + withType.containedScope = withScope; + } + TypeScript.preAssignWithScopes = preAssignWithScopes; + function preAssignFuncDeclScopes(ast, context) { + var funcDecl = ast; + var container = null; + var localContainer = null; + if(funcDecl.type) { + localContainer = ast.type.symbol; + } + var isStatic = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static); + var isInnerStatic = isStatic && context.scopeChain.fnc != null; + var parentScope = isInnerStatic ? context.scopeChain.fnc.type.memberScope : context.scopeChain.scope; + if(context.scopeChain.thisType && (!funcDecl.isConstructor || TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod))) { + var instType = context.scopeChain.thisType; + if(!(instType.typeFlags & TypeScript.TypeFlags.IsClass) && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { + if(!funcDecl.isMethod() || isStatic) { + parentScope = instType.constructorScope; + } else { + parentScope = instType.containedScope; + } + } else { + if(context.scopeChain.previous.scope.container && context.scopeChain.previous.scope.container.declAST && context.scopeChain.previous.scope.container.declAST.nodeType == TypeScript.NodeType.FuncDecl && (context.scopeChain.previous.scope.container.declAST).isConstructor) { + parentScope = instType.constructorScope; + } else { + if(isStatic && context.scopeChain.classType) { + parentScope = context.scopeChain.classType.containedScope; + } else { + parentScope = instType.containedScope; + } + } + } + container = instType.symbol; + } else { + if(funcDecl.isConstructor && context.scopeChain.thisType) { + container = context.scopeChain.thisType.symbol; + } + } + if(funcDecl.type == null || TypeScript.hasFlag(funcDecl.type.symbol.flags, TypeScript.SymbolFlags.TypeSetDuringScopeAssignment)) { + if(context.scopeChain.fnc && context.scopeChain.fnc.type) { + container = context.scopeChain.fnc.type.symbol; + } + var funcScope = null; + var outerFnc = context.scopeChain.fnc; + var nameText = funcDecl.name ? funcDecl.name.actualText : null; + var fgSym = null; + if(isStatic) { + if(outerFnc.type.members == null && container.getType().memberScope) { + outerFnc.type.members = ((container).type.memberScope).valueMembers; + } + funcScope = context.scopeChain.fnc.type.memberScope; + outerFnc.innerStaticFuncs[outerFnc.innerStaticFuncs.length] = funcDecl; + } else { + funcScope = context.scopeChain.scope; + } + if(nameText && nameText != "__missing" && !funcDecl.isAccessor()) { + if(isStatic) { + fgSym = funcScope.findLocal(nameText, false, false); + } else { + fgSym = funcScope.findLocal(nameText, false, false); + } + } + context.typeFlow.checker.createFunctionSignature(funcDecl, container, funcScope, fgSym, fgSym == null); + if(!funcDecl.accessorSymbol && (funcDecl.fncFlags & TypeScript.FncFlags.ClassMethod) && container && ((!fgSym || fgSym.declAST.nodeType != TypeScript.NodeType.FuncDecl) && funcDecl.isAccessor()) || (fgSym && fgSym.isAccessor())) { + funcDecl.accessorSymbol = context.typeFlow.checker.createAccessorSymbol(funcDecl, fgSym, container.getType(), (funcDecl.isMethod() && isStatic), true, funcScope, container); + } + funcDecl.type.symbol.flags |= TypeScript.SymbolFlags.TypeSetDuringScopeAssignment; + } + if(funcDecl.name && funcDecl.type) { + funcDecl.name.sym = funcDecl.type.symbol; + } + funcDecl.scopeType = funcDecl.type; + if(funcDecl.isOverload) { + return; + } + var funcTable = new TypeScript.StringHashTable(); + var funcMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(funcTable, new TypeScript.StringHashTable())); + var ambientFuncTable = new TypeScript.StringHashTable(); + var ambientFuncMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(ambientFuncTable, new TypeScript.StringHashTable())); + var funcStaticTable = new TypeScript.StringHashTable(); + var funcStaticMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(funcStaticTable, new TypeScript.StringHashTable())); + var ambientFuncStaticTable = new TypeScript.StringHashTable(); + var ambientFuncStaticMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(ambientFuncStaticTable, new TypeScript.StringHashTable())); + funcDecl.unitIndex = context.typeFlow.checker.locationInfo.unitIndex; + var locals = new TypeScript.SymbolScopeBuilder(funcMembers, ambientFuncMembers, null, null, parentScope, localContainer); + var statics = new TypeScript.SymbolScopeBuilder(funcStaticMembers, ambientFuncStaticMembers, null, null, parentScope, null); + if(funcDecl.isConstructor && context.scopeChain.thisType) { + context.scopeChain.thisType.constructorScope = locals; + } + funcDecl.symbols = funcTable; + if(!funcDecl.isSpecialFn()) { + var group = funcDecl.type; + var signature = funcDecl.signature; + if(!funcDecl.isConstructor) { + group.containedScope = locals; + locals.container = group.symbol; + group.memberScope = statics; + statics.container = group.symbol; + } + funcDecl.enclosingFnc = context.scopeChain.fnc; + group.enclosingType = isStatic ? context.scopeChain.classType : context.scopeChain.thisType; + var fgSym = ast.type.symbol; + if(((funcDecl.fncFlags & TypeScript.FncFlags.Signature) == TypeScript.FncFlags.None) && funcDecl.vars) { + context.typeFlow.addLocalsFromScope(locals, fgSym, funcDecl.vars, funcTable, false); + context.typeFlow.addLocalsFromScope(statics, fgSym, funcDecl.statics, funcStaticTable, false); + } + if(signature.parameters) { + var len = signature.parameters.length; + for(var i = 0; i < len; i++) { + var paramSym = signature.parameters[i]; + context.typeFlow.checker.resolveTypeLink(locals, paramSym.parameter.typeLink, true); + } + } + context.typeFlow.checker.resolveTypeLink(locals, signature.returnType, funcDecl.isSignature()); + } + if(!funcDecl.isConstructor || TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { + var thisType = (funcDecl.isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) ? context.scopeChain.thisType : null; + pushAssignScope(locals, context, thisType, null, funcDecl); + } + if(funcDecl.name && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFunctionExpression)) { + if(funcDecl.name.sym) { + funcTable.add(funcDecl.name.actualText, funcDecl.name.sym); + } + } + } + TypeScript.preAssignFuncDeclScopes = preAssignFuncDeclScopes; + function preAssignCatchScopes(ast, context) { + var catchBlock = ast; + if(catchBlock.param) { + var catchTable = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + var catchLocals = new TypeScript.SymbolScopeBuilder(catchTable, null, null, null, context.scopeChain.scope, context.scopeChain.scope.container); + catchBlock.containedScope = catchLocals; + pushAssignScope(catchLocals, context, context.scopeChain.thisType, context.scopeChain.classType, context.scopeChain.fnc); + } + } + TypeScript.preAssignCatchScopes = preAssignCatchScopes; + function preAssignScopes(ast, parent, walker) { + var context = walker.state; + var go = true; + if(ast) { + if(ast.nodeType == TypeScript.NodeType.List) { + var list = ast; + list.enclosingScope = context.scopeChain.scope; + } else { + if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { + preAssignModuleScopes(ast, context); + } else { + if(ast.nodeType == TypeScript.NodeType.ClassDeclaration) { + preAssignClassScopes(ast, context); + } else { + if(ast.nodeType == TypeScript.NodeType.InterfaceDeclaration) { + preAssignInterfaceScopes(ast, context); + } else { + if(ast.nodeType == TypeScript.NodeType.With) { + preAssignWithScopes(ast, context); + } else { + if(ast.nodeType == TypeScript.NodeType.FuncDecl) { + preAssignFuncDeclScopes(ast, context); + } else { + if(ast.nodeType == TypeScript.NodeType.Catch) { + preAssignCatchScopes(ast, context); + } else { + if(ast.nodeType == TypeScript.NodeType.TypeRef) { + go = false; + } + } + } + } + } + } + } + } + } + walker.options.goChildren = go; + return ast; + } + TypeScript.preAssignScopes = preAssignScopes; + function postAssignScopes(ast, parent, walker) { + var context = walker.state; + var go = true; + if(ast) { + if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { + var prevModDecl = ast; + popAssignScope(context); + context.modDeclChain.pop(); + if(context.modDeclChain.length >= 1) { + context.typeFlow.checker.currentModDecl = context.modDeclChain[context.modDeclChain.length - 1]; + } + } else { + if(ast.nodeType == TypeScript.NodeType.ClassDeclaration) { + popAssignScope(context); + } else { + if(ast.nodeType == TypeScript.NodeType.InterfaceDeclaration) { + popAssignScope(context); + } else { + if(ast.nodeType == TypeScript.NodeType.With) { + popAssignScope(context); + } else { + if(ast.nodeType == TypeScript.NodeType.FuncDecl) { + var funcDecl = ast; + if((!funcDecl.isConstructor || TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) && !funcDecl.isOverload) { + popAssignScope(context); + } + } else { + if(ast.nodeType == TypeScript.NodeType.Catch) { + var catchBlock = ast; + if(catchBlock.param) { + popAssignScope(context); + } + } else { + go = false; + } + } + } + } + } + } + } + walker.options.goChildren = go; + return ast; + } + TypeScript.postAssignScopes = postAssignScopes; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var TypeCollectionContext = (function () { + function TypeCollectionContext(scopeChain, checker) { + this.scopeChain = scopeChain; + this.checker = checker; + this.script = null; + } + return TypeCollectionContext; + })(); + TypeScript.TypeCollectionContext = TypeCollectionContext; + var MemberScopeContext = (function () { + function MemberScopeContext(flow, pos, matchFlag) { + this.flow = flow; + this.pos = pos; + this.matchFlag = matchFlag; + this.type = null; + this.ast = null; + this.options = new TypeScript.AstWalkOptions(); + } + return MemberScopeContext; + })(); + TypeScript.MemberScopeContext = MemberScopeContext; + var EnclosingScopeContext = (function () { + function EnclosingScopeContext(logger, script, text, pos, isMemberCompletion) { + this.logger = logger; + this.script = script; + this.text = text; + this.pos = pos; + this.isMemberCompletion = isMemberCompletion; + this.scopeGetter = null; + this.objectLiteralScopeGetter = null; + this.scopeStartAST = null; + this.skipNextFuncDeclForClass = false; + this.deepestModuleDecl = null; + this.enclosingClassDecl = null; + this.enclosingObjectLit = null; + this.publicsOnly = true; + this.useFullAst = false; + } + EnclosingScopeContext.prototype.getScope = function () { + return this.scopeGetter(); + }; + EnclosingScopeContext.prototype.getObjectLiteralScope = function () { + return this.objectLiteralScopeGetter(); + }; + EnclosingScopeContext.prototype.getScopeAST = function () { + return this.scopeStartAST; + }; + EnclosingScopeContext.prototype.getScopePosition = function () { + return this.scopeStartAST.minChar; + }; + EnclosingScopeContext.prototype.getScriptFragmentStartAST = function () { + return this.scopeStartAST; + }; + EnclosingScopeContext.prototype.getScriptFragmentPosition = function () { + return this.getScriptFragmentStartAST().minChar; + }; + EnclosingScopeContext.prototype.getScriptFragment = function () { + if(this.scriptFragment == null) { + var ast = this.getScriptFragmentStartAST(); + var minChar = ast.minChar; + var limChar = (this.isMemberCompletion ? this.pos : this.pos + 1); + this.scriptFragment = TypeScript.quickParse(this.logger, ast, this.text, minChar, limChar, null).Script; + } + return this.scriptFragment; + }; + return EnclosingScopeContext; + })(); + TypeScript.EnclosingScopeContext = EnclosingScopeContext; + function preFindMemberScope(ast, parent, walker) { + var memScope = walker.state; + if(TypeScript.hasFlag(ast.flags, memScope.matchFlag) && ((memScope.pos < 0) || (memScope.pos == ast.limChar))) { + memScope.ast = ast; + if((ast.type == null) && (memScope.pos >= 0)) { + memScope.flow.inScopeTypeCheck(ast, memScope.scope); + } + memScope.type = ast.type; + memScope.options.stopWalk(); + } + return ast; + } + TypeScript.preFindMemberScope = preFindMemberScope; + function pushTypeCollectionScope(container, valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, context, thisType, classType, moduleDecl) { + var builder = new TypeScript.SymbolScopeBuilder(valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, null, container); + var chain = new TypeScript.ScopeChain(container, context.scopeChain, builder); + chain.thisType = thisType; + chain.classType = classType; + chain.moduleDecl = moduleDecl; + context.scopeChain = chain; + } + TypeScript.pushTypeCollectionScope = pushTypeCollectionScope; + function popTypeCollectionScope(context) { + context.scopeChain = context.scopeChain.previous; + } + TypeScript.popTypeCollectionScope = popTypeCollectionScope; + function preFindEnclosingScope(ast, parent, walker) { + var context = walker.state; + var minChar = ast.minChar; + var limChar = ast.limChar; + if(ast.nodeType == TypeScript.NodeType.Script && context.pos > limChar) { + limChar = context.pos; + } + if((minChar <= context.pos) && (limChar >= context.pos)) { + switch(ast.nodeType) { + case TypeScript.NodeType.Script: { + var script = ast; + context.scopeGetter = function () { + return script.bod === null ? null : script.bod.enclosingScope; + }; + context.scopeStartAST = script; + break; + + } + case TypeScript.NodeType.ClassDeclaration: { + context.scopeGetter = function () { + return (ast.type === null || ast.type.instanceType.containedScope === null) ? null : ast.type.instanceType.containedScope; + }; + context.scopeStartAST = ast; + context.enclosingClassDecl = ast; + break; + + } + case TypeScript.NodeType.ObjectLit: { + var objectLit = ast; + if(objectLit.targetType) { + context.scopeGetter = function () { + return objectLit.targetType.containedScope; + }; + context.objectLiteralScopeGetter = function () { + return objectLit.targetType.memberScope; + }; + context.enclosingObjectLit = objectLit; + } + break; + + } + case TypeScript.NodeType.ModuleDeclaration: { + context.deepestModuleDecl = ast; + context.scopeGetter = function () { + return ast.type === null ? null : ast.type.containedScope; + }; + context.scopeStartAST = ast; + break; + + } + case TypeScript.NodeType.InterfaceDeclaration: { + context.scopeGetter = function () { + return (ast.type === null) ? null : ast.type.containedScope; + }; + context.scopeStartAST = ast; + break; + + } + case TypeScript.NodeType.FuncDecl: { + { + var funcDecl = ast; + if(context.skipNextFuncDeclForClass) { + context.skipNextFuncDeclForClass = false; + } else { + context.scopeGetter = function () { + if(funcDecl.isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { + if(ast.type && ast.type.enclosingType) { + return ast.type.enclosingType.constructorScope; + } + } + if(funcDecl.scopeType) { + return funcDecl.scopeType.containedScope; + } + if(funcDecl.type) { + return funcDecl.type.containedScope; + } + return null; + }; + context.scopeStartAST = ast; + } + } + break; + + } + } + walker.options.goChildren = true; + } else { + walker.options.goChildren = false; + } + return ast; + } + TypeScript.preFindEnclosingScope = preFindEnclosingScope; + function findEnclosingScopeAt(logger, script, text, pos, isMemberCompletion) { + var context = new EnclosingScopeContext(logger, script, text, pos, isMemberCompletion); + TypeScript.getAstWalkerFactory().walk(script, preFindEnclosingScope, null, null, context); + if(context.scopeStartAST === null) { + return null; + } + return context; + } + TypeScript.findEnclosingScopeAt = findEnclosingScopeAt; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Signature = (function () { + function Signature() { + this.hasVariableArgList = false; + this.parameters = null; + this.declAST = null; + this.typeCheckStatus = TypeScript.TypeCheckStatus.NotStarted; + this.nonOptionalParameterCount = 0; + } + Signature.prototype.specializeType = function (pattern, replacement, checker) { + var result = new Signature(); + if(this.hasVariableArgList) { + result.hasVariableArgList = true; + } + result.returnType = new TypeScript.TypeLink(); + if(this.returnType.type) { + result.returnType.type = this.returnType.type.specializeType(pattern, replacement, checker, false); + } else { + result.returnType.type = checker.anyType; + } + if(this.parameters) { + result.parameters = []; + for(var i = 0, len = this.parameters.length; i < len; i++) { + var oldSym = this.parameters[i]; + var paramDef = new TypeScript.ValueLocation(); + var paramSym = new TypeScript.ParameterSymbol(oldSym.name, oldSym.location, checker.locationInfo.unitIndex, paramDef); + paramSym.declAST = this.declAST; + paramDef.symbol = paramSym; + paramDef.typeLink = new TypeScript.TypeLink(); + result.parameters[i] = paramSym; + var oldType = oldSym.getType(); + if(oldType) { + paramDef.typeLink.type = oldType.specializeType(pattern, replacement, checker, false); + paramSym.declAST.type = paramDef.typeLink.type; + } else { + paramDef.typeLink.type = checker.anyType; + } + } + } + result.nonOptionalParameterCount = this.nonOptionalParameterCount; + result.declAST = this.declAST; + return result; + }; + Signature.prototype.toString = function () { + return this.toStringHelper(false, false, null); + }; + Signature.prototype.toStringHelper = function (shortform, brackets, scope) { + return this.toStringHelperEx(shortform, brackets, scope).toString(); + }; + Signature.prototype.toStringHelperEx = function (shortform, brackets, scope, prefix) { + if (typeof prefix === "undefined") { prefix = ""; } + var builder = new TypeScript.MemberNameArray(); + if(brackets) { + builder.prefix = prefix + "["; + } else { + builder.prefix = prefix + "("; + } + var paramLen = this.parameters.length; + var len = this.hasVariableArgList ? paramLen - 1 : paramLen; + for(var i = 0; i < len; i++) { + builder.add(TypeScript.MemberName.create(this.parameters[i].name + (this.parameters[i].isOptional() ? "?" : "") + ": ")); + builder.add(this.parameters[i].getType().getScopedTypeNameEx(scope)); + if(i < paramLen - 1) { + builder.add(TypeScript.MemberName.create(", ")); + } + } + if(this.hasVariableArgList) { + builder.add(TypeScript.MemberName.create("..." + this.parameters[i].name + ": ")); + builder.add(this.parameters[i].getType().getScopedTypeNameEx(scope)); + } + if(shortform) { + if(brackets) { + builder.add(TypeScript.MemberName.create("] => ")); + } else { + builder.add(TypeScript.MemberName.create(") => ")); + } + } else { + if(brackets) { + builder.add(TypeScript.MemberName.create("]: ")); + } else { + builder.add(TypeScript.MemberName.create("): ")); + } + } + if(this.returnType.type) { + builder.add(this.returnType.type.getScopedTypeNameEx(scope)); + } else { + builder.add(TypeScript.MemberName.create("any")); + } + return builder; + }; + return Signature; + })(); + TypeScript.Signature = Signature; + var SignatureGroup = (function () { + function SignatureGroup() { + this.signatures = []; + this.hasImplementation = true; + this.definitionSignature = null; + this.hasBeenTypechecked = false; + this.flags = TypeScript.SignatureFlags.None; + } + SignatureGroup.prototype.addSignature = function (signature) { + if(this.signatures == null) { + this.signatures = new Array(); + } + this.signatures[this.signatures.length] = signature; + if(signature.declAST && !signature.declAST.isOverload && !signature.declAST.isSignature() && !TypeScript.hasFlag(signature.declAST.fncFlags, TypeScript.FncFlags.Ambient) && TypeScript.hasFlag(signature.declAST.fncFlags, TypeScript.FncFlags.Definition)) { + this.definitionSignature = signature; + } + }; + SignatureGroup.prototype.toString = function () { + return this.signatures.toString(); + }; + SignatureGroup.prototype.toStrings = function (prefix, shortform, scope) { + var result = []; + var len = this.signatures.length; + if(len > 1) { + shortform = false; + } + for(var i = 0; i < len; i++) { + if(len > 1 && this.signatures[i] == this.definitionSignature) { + continue; + } + if(this.flags & TypeScript.SignatureFlags.IsIndexer) { + result.push(this.signatures[i].toStringHelperEx(shortform, true, scope)); + } else { + result.push(this.signatures[i].toStringHelperEx(shortform, false, scope, prefix)); + } + } + return result; + }; + SignatureGroup.prototype.specializeType = function (pattern, replacement, checker) { + var result = new SignatureGroup(); + if(this.signatures) { + for(var i = 0, len = this.signatures.length; i < len; i++) { + result.addSignature(this.signatures[i].specializeType(pattern, replacement, checker)); + } + } + return result; + }; + SignatureGroup.prototype.verifySignatures = function (checker) { + var len = 0; + if(this.signatures && ((len = this.signatures.length) > 0)) { + for(var i = 0; i < len; i++) { + for(var j = i + 1; j < len; j++) { + if(this.signatures[i].declAST && this.signatures[j].declAST && (!TypeScript.hasFlag(this.signatures[i].declAST.fncFlags, TypeScript.FncFlags.Definition) && !TypeScript.hasFlag(this.signatures[j].declAST.fncFlags, TypeScript.FncFlags.Definition)) && checker.signaturesAreIdentical(this.signatures[i], this.signatures[j])) { + checker.errorReporter.simpleError(this.signatures[i].declAST, (this.signatures[i].declAST && this.signatures[i].declAST.name) ? "Signature for '" + this.signatures[i].declAST.name.actualText + "' is duplicated" : "Signature is duplicated"); + } + } + if(this.definitionSignature) { + if(!checker.signatureIsAssignableToTarget(this.definitionSignature, this.signatures[i])) { + checker.errorReporter.simpleError(this.signatures[i].declAST, "Overload signature is not compatible with function definition"); + } + } + } + } + }; + SignatureGroup.prototype.typeCheck = function (checker, ast, hasConstruct) { + if(this.hasBeenTypechecked) { + return; + } + this.hasBeenTypechecked = true; + var len = 0; + if(this.signatures && ((len = this.signatures.length) > 0)) { + for(var i = 0; i < len; i++) { + if(!hasConstruct && !this.definitionSignature && this.signatures[i].declAST && this.signatures[i].declAST.isOverload && !TypeScript.hasFlag(this.signatures[i].declAST.fncFlags, TypeScript.FncFlags.Ambient)) { + checker.errorReporter.simpleError(this.signatures[i].declAST, "Overload declaration lacks definition"); + } + if(this.signatures[i].declAST && this.signatures[i].declAST.isConstructor && this.signatures[i].declAST.classDecl && this.signatures[i].declAST.classDecl.type.symbol.typeCheckStatus == TypeScript.TypeCheckStatus.NotStarted) { + checker.typeFlow.typeCheck(this.signatures[i].declAST.classDecl); + } + checker.typeFlow.typeCheck(this.signatures[i].declAST); + } + this.verifySignatures(checker); + } + }; + return SignatureGroup; + })(); + TypeScript.SignatureGroup = SignatureGroup; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (TypeCheckStatus) { + TypeCheckStatus._map = []; + TypeCheckStatus._map[0] = "NotStarted"; + TypeCheckStatus.NotStarted = 0; + TypeCheckStatus._map[1] = "Started"; + TypeCheckStatus.Started = 1; + TypeCheckStatus._map[2] = "Finished"; + TypeCheckStatus.Finished = 2; + })(TypeScript.TypeCheckStatus || (TypeScript.TypeCheckStatus = {})); + var TypeCheckStatus = TypeScript.TypeCheckStatus; + function aLexicallyEnclosesB(a, b) { + if(a.declAST && b && b.declAST && a.declAST.nodeType == TypeScript.NodeType.FuncDecl) { + return a.declAST.minChar <= b.declAST.minChar && a.declAST.limChar >= b.declAST.limChar; + } else { + return false; + } + } + TypeScript.aLexicallyEnclosesB = aLexicallyEnclosesB; + function aEnclosesB(a, b) { + while(a.container) { + if(a == b || aLexicallyEnclosesB(a.container, b)) { + return true; + } + a = a.container; + } + return false; + } + TypeScript.aEnclosesB = aEnclosesB; + var Symbol = (function () { + function Symbol(name, location, length, unitIndex) { + this.name = name; + this.location = location; + this.length = length; + this.unitIndex = unitIndex; + this.bound = false; + this.flags = TypeScript.SymbolFlags.None; + this.isObjectLitField = false; + this.declAST = null; + this.declModule = null; + this.passSymbolCreated = TypeScript.CompilerDiagnostics.analysisPass; + } + Symbol.prototype.instanceScope = function () { + return null; + }; + Symbol.prototype.isVariable = function () { + return false; + }; + Symbol.prototype.isMember = function () { + return false; + }; + Symbol.prototype.isInferenceSymbol = function () { + return false; + }; + Symbol.prototype.isWith = function () { + return false; + }; + Symbol.prototype.writeable = function () { + return false; + }; + Symbol.prototype.isType = function () { + return false; + }; + Symbol.prototype.getType = function () { + return null; + }; + Symbol.prototype.isAccessor = function () { + return false; + }; + Symbol.prototype.isInstanceProperty = function () { + return TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Property) && (!TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.ModuleMember)); + }; + Symbol.prototype.getTypeName = function (scope) { + return this.getTypeNameEx(scope).toString(); + }; + Symbol.prototype.getTypeNameEx = function (scope) { + return TypeScript.MemberName.create(this.toString()); + }; + Symbol.prototype.getOptionalNameString = function () { + return TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Optional) ? "?" : ""; + }; + Symbol.prototype.pathToRoot = function () { + var path = new Array(); + var node = this; + while(node && (node.name != TypeScript.globalId)) { + path[path.length] = node; + node = node.container; + } + return path; + }; + Symbol.prototype.findCommonAncestorPath = function (b) { + if(this.container == null) { + return new Array(); + } + var aPath = this.container.pathToRoot(); + var bPath; + if(b) { + bPath = b.pathToRoot(); + } else { + bPath = new Array(); + } + var commonNodeIndex = -1; + for(var i = 0, aLen = aPath.length; i < aLen; i++) { + var aNode = aPath[i]; + for(var j = 0, bLen = bPath.length; j < bLen; j++) { + var bNode = bPath[j]; + if(aNode == bNode) { + commonNodeIndex = i; + break; + } + } + if(commonNodeIndex >= 0) { + break; + } + } + if(commonNodeIndex >= 0) { + return aPath.slice(0, commonNodeIndex); + } else { + return aPath; + } + }; + Symbol.prototype.getPrettyName = function (scopeSymbol) { + return this.name; + }; + Symbol.prototype.scopeRelativeName = function (scope) { + if(scope == null) { + return this.getPrettyName(null) + this.getOptionalNameString(); + } + var lca = this.findCommonAncestorPath(scope.container); + var builder = ""; + for(var i = 0, len = lca.length; i < len; i++) { + var prettyName = lca[i].getPrettyName(i == len - 1 ? scope.container : lca[i + 1]); + builder = prettyName + "." + builder; + } + builder += this.getPrettyName(len == 0 ? scope.container : lca[0]) + this.getOptionalNameString(); + return builder; + }; + Symbol.prototype.fullName = function () { + var builder = this.name; + var ancestor = this.container; + while(ancestor && (ancestor.name != TypeScript.globalId)) { + builder = ancestor.name + "." + builder; + ancestor = ancestor.container; + } + return builder; + }; + Symbol.prototype.isExternallyVisible = function (checker) { + if(this == checker.gloMod) { + return true; + } + if(TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Private)) { + return false; + } + if(!TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Exported)) { + return this.container == checker.gloMod; + } + return this.container.isExternallyVisible(checker); + }; + Symbol.prototype.visible = function (scope, checker) { + if(checker == null || this.container == checker.gloMod) { + return true; + } + if(TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.ModuleMember)) { + if(TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Exported)) { + if(!TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Private)) { + return true; + } else { + return aEnclosesB(this, scope.container); + } + } else { + return checker && (checker.currentModDecl == this.declModule) || (checker.currentModDecl && checker.currentModDecl.mod && checker.currentModDecl.mod.symbol && this.declModule && this.declModule.mod && this.declModule.mod.symbol && aEnclosesB(checker.currentModDecl.mod.symbol, this.declModule.mod.symbol)); + } + } else { + var isFunction = this.declAST && this.declAST.nodeType == TypeScript.NodeType.FuncDecl; + var isMethod = isFunction && (this.declAST).isMethod(); + var isStaticFunction = isFunction && TypeScript.hasFlag((this.declAST).fncFlags, TypeScript.FncFlags.Static); + var isPrivateMethod = isMethod && TypeScript.hasFlag((this.declAST).fncFlags, TypeScript.FncFlags.Private); + var isAlias = this.isType() && (this).aliasLink; + if(this.isMember() || isMethod || isStaticFunction || isAlias) { + if(TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Private) || isPrivateMethod) { + if(scope.container == null && this.container != scope.container) { + return false; + } else { + return this.container == null ? true : aEnclosesB(scope.container, this.container); + } + } else { + return true; + } + } else { + if(this.container) { + return aEnclosesB(this, scope.container); + } else { + return true; + } + } + } + }; + Symbol.prototype.addRef = function (identifier) { + if(!this.refs) { + this.refs = []; + } + this.refs[this.refs.length] = identifier; + }; + Symbol.prototype.toString = function () { + if(this.name) { + return this.name; + } else { + return "_anonymous"; + } + }; + Symbol.prototype.print = function (outfile) { + outfile.Write(this.toString()); + }; + Symbol.prototype.specializeType = function (pattern, replacement, checker) { + throw new Error("please implement in derived class"); + }; + Symbol.prototype.setType = function (type) { + throw new Error("please implement in derived class"); + }; + Symbol.prototype.kind = function () { + throw new Error("please implement in derived class"); + }; + Symbol.prototype.getInterfaceDeclFromSymbol = function (checker) { + if(this.declAST != null) { + if(this.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) { + return this.declAST; + } else { + if(this.container != null && this.container != checker.gloMod && this.container.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) { + return this.container.declAST; + } + } + } + return null; + }; + Symbol.prototype.getVarDeclFromSymbol = function () { + if(this.declAST != null && this.declAST.nodeType == TypeScript.NodeType.VarDecl) { + return this.declAST; + } + return null; + }; + Symbol.prototype.getDocComments = function () { + if(this.declAST != null) { + return this.declAST.getDocComments(); + } + return []; + }; + Symbol.prototype.isStatic = function () { + return TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Static); + }; + return Symbol; + })(); + TypeScript.Symbol = Symbol; + var ValueLocation = (function () { + function ValueLocation() { } + return ValueLocation; + })(); + TypeScript.ValueLocation = ValueLocation; + var InferenceSymbol = (function (_super) { + __extends(InferenceSymbol, _super); + function InferenceSymbol(name, location, length, unitIndex) { + _super.call(this, name, location, length, unitIndex); + this.typeCheckStatus = TypeCheckStatus.NotStarted; + } + InferenceSymbol.prototype.isInferenceSymbol = function () { + return true; + }; + InferenceSymbol.prototype.transferVarFlags = function (varFlags) { + if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Ambient)) { + this.flags |= TypeScript.SymbolFlags.Ambient; + } + if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Constant)) { + this.flags |= TypeScript.SymbolFlags.Constant; + } + if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Static)) { + this.flags |= TypeScript.SymbolFlags.Static; + } + if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Property)) { + this.flags |= TypeScript.SymbolFlags.Property; + } + if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Private)) { + this.flags |= TypeScript.SymbolFlags.Private; + } + if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Public)) { + this.flags |= TypeScript.SymbolFlags.Public; + } + if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Readonly)) { + this.flags |= TypeScript.SymbolFlags.Readonly; + } + if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Exported)) { + this.flags |= TypeScript.SymbolFlags.Exported; + } + }; + return InferenceSymbol; + })(Symbol); + TypeScript.InferenceSymbol = InferenceSymbol; + var TypeSymbol = (function (_super) { + __extends(TypeSymbol, _super); + function TypeSymbol(locName, location, length, unitIndex, type) { + _super.call(this, locName, location, length, unitIndex); + this.type = type; + this.expansions = []; + this.expansionsDeclAST = []; + this.isDynamic = false; + this.isMethod = false; + this.aliasLink = null; + this.onlyReferencedAsTypeRef = TypeScript.optimizeModuleCodeGen; + this.prettyName = this.name; + } + TypeSymbol.prototype.addLocation = function (loc) { + if(this.additionalLocations == null) { + this.additionalLocations = []; + } + this.additionalLocations[this.additionalLocations.length] = loc; + }; + TypeSymbol.prototype.kind = function () { + return TypeScript.SymbolKind.Type; + }; + TypeSymbol.prototype.isType = function () { + return true; + }; + TypeSymbol.prototype.getType = function () { + return this.type; + }; + TypeSymbol.prototype.getTypeNameEx = function (scope) { + return this.type.getMemberTypeNameEx(this.name ? this.name + this.getOptionalNameString() : "", false, false, scope); + }; + TypeSymbol.prototype.instanceScope = function () { + if(!(this.type.typeFlags & TypeScript.TypeFlags.IsClass) && this.type.isClass()) { + return this.type.instanceType.constructorScope; + } else { + return this.type.containedScope; + } + }; + TypeSymbol.prototype.toString = function () { + var result = this.type.getTypeName(); + if(this.name) { + result = this.name + ":" + result; + } + return result; + }; + TypeSymbol.prototype.isClass = function () { + return this.instanceType != null; + }; + TypeSymbol.prototype.isFunction = function () { + return this.declAST != null && this.declAST.nodeType == TypeScript.NodeType.FuncDecl; + }; + TypeSymbol.prototype.specializeType = function (pattern, replacement, checker) { + if(this.type == pattern) { + return replacement.symbol; + } else { + var replType = this.type.specializeType(pattern, replacement, checker, false); + if(replType != this.type) { + var result = new TypeSymbol(this.name, -1, 0, -1, replType); + return result; + } else { + return this; + } + } + }; + TypeSymbol.prototype.getPrettyName = function (scopeSymbol) { + if(!!scopeSymbol && TypeScript.isQuoted(this.prettyName) && this.type.isModuleType()) { + var symbolPath = scopeSymbol.pathToRoot(); + var prettyName = this.getPrettyNameOfDynamicModule(symbolPath); + if(prettyName != null) { + return prettyName.name; + } + } + return this.prettyName; + }; + TypeSymbol.prototype.getPrettyNameOfDynamicModule = function (scopeSymbolPath) { + var scopeSymbolPathLength = scopeSymbolPath.length; + var externalSymbol = null; + if(scopeSymbolPath.length > 0 && scopeSymbolPath[scopeSymbolPathLength - 1].getType().isModuleType() && (scopeSymbolPath[scopeSymbolPathLength - 1]).isDynamic) { + if(scopeSymbolPathLength > 1 && scopeSymbolPath[scopeSymbolPathLength - 2].getType().isModuleType() && (scopeSymbolPath[scopeSymbolPathLength - 2]).isDynamic) { + var moduleType = scopeSymbolPath[scopeSymbolPathLength - 2].getType(); + externalSymbol = moduleType.findDynamicModuleName(this.type); + } + if(externalSymbol == null) { + var moduleType = scopeSymbolPath[scopeSymbolPathLength - 1].getType(); + externalSymbol = moduleType.findDynamicModuleName(this.type); + } + } + return externalSymbol; + }; + TypeSymbol.prototype.getDocComments = function () { + var comments = []; + if(this.declAST != null) { + comments = comments.concat(this.declAST.getDocComments()); + } + for(var i = 0; i < this.expansionsDeclAST.length; i++) { + comments = comments.concat(this.expansionsDeclAST[i].getDocComments()); + } + return comments; + }; + return TypeSymbol; + })(InferenceSymbol); + TypeScript.TypeSymbol = TypeSymbol; + var WithSymbol = (function (_super) { + __extends(WithSymbol, _super); + function WithSymbol(location, unitIndex, withType) { + _super.call(this, "with", location, 4, unitIndex, withType); + } + WithSymbol.prototype.isWith = function () { + return true; + }; + return WithSymbol; + })(TypeSymbol); + TypeScript.WithSymbol = WithSymbol; + var FieldSymbol = (function (_super) { + __extends(FieldSymbol, _super); + function FieldSymbol(name, location, unitIndex, canWrite, field) { + _super.call(this, name, location, name.length, unitIndex); + this.canWrite = canWrite; + this.field = field; + this.getter = null; + this.setter = null; + this.hasBeenEmitted = false; + this.name = name; + this.location = location; + } + FieldSymbol.prototype.kind = function () { + return TypeScript.SymbolKind.Field; + }; + FieldSymbol.prototype.writeable = function () { + return this.isAccessor() ? this.setter != null : this.canWrite; + }; + FieldSymbol.prototype.getType = function () { + return this.field.typeLink.type; + }; + FieldSymbol.prototype.getTypeNameEx = function (scope) { + return TypeScript.MemberName.create(this.field.typeLink.type.getScopedTypeNameEx(scope), this.name + this.getOptionalNameString() + ": ", ""); + }; + FieldSymbol.prototype.isMember = function () { + return true; + }; + FieldSymbol.prototype.setType = function (type) { + this.field.typeLink.type = type; + }; + FieldSymbol.prototype.isAccessor = function () { + return this.getter != null || this.setter != null; + }; + FieldSymbol.prototype.isVariable = function () { + return true; + }; + FieldSymbol.prototype.toString = function () { + return this.getTypeNameEx(null).toString(); + }; + FieldSymbol.prototype.specializeType = function (pattern, replacement, checker) { + var rType = this.field.typeLink.type.specializeType(pattern, replacement, checker, false); + if(rType != this.field.typeLink.type) { + var fieldDef = new ValueLocation(); + var result = new FieldSymbol(this.name, 0, checker.locationInfo.unitIndex, this.canWrite, fieldDef); + result.flags = this.flags; + fieldDef.symbol = result; + fieldDef.typeLink = new TypeScript.TypeLink(); + result.setType(rType); + result.typeCheckStatus = TypeCheckStatus.Finished; + return result; + } else { + return this; + } + }; + FieldSymbol.prototype.getDocComments = function () { + if(this.getter != null || this.setter != null) { + var comments = []; + if(this.getter != null) { + comments = comments.concat(this.getter.getDocComments()); + } + if(this.setter != null) { + comments = comments.concat(this.setter.getDocComments()); + } + return comments; + } else { + if(this.declAST != null) { + return this.declAST.getDocComments(); + } + } + return []; + }; + return FieldSymbol; + })(InferenceSymbol); + TypeScript.FieldSymbol = FieldSymbol; + var ParameterSymbol = (function (_super) { + __extends(ParameterSymbol, _super); + function ParameterSymbol(name, location, unitIndex, parameter) { + _super.call(this, name, location, name.length, unitIndex); + this.parameter = parameter; + this.paramDocComment = null; + this.funcDecl = null; + this.argsOffset = (-1); + this.name = name; + this.location = location; + } + ParameterSymbol.prototype.kind = function () { + return TypeScript.SymbolKind.Parameter; + }; + ParameterSymbol.prototype.writeable = function () { + return true; + }; + ParameterSymbol.prototype.getType = function () { + return this.parameter.typeLink.type; + }; + ParameterSymbol.prototype.setType = function (type) { + this.parameter.typeLink.type = type; + }; + ParameterSymbol.prototype.isVariable = function () { + return true; + }; + ParameterSymbol.prototype.isOptional = function () { + if(this.parameter && this.parameter.symbol && this.parameter.symbol.declAST) { + return (this.parameter.symbol.declAST).isOptional; + } else { + return false; + } + }; + ParameterSymbol.prototype.getTypeNameEx = function (scope) { + return TypeScript.MemberName.create(this.getType().getScopedTypeNameEx(scope), this.name + (this.isOptional() ? "?" : "") + ": ", ""); + }; + ParameterSymbol.prototype.toString = function () { + return this.getTypeNameEx(null).toString(); + }; + ParameterSymbol.prototype.specializeType = function (pattern, replacement, checker) { + var rType = this.parameter.typeLink.type.specializeType(pattern, replacement, checker, false); + if(this.parameter.typeLink.type != rType) { + var paramDef = new ValueLocation(); + var result = new ParameterSymbol(this.name, 0, checker.locationInfo.unitIndex, paramDef); + paramDef.symbol = result; + result.setType(rType); + return result; + } else { + return this; + } + }; + ParameterSymbol.prototype.getParameterDocComments = function () { + if(!this.paramDocComment) { + var parameterComments = []; + if(this.funcDecl) { + var fncDocComments = this.funcDecl.getDocComments(); + var paramComment = TypeScript.Comment.getParameterDocCommentText(this.name, fncDocComments); + if(paramComment != "") { + parameterComments.push(paramComment); + } + } + var docComments = TypeScript.Comment.getDocCommentText(this.getDocComments()); + if(docComments != "") { + parameterComments.push(docComments); + } + this.paramDocComment = parameterComments.join("\n"); + } + return this.paramDocComment; + }; + return ParameterSymbol; + })(InferenceSymbol); + TypeScript.ParameterSymbol = ParameterSymbol; + var VariableSymbol = (function (_super) { + __extends(VariableSymbol, _super); + function VariableSymbol(name, location, unitIndex, variable) { + _super.call(this, name, location, name.length, unitIndex); + this.variable = variable; + } + VariableSymbol.prototype.kind = function () { + return TypeScript.SymbolKind.Variable; + }; + VariableSymbol.prototype.writeable = function () { + return true; + }; + VariableSymbol.prototype.getType = function () { + return this.variable.typeLink.type; + }; + VariableSymbol.prototype.getTypeNameEx = function (scope) { + return TypeScript.MemberName.create(this.getType().getScopedTypeNameEx(scope), this.name + ": ", ""); + }; + VariableSymbol.prototype.setType = function (type) { + this.variable.typeLink.type = type; + }; + VariableSymbol.prototype.isVariable = function () { + return true; + }; + return VariableSymbol; + })(InferenceSymbol); + TypeScript.VariableSymbol = VariableSymbol; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ScopedMembers = (function () { + function ScopedMembers(dualMembers) { + this.dualMembers = dualMembers; + this.allMembers = this.dualMembers; + this.publicMembers = this.dualMembers.primaryTable; + this.privateMembers = this.dualMembers.secondaryTable; + } + ScopedMembers.prototype.addPublicMember = function (key, data) { + return this.dualMembers.primaryTable.add(key, data); + }; + ScopedMembers.prototype.addPrivateMember = function (key, data) { + return this.dualMembers.secondaryTable.add(key, data); + }; + return ScopedMembers; + })(); + TypeScript.ScopedMembers = ScopedMembers; + (function (SymbolKind) { + SymbolKind._map = []; + SymbolKind._map[0] = "None"; + SymbolKind.None = 0; + SymbolKind._map[1] = "Type"; + SymbolKind.Type = 1; + SymbolKind._map[2] = "Field"; + SymbolKind.Field = 2; + SymbolKind._map[3] = "Parameter"; + SymbolKind.Parameter = 3; + SymbolKind._map[4] = "Variable"; + SymbolKind.Variable = 4; + })(TypeScript.SymbolKind || (TypeScript.SymbolKind = {})); + var SymbolKind = TypeScript.SymbolKind; + var SymbolScope = (function () { + function SymbolScope(container) { + this.container = container; + } + SymbolScope.prototype.printLabel = function () { + return "base"; + }; + SymbolScope.prototype.getAllSymbolNames = function (members) { + return [ + "please", + "implement", + "in", + "derived", + "classes" + ]; + }; + SymbolScope.prototype.getAllTypeSymbolNames = function (members) { + return [ + "please", + "implement", + "in", + "derived", + "classes" + ]; + }; + SymbolScope.prototype.getAllValueSymbolNames = function (members) { + return [ + "please", + "implement", + "in", + "derived", + "classes" + ]; + }; + SymbolScope.prototype.search = function (filter, name, publicOnly, typespace) { + return null; + }; + SymbolScope.prototype.findLocal = function (name, publicOnly, typespace) { + return null; + }; + SymbolScope.prototype.find = function (name, publicOnly, typespace) { + return null; + }; + SymbolScope.prototype.findImplementation = function (name, publicOnly, typespace) { + return null; + }; + SymbolScope.prototype.findAmbient = function (name, publicOnly, typespace) { + return null; + }; + SymbolScope.prototype.print = function (outfile) { + if(this.container) { + outfile.WriteLine(this.printLabel() + " scope with container: " + this.container.name + "..."); + } else { + outfile.WriteLine(this.printLabel() + " scope..."); + } + }; + SymbolScope.prototype.enter = function (container, ast, symbol, errorReporter, publicOnly, typespace, ambient) { + throw new Error("please implement in derived class"); + }; + SymbolScope.prototype.getTable = function () { + throw new Error("please implement in derived class"); + }; + return SymbolScope; + })(); + TypeScript.SymbolScope = SymbolScope; + function symbolCanBeUsed(sym, publicOnly) { + return publicOnly ? !(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Private) || (sym.declAST && sym.declAST.nodeType == TypeScript.NodeType.FuncDecl && TypeScript.hasFlag((sym.declAST).fncFlags, TypeScript.FncFlags.Private))) : true; + } + var SymbolAggregateScope = (function (_super) { + __extends(SymbolAggregateScope, _super); + function SymbolAggregateScope(container) { + _super.call(this, container); + this.valueCache = null; + this.valueImplCache = null; + this.valueAmbientCache = null; + this.typeCache = null; + this.typeImplCache = null; + this.typeAmbientCache = null; + this.parents = null; + this.container = container; + } + SymbolAggregateScope.prototype.printLabel = function () { + return "agg"; + }; + SymbolAggregateScope.prototype.search = function (filter, name, publicOnly, typespace) { + if(this.parents) { + for(var i = 0; i < this.parents.length; i++) { + var sym = this.parents[i].search(filter, name, publicOnly, typespace); + if(sym) { + if(filter.update(sym)) { + return sym; + } + } + } + } + return filter.result; + }; + SymbolAggregateScope.prototype.getAllSymbolNames = function (members) { + var result = []; + if(this.parents) { + for(var i = 0; i < this.parents.length; i++) { + var parentResult = this.parents[i].getAllSymbolNames(members); + if(parentResult) { + result = result.concat(parentResult); + } + } + } + return result; + }; + SymbolAggregateScope.prototype.getAllTypeSymbolNames = function (members) { + var result = []; + if(this.parents) { + for(var i = 0; i < this.parents.length; i++) { + var parentResult = this.parents[i].getAllTypeSymbolNames(members); + if(parentResult) { + result = result.concat(parentResult); + } + } + } + return result; + }; + SymbolAggregateScope.prototype.getAllValueSymbolNames = function (members) { + var result = []; + if(this.parents) { + for(var i = 0; i < this.parents.length; i++) { + var parentResult = this.parents[i].getAllValueSymbolNames(members); + if(parentResult) { + result = result.concat(parentResult); + } + } + } + return result; + }; + SymbolAggregateScope.prototype.print = function (outfile) { + _super.prototype.print.call(this, outfile); + if(this.parents) { + for(var i = 0; i < this.parents.length; i++) { + this.parents[i].print(outfile); + } + } + }; + SymbolAggregateScope.prototype.findImplementation = function (name, publicOnly, typespace) { + var sym = null; + var i = 0; + var implCache = this.valueImplCache; + if(typespace) { + implCache = this.typeImplCache; + } + if(implCache && ((sym = implCache.lookup(name)) != null) && (publicOnly ? !(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Private) || (sym.declAST && sym.declAST.nodeType == TypeScript.NodeType.FuncDecl && TypeScript.hasFlag((sym.declAST).fncFlags, TypeScript.FncFlags.Private))) : true)) { + return sym; + } + if(this.parents) { + for(i = 0; i < this.parents.length; i++) { + sym = this.parents[i].findImplementation(name, publicOnly, typespace); + if(sym) { + break; + } + } + } + if(implCache) { + if(typespace) { + this.typeImplCache = new TypeScript.StringHashTable(); + implCache = this.typeImplCache; + } else { + this.valueImplCache = new TypeScript.StringHashTable(); + implCache = this.valueImplCache; + } + } + implCache.add(name, sym); + return sym; + }; + SymbolAggregateScope.prototype.find = function (name, publicOnly, typespace) { + var sym = null; + var i = 0; + var cache = this.valueCache; + if(typespace) { + cache = this.typeCache; + } + if(cache && ((sym = cache.lookup(name)) != null) && (publicOnly ? !(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Private) || (sym.declAST && sym.declAST.nodeType == TypeScript.NodeType.FuncDecl && TypeScript.hasFlag((sym.declAST).fncFlags, TypeScript.FncFlags.Private))) : true)) { + return sym; + } + if(this.parents) { + for(i = 0; i < this.parents.length; i++) { + sym = this.parents[i].find(name, publicOnly, typespace); + if(sym) { + break; + } + } + } + if(cache == null) { + if(typespace) { + this.typeCache = new TypeScript.StringHashTable(); + cache = this.typeCache; + } else { + this.valueCache = new TypeScript.StringHashTable(); + cache = this.valueCache; + } + } + cache.add(name, sym); + return sym; + }; + SymbolAggregateScope.prototype.findAmbient = function (name, publicOnly, typespace) { + var sym = null; + var i = 0; + var cache = this.valueAmbientCache; + if(typespace) { + cache = this.typeAmbientCache; + } + if(cache && ((sym = cache.lookup(name)) != null)) { + return sym; + } + if(this.parents) { + for(i = 0; i < this.parents.length; i++) { + sym = this.parents[i].findAmbient(name, publicOnly, typespace); + if(sym) { + break; + } + } + } + if(cache == null) { + if(typespace) { + this.typeAmbientCache = new TypeScript.StringHashTable(); + cache = this.typeAmbientCache; + } else { + this.valueAmbientCache = new TypeScript.StringHashTable(); + cache = this.valueAmbientCache; + } + } + cache.add(name, sym); + return sym; + }; + SymbolAggregateScope.prototype.addParentScope = function (parent) { + if(this.parents == null) { + this.parents = new Array(); + } + this.parents[this.parents.length] = parent; + }; + return SymbolAggregateScope; + })(SymbolScope); + TypeScript.SymbolAggregateScope = SymbolAggregateScope; + var SymbolTableScope = (function (_super) { + __extends(SymbolTableScope, _super); + function SymbolTableScope(valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, container) { + _super.call(this, container); + this.valueMembers = valueMembers; + this.ambientValueMembers = ambientValueMembers; + this.enclosedTypes = enclosedTypes; + this.ambientEnclosedTypes = ambientEnclosedTypes; + this.container = container; + } + SymbolTableScope.prototype.printLabel = function () { + return "table"; + }; + SymbolTableScope.prototype.getAllSymbolNames = function (members) { + var result = this.getAllTypeSymbolNames(members); + return result.concat(this.getAllValueSymbolNames(members)); + }; + SymbolTableScope.prototype.getAllTypeSymbolNames = function (members) { + var result = []; + if(this.ambientEnclosedTypes) { + result = result.concat(this.ambientEnclosedTypes.allMembers.getAllKeys()); + } + if(this.enclosedTypes) { + result = result.concat(this.enclosedTypes.allMembers.getAllKeys()); + } + return result; + }; + SymbolTableScope.prototype.getAllValueSymbolNames = function (members) { + var result = []; + if(this.ambientValueMembers) { + result = result.concat(this.ambientValueMembers.allMembers.getAllKeys()); + } + if(this.valueMembers) { + result = result.concat(this.valueMembers.allMembers.getAllKeys()); + } + return result; + }; + SymbolTableScope.prototype.search = function (filter, name, publicOnly, typespace) { + var sym = this.find(name, publicOnly, typespace); + filter.update(sym); + return filter.result; + }; + SymbolTableScope.prototype.find = function (name, publicOnly, typespace) { + var table = null; + var ambientTable = null; + if(typespace) { + table = (this.enclosedTypes == null) ? null : publicOnly ? this.enclosedTypes.publicMembers : this.enclosedTypes.allMembers; + ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; + } else { + table = (this.valueMembers == null) ? null : publicOnly ? this.valueMembers.publicMembers : this.valueMembers.allMembers; + ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; + } + if(ambientTable) { + var s = ambientTable.lookup(name); + if(s) { + return s; + } + } + if(table) { + var s = table.lookup(name); + if(s) { + return s; + } + } + return null; + }; + SymbolTableScope.prototype.findAmbient = function (name, publicOnly, typespace) { + var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; + if(typespace) { + ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; + } + if(ambientTable) { + var s = ambientTable.lookup(name); + if(s) { + return s; + } + } + return null; + }; + SymbolTableScope.prototype.print = function (outfile) { + _super.prototype.print.call(this, outfile); + if(this.ambientValueMembers) { + this.ambientValueMembers.allMembers.map(function (key, sym, context) { + outfile.WriteLine(" " + key); + }, null); + } + if(this.valueMembers) { + this.valueMembers.allMembers.map(function (key, sym, context) { + outfile.WriteLine(" " + key); + }, null); + } + if(this.ambientEnclosedTypes) { + this.ambientEnclosedTypes.allMembers.map(function (key, sym, context) { + outfile.WriteLine(" " + key); + }, null); + } + if(this.enclosedTypes) { + this.enclosedTypes.allMembers.map(function (key, sym, context) { + outfile.WriteLine(" " + key); + }, null); + } + }; + SymbolTableScope.prototype.findImplementation = function (name, publicOnly, typespace) { + var sym = this.find(name, publicOnly, typespace); + if(sym) { + if(sym.kind() == SymbolKind.Type) { + var typeSym = sym; + if(!typeSym.type.hasImplementation()) { + sym = null; + } + } else { + if(sym.container) { + if(sym.container.kind() == SymbolKind.Type) { + var ctypeSym = sym.container; + if(!ctypeSym.type.hasImplementation()) { + sym = null; + } + } + } + } + } + return sym; + }; + SymbolTableScope.prototype.getTable = function () { + return this.valueMembers.publicMembers; + }; + return SymbolTableScope; + })(SymbolScope); + TypeScript.SymbolTableScope = SymbolTableScope; + var SymbolScopeBuilder = (function (_super) { + __extends(SymbolScopeBuilder, _super); + function SymbolScopeBuilder(valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, parent, container) { + _super.call(this, container); + this.valueMembers = valueMembers; + this.ambientValueMembers = ambientValueMembers; + this.enclosedTypes = enclosedTypes; + this.ambientEnclosedTypes = ambientEnclosedTypes; + this.parent = parent; + this.container = container; + } + SymbolScopeBuilder.prototype.printLabel = function () { + return "builder"; + }; + SymbolScopeBuilder.prototype.getAllSymbolNames = function (members) { + var result = this.getAllTypeSymbolNames(members); + return result.concat(this.getAllValueSymbolNames(members)); + }; + SymbolScopeBuilder.prototype.getAllTypeSymbolNames = function (members) { + var result = []; + if(this.ambientEnclosedTypes) { + result = result.concat(this.ambientEnclosedTypes.allMembers.getAllKeys()); + } + if(this.enclosedTypes) { + result = result.concat(this.enclosedTypes.allMembers.getAllKeys()); + } + if(!members && this.parent) { + var parentResult = this.parent.getAllTypeSymbolNames(members); + if(parentResult) { + result = result.concat(parentResult); + } + } + return result; + }; + SymbolScopeBuilder.prototype.getAllValueSymbolNames = function (members) { + var result = []; + if(this.ambientValueMembers) { + result = result.concat(this.ambientValueMembers.allMembers.getAllKeys()); + } + if(this.valueMembers) { + result = result.concat(this.valueMembers.allMembers.getAllKeys()); + } + if(!members && this.parent) { + var parentResult = this.parent.getAllValueSymbolNames(members); + if(parentResult) { + result = result.concat(parentResult); + } + } + return result; + }; + SymbolScopeBuilder.prototype.search = function (filter, name, publicOnly, typespace) { + var sym = null; + var table = (this.valueMembers == null) ? null : publicOnly ? this.valueMembers.publicMembers : this.valueMembers.allMembers; + var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; + if(typespace) { + table = (this.enclosedTypes == null) ? null : publicOnly ? this.enclosedTypes.publicMembers : this.enclosedTypes.allMembers; + ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; + } + if(ambientTable) { + if((sym = ambientTable.lookup(name)) != null) { + if(filter.update(sym)) { + return sym; + } + } + } + if(table) { + if((sym = table.lookup(name)) != null) { + if(filter.update(sym)) { + return sym; + } + } + } + if(this.parent) { + sym = this.parent.search(filter, name, publicOnly, typespace); + if(sym) { + if(filter.update(sym)) { + return sym; + } + } + } + return filter.result; + }; + SymbolScopeBuilder.prototype.print = function (outfile) { + _super.prototype.print.call(this, outfile); + if(this.ambientValueMembers) { + this.ambientValueMembers.allMembers.map(function (key, s, context) { + var sym = s; + outfile.WriteLine(" " + key); + }, null); + } + if(this.valueMembers) { + this.valueMembers.allMembers.map(function (key, s, context) { + var sym = s; + outfile.WriteLine(" " + key); + }, null); + } + if(this.ambientEnclosedTypes) { + this.ambientEnclosedTypes.allMembers.map(function (key, s, context) { + var sym = s; + outfile.WriteLine(" " + key); + }, null); + } + if(this.enclosedTypes) { + this.enclosedTypes.allMembers.map(function (key, s, context) { + var sym = s; + outfile.WriteLine(" " + key); + }, null); + } + if(this.parent) { + this.parent.print(outfile); + } + }; + SymbolScopeBuilder.prototype.find = function (name, publicOnly, typespace) { + var sym = null; + var table = (this.valueMembers == null) ? null : publicOnly ? this.valueMembers.publicMembers : this.valueMembers.allMembers; + var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; + if(typespace) { + table = (this.enclosedTypes == null) ? null : publicOnly ? this.enclosedTypes.publicMembers : this.enclosedTypes.allMembers; + ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; + } + if(ambientTable && ((sym = ambientTable.lookup(name)) != null)) { + return sym; + } + if(table && ((sym = table.lookup(name)) != null)) { + return sym; + } + if(this.parent) { + return this.parent.find(name, publicOnly, typespace); + } + return null; + }; + SymbolScopeBuilder.prototype.findAmbient = function (name, publicOnly, typespace) { + var sym = null; + var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; + if(typespace) { + ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; + } + if(ambientTable && ((sym = ambientTable.lookup(name)) != null)) { + return sym; + } + if(this.parent) { + return this.parent.findAmbient(name, publicOnly, typespace); + } + return null; + }; + SymbolScopeBuilder.prototype.findLocal = function (name, publicOnly, typespace) { + var sym = null; + var table = (this.valueMembers == null) ? null : publicOnly ? this.valueMembers.publicMembers : this.valueMembers.allMembers; + var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; + if(typespace) { + table = (this.enclosedTypes == null) ? null : publicOnly ? this.enclosedTypes.publicMembers : this.enclosedTypes.allMembers; + ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; + } + if(table) { + if((sym = table.lookup(name)) != null) { + if(sym) { + return sym; + } + } + } + if(ambientTable) { + if((sym = ambientTable.lookup(name)) != null) { + if(sym) { + return sym; + } + } + } + return null; + }; + SymbolScopeBuilder.prototype.enter = function (container, ast, symbol, errorReporter, insertAsPublic, typespace, ambient) { + var table = null; + if(ambient) { + if(typespace) { + table = (this.ambientEnclosedTypes == null) ? null : insertAsPublic ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.privateMembers; + } else { + table = (this.ambientValueMembers == null) ? null : insertAsPublic ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.privateMembers; + } + } else { + if(typespace) { + table = (this.enclosedTypes == null) ? null : insertAsPublic ? this.enclosedTypes.publicMembers : this.enclosedTypes.privateMembers; + } else { + table = (this.valueMembers == null) ? null : insertAsPublic ? this.valueMembers.publicMembers : this.valueMembers.privateMembers; + } + } + if(table) { + if(!table.add(symbol.name, symbol)) { + errorReporter.duplicateIdentifier(ast, symbol.name); + } + } else { + TypeScript.CompilerDiagnostics.Alert("YYYYY"); + } + symbol.container = container; + }; + SymbolScopeBuilder.prototype.getTable = function () { + return this.valueMembers.allMembers; + }; + return SymbolScopeBuilder; + })(SymbolScope); + TypeScript.SymbolScopeBuilder = SymbolScopeBuilder; + var FilteredSymbolScope = (function (_super) { + __extends(FilteredSymbolScope, _super); + function FilteredSymbolScope(scope, container, filter) { + _super.call(this, container); + this.scope = scope; + this.filter = filter; + } + FilteredSymbolScope.prototype.print = function (outfile) { + this.scope.print(outfile); + }; + FilteredSymbolScope.prototype.find = function (name, publicOnly, typespace) { + this.filter.reset(); + return this.scope.search(this.filter, name, publicOnly, typespace); + }; + FilteredSymbolScope.prototype.findLocal = function (name, publicOnly, typespace) { + return this.scope.findLocal(name, publicOnly, typespace); + }; + return FilteredSymbolScope; + })(SymbolScope); + TypeScript.FilteredSymbolScope = FilteredSymbolScope; + var FilteredSymbolScopeBuilder = (function (_super) { + __extends(FilteredSymbolScopeBuilder, _super); + function FilteredSymbolScopeBuilder(valueMembers, parent, container, filter) { + _super.call(this, valueMembers, null, null, null, parent, container); + this.filter = filter; + } + FilteredSymbolScopeBuilder.prototype.findLocal = function (name, publicOnly, typespace) { + var sym = _super.prototype.findLocal.call(this, name, publicOnly, typespace); + if(sym) { + if(!this.filter(sym)) { + return null; + } + } + return sym; + }; + FilteredSymbolScopeBuilder.prototype.search = function (filter, name, publicOnly, typespace) { + throw new Error("please implement"); + }; + FilteredSymbolScopeBuilder.prototype.find = function (name, publicOnly, typespace) { + var sym = _super.prototype.findLocal.call(this, name, publicOnly, typespace); + if(sym) { + if(!this.filter(sym)) { + return null; + } + } + return _super.prototype.find.call(this, name, publicOnly, typespace); + }; + return FilteredSymbolScopeBuilder; + })(SymbolScopeBuilder); + TypeScript.FilteredSymbolScopeBuilder = FilteredSymbolScopeBuilder; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (TokenID) { + TokenID._map = []; + TokenID._map[0] = "Any"; + TokenID.Any = 0; + TokenID._map[1] = "Bool"; + TokenID.Bool = 1; + TokenID._map[2] = "Break"; + TokenID.Break = 2; + TokenID._map[3] = "Case"; + TokenID.Case = 3; + TokenID._map[4] = "Catch"; + TokenID.Catch = 4; + TokenID._map[5] = "Class"; + TokenID.Class = 5; + TokenID._map[6] = "Const"; + TokenID.Const = 6; + TokenID._map[7] = "Continue"; + TokenID.Continue = 7; + TokenID._map[8] = "Debugger"; + TokenID.Debugger = 8; + TokenID._map[9] = "Default"; + TokenID.Default = 9; + TokenID._map[10] = "Delete"; + TokenID.Delete = 10; + TokenID._map[11] = "Do"; + TokenID.Do = 11; + TokenID._map[12] = "Else"; + TokenID.Else = 12; + TokenID._map[13] = "Enum"; + TokenID.Enum = 13; + TokenID._map[14] = "Export"; + TokenID.Export = 14; + TokenID._map[15] = "Extends"; + TokenID.Extends = 15; + TokenID._map[16] = "Declare"; + TokenID.Declare = 16; + TokenID._map[17] = "False"; + TokenID.False = 17; + TokenID._map[18] = "Finally"; + TokenID.Finally = 18; + TokenID._map[19] = "For"; + TokenID.For = 19; + TokenID._map[20] = "Function"; + TokenID.Function = 20; + TokenID._map[21] = "Constructor"; + TokenID.Constructor = 21; + TokenID._map[22] = "Get"; + TokenID.Get = 22; + TokenID._map[23] = "If"; + TokenID.If = 23; + TokenID._map[24] = "Implements"; + TokenID.Implements = 24; + TokenID._map[25] = "Import"; + TokenID.Import = 25; + TokenID._map[26] = "In"; + TokenID.In = 26; + TokenID._map[27] = "InstanceOf"; + TokenID.InstanceOf = 27; + TokenID._map[28] = "Interface"; + TokenID.Interface = 28; + TokenID._map[29] = "Let"; + TokenID.Let = 29; + TokenID._map[30] = "Module"; + TokenID.Module = 30; + TokenID._map[31] = "New"; + TokenID.New = 31; + TokenID._map[32] = "Number"; + TokenID.Number = 32; + TokenID._map[33] = "Null"; + TokenID.Null = 33; + TokenID._map[34] = "Package"; + TokenID.Package = 34; + TokenID._map[35] = "Private"; + TokenID.Private = 35; + TokenID._map[36] = "Protected"; + TokenID.Protected = 36; + TokenID._map[37] = "Public"; + TokenID.Public = 37; + TokenID._map[38] = "Return"; + TokenID.Return = 38; + TokenID._map[39] = "Set"; + TokenID.Set = 39; + TokenID._map[40] = "Static"; + TokenID.Static = 40; + TokenID._map[41] = "String"; + TokenID.String = 41; + TokenID._map[42] = "Super"; + TokenID.Super = 42; + TokenID._map[43] = "Switch"; + TokenID.Switch = 43; + TokenID._map[44] = "This"; + TokenID.This = 44; + TokenID._map[45] = "Throw"; + TokenID.Throw = 45; + TokenID._map[46] = "True"; + TokenID.True = 46; + TokenID._map[47] = "Try"; + TokenID.Try = 47; + TokenID._map[48] = "TypeOf"; + TokenID.TypeOf = 48; + TokenID._map[49] = "Var"; + TokenID.Var = 49; + TokenID._map[50] = "Void"; + TokenID.Void = 50; + TokenID._map[51] = "With"; + TokenID.With = 51; + TokenID._map[52] = "While"; + TokenID.While = 52; + TokenID._map[53] = "Yield"; + TokenID.Yield = 53; + TokenID._map[54] = "Semicolon"; + TokenID.Semicolon = 54; + TokenID._map[55] = "OpenParen"; + TokenID.OpenParen = 55; + TokenID._map[56] = "CloseParen"; + TokenID.CloseParen = 56; + TokenID._map[57] = "OpenBracket"; + TokenID.OpenBracket = 57; + TokenID._map[58] = "CloseBracket"; + TokenID.CloseBracket = 58; + TokenID._map[59] = "OpenBrace"; + TokenID.OpenBrace = 59; + TokenID._map[60] = "CloseBrace"; + TokenID.CloseBrace = 60; + TokenID._map[61] = "Comma"; + TokenID.Comma = 61; + TokenID._map[62] = "Equals"; + TokenID.Equals = 62; + TokenID._map[63] = "PlusEquals"; + TokenID.PlusEquals = 63; + TokenID._map[64] = "MinusEquals"; + TokenID.MinusEquals = 64; + TokenID._map[65] = "AsteriskEquals"; + TokenID.AsteriskEquals = 65; + TokenID._map[66] = "SlashEquals"; + TokenID.SlashEquals = 66; + TokenID._map[67] = "PercentEquals"; + TokenID.PercentEquals = 67; + TokenID._map[68] = "AmpersandEquals"; + TokenID.AmpersandEquals = 68; + TokenID._map[69] = "CaretEquals"; + TokenID.CaretEquals = 69; + TokenID._map[70] = "BarEquals"; + TokenID.BarEquals = 70; + TokenID._map[71] = "LessThanLessThanEquals"; + TokenID.LessThanLessThanEquals = 71; + TokenID._map[72] = "GreaterThanGreaterThanEquals"; + TokenID.GreaterThanGreaterThanEquals = 72; + TokenID._map[73] = "GreaterThanGreaterThanGreaterThanEquals"; + TokenID.GreaterThanGreaterThanGreaterThanEquals = 73; + TokenID._map[74] = "Question"; + TokenID.Question = 74; + TokenID._map[75] = "Colon"; + TokenID.Colon = 75; + TokenID._map[76] = "BarBar"; + TokenID.BarBar = 76; + TokenID._map[77] = "AmpersandAmpersand"; + TokenID.AmpersandAmpersand = 77; + TokenID._map[78] = "Bar"; + TokenID.Bar = 78; + TokenID._map[79] = "Caret"; + TokenID.Caret = 79; + TokenID._map[80] = "And"; + TokenID.And = 80; + TokenID._map[81] = "EqualsEquals"; + TokenID.EqualsEquals = 81; + TokenID._map[82] = "ExclamationEquals"; + TokenID.ExclamationEquals = 82; + TokenID._map[83] = "EqualsEqualsEquals"; + TokenID.EqualsEqualsEquals = 83; + TokenID._map[84] = "ExclamationEqualsEquals"; + TokenID.ExclamationEqualsEquals = 84; + TokenID._map[85] = "LessThan"; + TokenID.LessThan = 85; + TokenID._map[86] = "LessThanEquals"; + TokenID.LessThanEquals = 86; + TokenID._map[87] = "GreaterThan"; + TokenID.GreaterThan = 87; + TokenID._map[88] = "GreaterThanEquals"; + TokenID.GreaterThanEquals = 88; + TokenID._map[89] = "LessThanLessThan"; + TokenID.LessThanLessThan = 89; + TokenID._map[90] = "GreaterThanGreaterThan"; + TokenID.GreaterThanGreaterThan = 90; + TokenID._map[91] = "GreaterThanGreaterThanGreaterThan"; + TokenID.GreaterThanGreaterThanGreaterThan = 91; + TokenID._map[92] = "Plus"; + TokenID.Plus = 92; + TokenID._map[93] = "Minus"; + TokenID.Minus = 93; + TokenID._map[94] = "Asterisk"; + TokenID.Asterisk = 94; + TokenID._map[95] = "Slash"; + TokenID.Slash = 95; + TokenID._map[96] = "Percent"; + TokenID.Percent = 96; + TokenID._map[97] = "Tilde"; + TokenID.Tilde = 97; + TokenID._map[98] = "Exclamation"; + TokenID.Exclamation = 98; + TokenID._map[99] = "PlusPlus"; + TokenID.PlusPlus = 99; + TokenID._map[100] = "MinusMinus"; + TokenID.MinusMinus = 100; + TokenID._map[101] = "Dot"; + TokenID.Dot = 101; + TokenID._map[102] = "DotDotDot"; + TokenID.DotDotDot = 102; + TokenID._map[103] = "Error"; + TokenID.Error = 103; + TokenID._map[104] = "EndOfFile"; + TokenID.EndOfFile = 104; + TokenID._map[105] = "EqualsGreaterThan"; + TokenID.EqualsGreaterThan = 105; + TokenID._map[106] = "Identifier"; + TokenID.Identifier = 106; + TokenID._map[107] = "StringLiteral"; + TokenID.StringLiteral = 107; + TokenID._map[108] = "RegularExpressionLiteral"; + TokenID.RegularExpressionLiteral = 108; + TokenID._map[109] = "NumberLiteral"; + TokenID.NumberLiteral = 109; + TokenID._map[110] = "Whitespace"; + TokenID.Whitespace = 110; + TokenID._map[111] = "Comment"; + TokenID.Comment = 111; + TokenID._map[112] = "Lim"; + TokenID.Lim = 112; + TokenID.LimFixed = TokenID.EqualsGreaterThan; + TokenID.LimKeyword = TokenID.Yield; + })(TypeScript.TokenID || (TypeScript.TokenID = {})); + var TokenID = TypeScript.TokenID; + TypeScript.tokenTable = new Array(); + TypeScript.nodeTypeTable = new Array(); + TypeScript.nodeTypeToTokTable = new Array(); + TypeScript.noRegexTable = new Array(); + TypeScript.noRegexTable[TokenID.Identifier] = true; + TypeScript.noRegexTable[TokenID.StringLiteral] = true; + TypeScript.noRegexTable[TokenID.NumberLiteral] = true; + TypeScript.noRegexTable[TokenID.RegularExpressionLiteral] = true; + TypeScript.noRegexTable[TokenID.This] = true; + TypeScript.noRegexTable[TokenID.PlusPlus] = true; + TypeScript.noRegexTable[TokenID.MinusMinus] = true; + TypeScript.noRegexTable[TokenID.CloseParen] = true; + TypeScript.noRegexTable[TokenID.CloseBracket] = true; + TypeScript.noRegexTable[TokenID.CloseBrace] = true; + TypeScript.noRegexTable[TokenID.True] = true; + TypeScript.noRegexTable[TokenID.False] = true; + (function (OperatorPrecedence) { + OperatorPrecedence._map = []; + OperatorPrecedence._map[0] = "None"; + OperatorPrecedence.None = 0; + OperatorPrecedence._map[1] = "Comma"; + OperatorPrecedence.Comma = 1; + OperatorPrecedence._map[2] = "Assignment"; + OperatorPrecedence.Assignment = 2; + OperatorPrecedence._map[3] = "Conditional"; + OperatorPrecedence.Conditional = 3; + OperatorPrecedence._map[4] = "LogicalOr"; + OperatorPrecedence.LogicalOr = 4; + OperatorPrecedence._map[5] = "LogicalAnd"; + OperatorPrecedence.LogicalAnd = 5; + OperatorPrecedence._map[6] = "BitwiseOr"; + OperatorPrecedence.BitwiseOr = 6; + OperatorPrecedence._map[7] = "BitwiseExclusiveOr"; + OperatorPrecedence.BitwiseExclusiveOr = 7; + OperatorPrecedence._map[8] = "BitwiseAnd"; + OperatorPrecedence.BitwiseAnd = 8; + OperatorPrecedence._map[9] = "Equality"; + OperatorPrecedence.Equality = 9; + OperatorPrecedence._map[10] = "Relational"; + OperatorPrecedence.Relational = 10; + OperatorPrecedence._map[11] = "Shift"; + OperatorPrecedence.Shift = 11; + OperatorPrecedence._map[12] = "Additive"; + OperatorPrecedence.Additive = 12; + OperatorPrecedence._map[13] = "Multiplicative"; + OperatorPrecedence.Multiplicative = 13; + OperatorPrecedence._map[14] = "Unary"; + OperatorPrecedence.Unary = 14; + OperatorPrecedence._map[15] = "Lim"; + OperatorPrecedence.Lim = 15; + })(TypeScript.OperatorPrecedence || (TypeScript.OperatorPrecedence = {})); + var OperatorPrecedence = TypeScript.OperatorPrecedence; + (function (Reservation) { + Reservation._map = []; + Reservation.None = 0; + Reservation.Javascript = 1; + Reservation.JavascriptFuture = 2; + Reservation.TypeScript = 4; + Reservation.JavascriptFutureStrict = 8; + Reservation.TypeScriptAndJS = Reservation.Javascript | Reservation.TypeScript; + Reservation.TypeScriptAndJSFuture = Reservation.JavascriptFuture | Reservation.TypeScript; + Reservation.TypeScriptAndJSFutureStrict = Reservation.JavascriptFutureStrict | Reservation.TypeScript; + })(TypeScript.Reservation || (TypeScript.Reservation = {})); + var Reservation = TypeScript.Reservation; + var TokenInfo = (function () { + function TokenInfo(tokenId, reservation, binopPrecedence, binopNodeType, unopPrecedence, unopNodeType, text, ers) { + this.tokenId = tokenId; + this.reservation = reservation; + this.binopPrecedence = binopPrecedence; + this.binopNodeType = binopNodeType; + this.unopPrecedence = unopPrecedence; + this.unopNodeType = unopNodeType; + this.text = text; + this.ers = ers; + } + return TokenInfo; + })(); + TypeScript.TokenInfo = TokenInfo; + function setTokenInfo(tokenId, reservation, binopPrecedence, binopNodeType, unopPrecedence, unopNodeType, text, ers) { + if(tokenId !== undefined) { + TypeScript.tokenTable[tokenId] = new TokenInfo(tokenId, reservation, binopPrecedence, binopNodeType, unopPrecedence, unopNodeType, text, ers); + if(binopNodeType != TypeScript.NodeType.None) { + TypeScript.nodeTypeTable[binopNodeType] = text; + TypeScript.nodeTypeToTokTable[binopNodeType] = tokenId; + } + if(unopNodeType != TypeScript.NodeType.None) { + TypeScript.nodeTypeTable[unopNodeType] = text; + } + } + } + setTokenInfo(TokenID.Any, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "any", TypeScript.ErrorRecoverySet.PrimType); + setTokenInfo(TokenID.Bool, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "bool", TypeScript.ErrorRecoverySet.PrimType); + setTokenInfo(TokenID.Break, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "break", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.Case, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "case", TypeScript.ErrorRecoverySet.SCase); + setTokenInfo(TokenID.Catch, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "catch", TypeScript.ErrorRecoverySet.Catch); + setTokenInfo(TokenID.Class, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "class", TypeScript.ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.Const, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "const", TypeScript.ErrorRecoverySet.Var); + setTokenInfo(TokenID.Continue, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "continue", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.Debugger, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.Debugger, "debugger", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.Default, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "default", TypeScript.ErrorRecoverySet.SCase); + setTokenInfo(TokenID.Delete, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.Delete, "delete", TypeScript.ErrorRecoverySet.Prefix); + setTokenInfo(TokenID.Do, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "do", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.Else, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "else", TypeScript.ErrorRecoverySet.Else); + setTokenInfo(TokenID.Enum, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "enum", TypeScript.ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.Export, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "export", TypeScript.ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.Extends, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "extends", TypeScript.ErrorRecoverySet.None); + setTokenInfo(TokenID.Declare, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "declare", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.False, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "false", TypeScript.ErrorRecoverySet.RLit); + setTokenInfo(TokenID.Finally, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "finally", TypeScript.ErrorRecoverySet.Catch); + setTokenInfo(TokenID.For, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "for", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.Function, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "function", TypeScript.ErrorRecoverySet.Func); + setTokenInfo(TokenID.Constructor, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "constructor", TypeScript.ErrorRecoverySet.Func); + setTokenInfo(TokenID.Get, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "get", TypeScript.ErrorRecoverySet.Func); + setTokenInfo(TokenID.Set, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "set", TypeScript.ErrorRecoverySet.Func); + setTokenInfo(TokenID.If, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "if", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.Implements, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "implements", TypeScript.ErrorRecoverySet.None); + setTokenInfo(TokenID.Import, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "import", TypeScript.ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.In, Reservation.TypeScriptAndJS, OperatorPrecedence.Relational, TypeScript.NodeType.In, OperatorPrecedence.None, TypeScript.NodeType.None, "in", TypeScript.ErrorRecoverySet.None); + setTokenInfo(TokenID.InstanceOf, Reservation.TypeScriptAndJS, OperatorPrecedence.Relational, TypeScript.NodeType.InstOf, OperatorPrecedence.None, TypeScript.NodeType.None, "instanceof", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.Interface, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "interface", TypeScript.ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.Let, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "let", TypeScript.ErrorRecoverySet.None); + setTokenInfo(TokenID.Module, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "module", TypeScript.ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.New, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "new", TypeScript.ErrorRecoverySet.PreOp); + setTokenInfo(TokenID.Number, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "number", TypeScript.ErrorRecoverySet.PrimType); + setTokenInfo(TokenID.Null, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "null", TypeScript.ErrorRecoverySet.RLit); + setTokenInfo(TokenID.Package, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "package", TypeScript.ErrorRecoverySet.None); + setTokenInfo(TokenID.Private, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "private", TypeScript.ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.Protected, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "protected", TypeScript.ErrorRecoverySet.None); + setTokenInfo(TokenID.Public, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "public", TypeScript.ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.Return, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "return", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.Static, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "static", TypeScript.ErrorRecoverySet.None); + setTokenInfo(TokenID.String, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "string", TypeScript.ErrorRecoverySet.PrimType); + setTokenInfo(TokenID.Super, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "super", TypeScript.ErrorRecoverySet.RLit); + setTokenInfo(TokenID.Switch, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "switch", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.This, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "this", TypeScript.ErrorRecoverySet.RLit); + setTokenInfo(TokenID.Throw, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "throw", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.True, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "true", TypeScript.ErrorRecoverySet.RLit); + setTokenInfo(TokenID.Try, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "try", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.TypeOf, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.Typeof, "typeof", TypeScript.ErrorRecoverySet.Prefix); + setTokenInfo(TokenID.Var, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "var", TypeScript.ErrorRecoverySet.Var); + setTokenInfo(TokenID.Void, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.Void, "void", TypeScript.ErrorRecoverySet.Prefix); + setTokenInfo(TokenID.With, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.With, "with", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.While, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "while", TypeScript.ErrorRecoverySet.While); + setTokenInfo(TokenID.Yield, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "yield", TypeScript.ErrorRecoverySet.None); + setTokenInfo(TokenID.Identifier, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "identifier", TypeScript.ErrorRecoverySet.ID); + setTokenInfo(TokenID.NumberLiteral, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "numberLiteral", TypeScript.ErrorRecoverySet.Literal); + setTokenInfo(TokenID.RegularExpressionLiteral, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "regex", TypeScript.ErrorRecoverySet.RegExp); + setTokenInfo(TokenID.StringLiteral, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "qstring", TypeScript.ErrorRecoverySet.Literal); + setTokenInfo(TokenID.Semicolon, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, ";", TypeScript.ErrorRecoverySet.SColon); + setTokenInfo(TokenID.CloseParen, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, ")", TypeScript.ErrorRecoverySet.RParen); + setTokenInfo(TokenID.CloseBracket, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "]", TypeScript.ErrorRecoverySet.RBrack); + setTokenInfo(TokenID.OpenBrace, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "{", TypeScript.ErrorRecoverySet.LCurly); + setTokenInfo(TokenID.CloseBrace, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "}", TypeScript.ErrorRecoverySet.RCurly); + setTokenInfo(TokenID.DotDotDot, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "...", TypeScript.ErrorRecoverySet.None); + setTokenInfo(TokenID.Comma, Reservation.None, OperatorPrecedence.Comma, TypeScript.NodeType.Comma, OperatorPrecedence.None, TypeScript.NodeType.None, ",", TypeScript.ErrorRecoverySet.Comma); + setTokenInfo(TokenID.Equals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.Asg, OperatorPrecedence.None, TypeScript.NodeType.None, "=", TypeScript.ErrorRecoverySet.Asg); + setTokenInfo(TokenID.PlusEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgAdd, OperatorPrecedence.None, TypeScript.NodeType.None, "+=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.MinusEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgSub, OperatorPrecedence.None, TypeScript.NodeType.None, "-=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.AsteriskEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgMul, OperatorPrecedence.None, TypeScript.NodeType.None, "*=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.SlashEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgDiv, OperatorPrecedence.None, TypeScript.NodeType.None, "/=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.PercentEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgMod, OperatorPrecedence.None, TypeScript.NodeType.None, "%=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.AmpersandEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgAnd, OperatorPrecedence.None, TypeScript.NodeType.None, "&=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.CaretEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgXor, OperatorPrecedence.None, TypeScript.NodeType.None, "^=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.BarEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgOr, OperatorPrecedence.None, TypeScript.NodeType.None, "|=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.LessThanLessThanEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgLsh, OperatorPrecedence.None, TypeScript.NodeType.None, "<<=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.GreaterThanGreaterThanEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgRsh, OperatorPrecedence.None, TypeScript.NodeType.None, ">>=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.GreaterThanGreaterThanGreaterThanEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgRs2, OperatorPrecedence.None, TypeScript.NodeType.None, ">>>=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.Question, Reservation.None, OperatorPrecedence.Conditional, TypeScript.NodeType.ConditionalExpression, OperatorPrecedence.None, TypeScript.NodeType.None, "?", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.Colon, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, ":", TypeScript.ErrorRecoverySet.Colon); + setTokenInfo(TokenID.BarBar, Reservation.None, OperatorPrecedence.LogicalOr, TypeScript.NodeType.LogOr, OperatorPrecedence.None, TypeScript.NodeType.None, "||", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.AmpersandAmpersand, Reservation.None, OperatorPrecedence.LogicalAnd, TypeScript.NodeType.LogAnd, OperatorPrecedence.None, TypeScript.NodeType.None, "&&", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.Bar, Reservation.None, OperatorPrecedence.BitwiseOr, TypeScript.NodeType.Or, OperatorPrecedence.None, TypeScript.NodeType.None, "|", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.Caret, Reservation.None, OperatorPrecedence.BitwiseExclusiveOr, TypeScript.NodeType.Xor, OperatorPrecedence.None, TypeScript.NodeType.None, "^", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.And, Reservation.None, OperatorPrecedence.BitwiseAnd, TypeScript.NodeType.And, OperatorPrecedence.None, TypeScript.NodeType.None, "&", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.EqualsEquals, Reservation.None, OperatorPrecedence.Equality, TypeScript.NodeType.Eq, OperatorPrecedence.None, TypeScript.NodeType.None, "==", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.ExclamationEquals, Reservation.None, OperatorPrecedence.Equality, TypeScript.NodeType.Ne, OperatorPrecedence.None, TypeScript.NodeType.None, "!=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.EqualsEqualsEquals, Reservation.None, OperatorPrecedence.Equality, TypeScript.NodeType.Eqv, OperatorPrecedence.None, TypeScript.NodeType.None, "===", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.ExclamationEqualsEquals, Reservation.None, OperatorPrecedence.Equality, TypeScript.NodeType.NEqv, OperatorPrecedence.None, TypeScript.NodeType.None, "!==", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.LessThan, Reservation.None, OperatorPrecedence.Relational, TypeScript.NodeType.Lt, OperatorPrecedence.None, TypeScript.NodeType.None, "<", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.LessThanEquals, Reservation.None, OperatorPrecedence.Relational, TypeScript.NodeType.Le, OperatorPrecedence.None, TypeScript.NodeType.None, "<=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.GreaterThan, Reservation.None, OperatorPrecedence.Relational, TypeScript.NodeType.Gt, OperatorPrecedence.None, TypeScript.NodeType.None, ">", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.GreaterThanEquals, Reservation.None, OperatorPrecedence.Relational, TypeScript.NodeType.Ge, OperatorPrecedence.None, TypeScript.NodeType.None, ">=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.LessThanLessThan, Reservation.None, OperatorPrecedence.Shift, TypeScript.NodeType.Lsh, OperatorPrecedence.None, TypeScript.NodeType.None, "<<", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.GreaterThanGreaterThan, Reservation.None, OperatorPrecedence.Shift, TypeScript.NodeType.Rsh, OperatorPrecedence.None, TypeScript.NodeType.None, ">>", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.GreaterThanGreaterThanGreaterThan, Reservation.None, OperatorPrecedence.Shift, TypeScript.NodeType.Rs2, OperatorPrecedence.None, TypeScript.NodeType.None, ">>>", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.Plus, Reservation.None, OperatorPrecedence.Additive, TypeScript.NodeType.Add, OperatorPrecedence.Unary, TypeScript.NodeType.Pos, "+", TypeScript.ErrorRecoverySet.AddOp); + setTokenInfo(TokenID.Minus, Reservation.None, OperatorPrecedence.Additive, TypeScript.NodeType.Sub, OperatorPrecedence.Unary, TypeScript.NodeType.Neg, "-", TypeScript.ErrorRecoverySet.AddOp); + setTokenInfo(TokenID.Asterisk, Reservation.None, OperatorPrecedence.Multiplicative, TypeScript.NodeType.Mul, OperatorPrecedence.None, TypeScript.NodeType.None, "*", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.Slash, Reservation.None, OperatorPrecedence.Multiplicative, TypeScript.NodeType.Div, OperatorPrecedence.None, TypeScript.NodeType.None, "/", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.Percent, Reservation.None, OperatorPrecedence.Multiplicative, TypeScript.NodeType.Mod, OperatorPrecedence.None, TypeScript.NodeType.None, "%", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.Tilde, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.Not, "~", TypeScript.ErrorRecoverySet.PreOp); + setTokenInfo(TokenID.Exclamation, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.LogNot, "!", TypeScript.ErrorRecoverySet.PreOp); + setTokenInfo(TokenID.PlusPlus, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.IncPre, "++", TypeScript.ErrorRecoverySet.PreOp); + setTokenInfo(TokenID.MinusMinus, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.DecPre, "--", TypeScript.ErrorRecoverySet.PreOp); + setTokenInfo(TokenID.OpenParen, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "(", TypeScript.ErrorRecoverySet.LParen); + setTokenInfo(TokenID.OpenBracket, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "[", TypeScript.ErrorRecoverySet.LBrack); + setTokenInfo(TokenID.Dot, Reservation.None, OperatorPrecedence.Unary, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, ".", TypeScript.ErrorRecoverySet.Dot); + setTokenInfo(TokenID.EndOfFile, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "", TypeScript.ErrorRecoverySet.EOF); + setTokenInfo(TokenID.EqualsGreaterThan, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "=>", TypeScript.ErrorRecoverySet.None); + function lookupToken(tokenId) { + return TypeScript.tokenTable[tokenId]; + } + TypeScript.lookupToken = lookupToken; + (function (TokenClass) { + TokenClass._map = []; + TokenClass._map[0] = "Punctuation"; + TokenClass.Punctuation = 0; + TokenClass._map[1] = "Keyword"; + TokenClass.Keyword = 1; + TokenClass._map[2] = "Operator"; + TokenClass.Operator = 2; + TokenClass._map[3] = "Comment"; + TokenClass.Comment = 3; + TokenClass._map[4] = "Whitespace"; + TokenClass.Whitespace = 4; + TokenClass._map[5] = "Identifier"; + TokenClass.Identifier = 5; + TokenClass._map[6] = "NumberLiteral"; + TokenClass.NumberLiteral = 6; + TokenClass._map[7] = "StringLiteral"; + TokenClass.StringLiteral = 7; + TokenClass._map[8] = "RegExpLiteral"; + TokenClass.RegExpLiteral = 8; + })(TypeScript.TokenClass || (TypeScript.TokenClass = {})); + var TokenClass = TypeScript.TokenClass; + var SavedToken = (function () { + function SavedToken(tok, minChar, limChar) { + this.tok = tok; + this.minChar = minChar; + this.limChar = limChar; + } + return SavedToken; + })(); + TypeScript.SavedToken = SavedToken; + var Token = (function () { + function Token(tokenId) { + this.tokenId = tokenId; + } + Token.prototype.toString = function () { + return "token: " + this.tokenId + " " + this.getText() + " (" + (TokenID)._map[this.tokenId] + ")"; + }; + Token.prototype.print = function (line, outfile) { + outfile.WriteLine(this.toString() + ",on line" + line); + }; + Token.prototype.getText = function () { + return TypeScript.tokenTable[this.tokenId].text; + }; + Token.prototype.classification = function () { + if(this.tokenId <= TokenID.LimKeyword) { + return TokenClass.Keyword; + } else { + var tokenInfo = lookupToken(this.tokenId); + if(tokenInfo != undefined) { + if((tokenInfo.unopNodeType != TypeScript.NodeType.None) || (tokenInfo.binopNodeType != TypeScript.NodeType.None)) { + return TokenClass.Operator; + } + } + } + return TokenClass.Punctuation; + }; + return Token; + })(); + TypeScript.Token = Token; + var NumberLiteralToken = (function (_super) { + __extends(NumberLiteralToken, _super); + function NumberLiteralToken(value, hasEmptyFraction) { + _super.call(this, TokenID.NumberLiteral); + this.value = value; + this.hasEmptyFraction = hasEmptyFraction; + } + NumberLiteralToken.prototype.getText = function () { + return this.hasEmptyFraction ? this.value.toString() + ".0" : this.value.toString(); + }; + NumberLiteralToken.prototype.classification = function () { + return TokenClass.NumberLiteral; + }; + return NumberLiteralToken; + })(Token); + TypeScript.NumberLiteralToken = NumberLiteralToken; + var StringLiteralToken = (function (_super) { + __extends(StringLiteralToken, _super); + function StringLiteralToken(value) { + _super.call(this, TokenID.StringLiteral); + this.value = value; + } + StringLiteralToken.prototype.getText = function () { + return this.value; + }; + StringLiteralToken.prototype.classification = function () { + return TokenClass.StringLiteral; + }; + return StringLiteralToken; + })(Token); + TypeScript.StringLiteralToken = StringLiteralToken; + var IdentifierToken = (function (_super) { + __extends(IdentifierToken, _super); + function IdentifierToken(value, hasEscapeSequence) { + _super.call(this, TokenID.Identifier); + this.value = value; + this.hasEscapeSequence = hasEscapeSequence; + } + IdentifierToken.prototype.getText = function () { + return this.value; + }; + IdentifierToken.prototype.classification = function () { + return TokenClass.Identifier; + }; + return IdentifierToken; + })(Token); + TypeScript.IdentifierToken = IdentifierToken; + var WhitespaceToken = (function (_super) { + __extends(WhitespaceToken, _super); + function WhitespaceToken(tokenId, value) { + _super.call(this, tokenId); + this.value = value; + } + WhitespaceToken.prototype.getText = function () { + return this.value; + }; + WhitespaceToken.prototype.classification = function () { + return TokenClass.Whitespace; + }; + return WhitespaceToken; + })(Token); + TypeScript.WhitespaceToken = WhitespaceToken; + var CommentToken = (function (_super) { + __extends(CommentToken, _super); + function CommentToken(tokenID, value, isBlock, startPos, line, endsLine) { + _super.call(this, tokenID); + this.value = value; + this.isBlock = isBlock; + this.startPos = startPos; + this.line = line; + this.endsLine = endsLine; + } + CommentToken.prototype.getText = function () { + return this.value; + }; + CommentToken.prototype.classification = function () { + return TokenClass.Comment; + }; + return CommentToken; + })(Token); + TypeScript.CommentToken = CommentToken; + var RegularExpressionLiteralToken = (function (_super) { + __extends(RegularExpressionLiteralToken, _super); + function RegularExpressionLiteralToken(regex) { + _super.call(this, TokenID.RegularExpressionLiteral); + this.regex = regex; + } + RegularExpressionLiteralToken.prototype.getText = function () { + return this.regex.toString(); + }; + RegularExpressionLiteralToken.prototype.classification = function () { + return TokenClass.RegExpLiteral; + }; + return RegularExpressionLiteralToken; + })(Token); + TypeScript.RegularExpressionLiteralToken = RegularExpressionLiteralToken; + TypeScript.staticTokens = new Array(); + function initializeStaticTokens() { + for(var i = 0; i <= TokenID.LimFixed; i++) { + TypeScript.staticTokens[i] = new Token(i); + } + } + TypeScript.initializeStaticTokens = initializeStaticTokens; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ArrayCache = (function () { + function ArrayCache() { + this.arrayBase = null; + } + ArrayCache.prototype.specialize = function (arrInstType, checker) { + if(this.arrayBase == null) { + this.arrayBase = arrInstType.specializeType(checker.wildElm.type, this.arrayType.elementType, checker, true); + } + return this.arrayBase; + }; + return ArrayCache; + })(); + TypeScript.ArrayCache = ArrayCache; + var TypeComparisonInfo = (function () { + function TypeComparisonInfo() { + this.onlyCaptureFirstError = false; + this.flags = TypeScript.TypeRelationshipFlags.SuccessfulComparison; + this.message = ""; + } + TypeComparisonInfo.prototype.addMessageToFront = function (message) { + if(!this.onlyCaptureFirstError) { + this.message = this.message ? message + ":\n\t" + this.message : message; + } else { + this.setMessage(message); + } + }; + TypeComparisonInfo.prototype.setMessage = function (message) { + this.message = message; + }; + return TypeComparisonInfo; + })(); + TypeScript.TypeComparisonInfo = TypeComparisonInfo; + (function (TypeCheckCollectionMode) { + TypeCheckCollectionMode._map = []; + TypeCheckCollectionMode._map[0] = "Resident"; + TypeCheckCollectionMode.Resident = 0; + TypeCheckCollectionMode._map[1] = "Transient"; + TypeCheckCollectionMode.Transient = 1; + })(TypeScript.TypeCheckCollectionMode || (TypeScript.TypeCheckCollectionMode = {})); + var TypeCheckCollectionMode = TypeScript.TypeCheckCollectionMode; + var PersistentGlobalTypeState = (function () { + function PersistentGlobalTypeState(errorReporter) { + this.errorReporter = errorReporter; + this.importedGlobalsTable = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + this.importedGlobalsTypeTable = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + this.globals = null; + this.globalTypes = null; + this.ambientGlobals = null; + this.ambientGlobalTypes = null; + this.residentGlobalValues = new TypeScript.StringHashTable(); + this.residentGlobalTypes = new TypeScript.StringHashTable(); + this.residentGlobalAmbientValues = new TypeScript.StringHashTable(); + this.residentGlobalAmbientTypes = new TypeScript.StringHashTable(); + this.residentTypeCheck = true; + this.mod = null; + this.gloMod = null; + this.wildElm = null; + this.importedGlobals = new TypeScript.SymbolScopeBuilder(null, this.importedGlobalsTable, null, this.importedGlobalsTypeTable, null, null); + this.dualGlobalValues = new TypeScript.DualStringHashTable(this.residentGlobalValues, new TypeScript.StringHashTable()); + this.dualGlobalTypes = new TypeScript.DualStringHashTable(this.residentGlobalTypes, new TypeScript.StringHashTable()); + this.dualAmbientGlobalValues = new TypeScript.DualStringHashTable(this.residentGlobalAmbientValues, new TypeScript.StringHashTable()); + this.dualAmbientGlobalTypes = new TypeScript.DualStringHashTable(this.residentGlobalAmbientTypes, new TypeScript.StringHashTable()); + var dualGlobalScopedMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(this.dualGlobalValues, new TypeScript.StringHashTable())); + var dualGlobalScopedAmbientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(this.dualAmbientGlobalValues, new TypeScript.StringHashTable())); + var dualGlobalScopedEnclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(this.dualGlobalTypes, new TypeScript.StringHashTable())); + var dualGlobalScopedAmbientEnclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(this.dualAmbientGlobalTypes, new TypeScript.StringHashTable())); + this.globalScope = new TypeScript.SymbolScopeBuilder(dualGlobalScopedMembers, dualGlobalScopedAmbientMembers, dualGlobalScopedEnclosedTypes, dualGlobalScopedAmbientEnclosedTypes, this.importedGlobals, null); + this.voidType = this.enterPrimitive(TypeScript.Primitive.Void, "void"); + this.booleanType = this.enterPrimitive(TypeScript.Primitive.Boolean, "bool"); + this.doubleType = this.enterPrimitive(TypeScript.Primitive.Double, "number"); + this.importedGlobals.ambientEnclosedTypes.addPublicMember("number", this.doubleType.symbol); + this.stringType = this.enterPrimitive(TypeScript.Primitive.String, "string"); + this.anyType = this.enterPrimitive(TypeScript.Primitive.Any, "any"); + this.nullType = this.enterPrimitive(TypeScript.Primitive.Null, "null"); + this.undefinedType = this.enterPrimitive(TypeScript.Primitive.Undefined, "undefined"); + this.setCollectionMode(TypeCheckCollectionMode.Resident); + this.wildElm = new TypeScript.TypeSymbol("_element", -1, 0, -1, new TypeScript.Type()); + this.importedGlobalsTypeTable.addPublicMember(this.wildElm.name, this.wildElm); + this.mod = new TypeScript.ModuleType(dualGlobalScopedEnclosedTypes, dualGlobalScopedAmbientEnclosedTypes); + this.mod.members = dualGlobalScopedMembers; + this.mod.ambientMembers = dualGlobalScopedAmbientMembers; + this.mod.containedScope = this.globalScope; + this.gloMod = new TypeScript.TypeSymbol(TypeScript.globalId, -1, 0, -1, this.mod); + this.mod.members.addPublicMember(this.gloMod.name, this.gloMod); + this.defineGlobalValue("undefined", this.undefinedType); + } + PersistentGlobalTypeState.prototype.enterPrimitive = function (flags, name) { + var primitive = new TypeScript.Type(); + primitive.primitiveTypeClass = flags; + var symbol = new TypeScript.TypeSymbol(name, -1, name.length, -1, primitive); + symbol.typeCheckStatus = TypeScript.TypeCheckStatus.Finished; + primitive.symbol = symbol; + this.importedGlobals.enter(null, null, symbol, this.errorReporter, true, true, true); + return primitive; + }; + PersistentGlobalTypeState.prototype.setCollectionMode = function (mode) { + this.residentTypeCheck = this.dualGlobalValues.insertPrimary = this.dualGlobalTypes.insertPrimary = this.dualAmbientGlobalValues.insertPrimary = this.dualAmbientGlobalTypes.insertPrimary = mode == TypeCheckCollectionMode.Resident; + }; + PersistentGlobalTypeState.prototype.refreshPersistentState = function () { + this.globals = new TypeScript.StringHashTable(); + this.globalTypes = new TypeScript.StringHashTable(); + this.ambientGlobals = new TypeScript.StringHashTable(); + this.ambientGlobalTypes = new TypeScript.StringHashTable(); + this.globalTypes.add(this.voidType.symbol.name, this.voidType.symbol); + this.globalTypes.add(this.booleanType.symbol.name, this.booleanType.symbol); + this.globalTypes.add(this.doubleType.symbol.name, this.doubleType.symbol); + this.globalTypes.add("number", this.doubleType.symbol); + this.globalTypes.add(this.stringType.symbol.name, this.stringType.symbol); + this.globalTypes.add(this.anyType.symbol.name, this.anyType.symbol); + this.globalTypes.add(this.nullType.symbol.name, this.nullType.symbol); + this.globalTypes.add(this.undefinedType.symbol.name, this.undefinedType.symbol); + this.dualGlobalValues.secondaryTable = this.globals; + this.dualGlobalTypes.secondaryTable = this.globalTypes; + this.dualAmbientGlobalValues.secondaryTable = this.ambientGlobals; + this.dualAmbientGlobalTypes.secondaryTable = this.ambientGlobalTypes; + }; + PersistentGlobalTypeState.prototype.defineGlobalValue = function (name, type) { + var valueLocation = new TypeScript.ValueLocation(); + valueLocation.typeLink = new TypeScript.TypeLink(); + var sym = new TypeScript.VariableSymbol(name, 0, -1, valueLocation); + sym.setType(type); + sym.typeCheckStatus = TypeScript.TypeCheckStatus.Finished; + sym.container = this.gloMod; + this.importedGlobalsTable.addPublicMember(name, sym); + }; + return PersistentGlobalTypeState; + })(); + TypeScript.PersistentGlobalTypeState = PersistentGlobalTypeState; + var ContextualTypeContext = (function () { + function ContextualTypeContext(contextualType, provisional, contextID) { + this.contextualType = contextualType; + this.provisional = provisional; + this.contextID = contextID; + this.targetSig = null; + this.targetThis = null; + this.targetAccessorType = null; + } + return ContextualTypeContext; + })(); + TypeScript.ContextualTypeContext = ContextualTypeContext; + var ContextualTypingContextStack = (function () { + function ContextualTypingContextStack(checker) { + this.checker = checker; + this.contextStack = []; + this.hadProvisionalErrors = false; + } + ContextualTypingContextStack.contextID = TypeScript.TypeCheckStatus.Finished + 1; + ContextualTypingContextStack.prototype.pushContextualType = function (type, provisional) { + this.contextStack.push(new ContextualTypeContext(type, provisional, ContextualTypingContextStack.contextID++)); + this.checker.errorReporter.pushToErrorSink = provisional; + }; + ContextualTypingContextStack.prototype.popContextualType = function () { + var tc = this.contextStack.pop(); + this.checker.errorReporter.pushToErrorSink = this.isProvisional(); + this.hadProvisionalErrors = this.hadProvisionalErrors || (tc.provisional && (this.checker.errorReporter.getCapturedErrors().length)); + this.checker.errorReporter.freeCapturedErrors(); + return tc; + }; + ContextualTypingContextStack.prototype.getContextualType = function () { + return (!this.contextStack.length ? null : this.contextStack[this.contextStack.length - 1]); + }; + ContextualTypingContextStack.prototype.getContextID = function () { + return (!this.contextStack.length ? TypeScript.TypeCheckStatus.Finished : this.contextStack[this.contextStack.length - 1].contextID); + }; + ContextualTypingContextStack.prototype.isProvisional = function () { + return (!this.contextStack.length ? false : this.contextStack[this.contextStack.length - 1].provisional); + }; + return ContextualTypingContextStack; + })(); + TypeScript.ContextualTypingContextStack = ContextualTypingContextStack; + var TypeChecker = (function () { + function TypeChecker(persistentState) { + this.persistentState = persistentState; + this.errorReporter = null; + this.checkControlFlow = false; + this.printControlFlowGraph = false; + this.checkControlFlowUseDef = false; + this.styleSettings = null; + this.units = null; + this.anon = "_anonymous"; + this.locationInfo = null; + this.typeFlow = null; + this.currentCompareA = null; + this.currentCompareB = null; + this.currentModDecl = null; + this.inBind = false; + this.inWith = false; + this.errorsOnWith = true; + this.currentContextualTypeContext = null; + this.resolvingBases = false; + this.canCallDefinitionSignature = false; + this.assignableCache = { + }; + this.subtypeCache = { + }; + this.identicalCache = { + }; + this.provisionalStartedTypecheckObjects = []; + this.mustCaptureGlobalThis = false; + this.voidType = this.persistentState.voidType; + this.booleanType = this.persistentState.booleanType; + this.numberType = this.persistentState.doubleType; + this.stringType = this.persistentState.stringType; + this.anyType = this.persistentState.anyType; + this.nullType = this.persistentState.nullType; + this.undefinedType = this.persistentState.undefinedType; + this.globals = this.persistentState.dualGlobalValues; + this.globalTypes = this.persistentState.dualGlobalTypes; + this.ambientGlobals = this.persistentState.dualAmbientGlobalValues; + this.ambientGlobalTypes = this.persistentState.dualAmbientGlobalTypes; + this.gloModType = this.persistentState.mod; + this.gloMod = this.persistentState.gloMod; + this.wildElm = this.persistentState.wildElm; + this.globalScope = this.persistentState.globalScope; + this.typingContextStack = new ContextualTypingContextStack(this); + } + TypeChecker.prototype.setStyleOptions = function (style) { + this.styleSettings = style; + }; + TypeChecker.prototype.setContextualType = function (type, provisional) { + this.typingContextStack.pushContextualType(type, provisional); + this.currentContextualTypeContext = this.typingContextStack.getContextualType(); + }; + TypeChecker.prototype.unsetContextualType = function () { + var lastTC = this.typingContextStack.popContextualType(); + this.currentContextualTypeContext = this.typingContextStack.getContextualType(); + return lastTC; + }; + TypeChecker.prototype.hadProvisionalErrors = function () { + return this.typingContextStack.hadProvisionalErrors; + }; + TypeChecker.prototype.resetProvisionalErrors = function () { + if(!this.typingContextStack.getContextualType()) { + this.typingContextStack.hadProvisionalErrors = false; + } + }; + TypeChecker.prototype.typeCheckWithContextualType = function (contextType, provisional, condition, ast) { + if(condition) { + this.setContextualType(contextType, this.typingContextStack.isProvisional() || provisional); + } + this.typeFlow.typeCheck(ast); + if(condition) { + this.unsetContextualType(); + } + }; + TypeChecker.prototype.resetTargetType = function () { + this.currentContextualTypeContext = this.typingContextStack.getContextualType(); + }; + TypeChecker.prototype.killCurrentContextualType = function () { + this.currentContextualTypeContext = null; + this.errorReporter.pushToErrorSink = false; + }; + TypeChecker.prototype.hasTargetType = function () { + return this.currentContextualTypeContext && this.currentContextualTypeContext.contextualType; + }; + TypeChecker.prototype.getTargetTypeContext = function () { + return this.currentContextualTypeContext; + }; + TypeChecker.prototype.inProvisionalTypecheckMode = function () { + return this.typingContextStack.isProvisional(); + }; + TypeChecker.prototype.getTypeCheckFinishedStatus = function () { + if(this.inProvisionalTypecheckMode()) { + return this.typingContextStack.getContextID(); + } + return TypeScript.TypeCheckStatus.Finished; + }; + TypeChecker.prototype.typeStatusIsFinished = function (status) { + return status == TypeScript.TypeCheckStatus.Finished || (this.inProvisionalTypecheckMode() && status == this.typingContextStack.getContextID()); + }; + TypeChecker.prototype.addStartedPTO = function (pto) { + if(this.inProvisionalTypecheckMode()) { + this.provisionalStartedTypecheckObjects[this.provisionalStartedTypecheckObjects.length] = pto; + } + }; + TypeChecker.prototype.cleanStartedPTO = function () { + for(var i = 0; i < this.provisionalStartedTypecheckObjects.length; i++) { + if(this.provisionalStartedTypecheckObjects[i].typeCheckStatus >= this.typingContextStack.getContextID()) { + this.provisionalStartedTypecheckObjects[i].typeCheckStatus = TypeScript.TypeCheckStatus.NotStarted; + } + } + this.provisionalStartedTypecheckObjects = []; + }; + TypeChecker.prototype.collectTypes = function (ast) { + if(ast.nodeType == TypeScript.NodeType.Script) { + var script = ast; + this.locationInfo = script.locationInfo; + } + var globalChain = new TypeScript.ScopeChain(this.gloMod, null, this.globalScope); + var context = new TypeScript.TypeCollectionContext(globalChain, this); + TypeScript.getAstWalkerFactory().walk(ast, TypeScript.preCollectTypes, TypeScript.postCollectTypes, null, context); + }; + TypeChecker.prototype.makeArrayType = function (type) { + if(type.arrayCache == null) { + type.arrayCache = new ArrayCache(); + type.arrayCache.arrayType = new TypeScript.Type(); + type.arrayCache.arrayType.elementType = type; + type.arrayCache.arrayType.symbol = type.symbol; + } + return type.arrayCache.arrayType; + }; + TypeChecker.prototype.getParameterList = function (funcDecl, container) { + var args = funcDecl.arguments; + var parameterTable = null; + var parameterBuilder = null; + var len = args.members.length; + var nonOptionalParams = 0; + var result = []; + if(len > 0) { + parameterTable = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + parameterBuilder = new TypeScript.SymbolScopeBuilder(parameterTable, null, null, null, null, container); + for(var i = 0; i < len; i++) { + var parameter = args.members[i]; + var paramDef = new TypeScript.ValueLocation(); + var parameterSymbol = new TypeScript.ParameterSymbol(parameter.id.text, parameter.minChar, this.locationInfo.unitIndex, paramDef); + parameterSymbol.declAST = parameter; + parameterSymbol.funcDecl = funcDecl; + parameter.id.sym = parameterSymbol; + parameter.sym = parameterSymbol; + paramDef.symbol = parameterSymbol; + paramDef.typeLink = TypeScript.getTypeLink(parameter.typeExpr, this, false); + parameterBuilder.enter(null, parameter, parameterSymbol, this.errorReporter, true, false, false); + result[result.length] = parameterSymbol; + if(!parameter.isOptionalArg()) { + nonOptionalParams++; + } + } + } + return { + parameters: result, + nonOptionalParameterCount: nonOptionalParams + }; + }; + TypeChecker.prototype.createFunctionSignature = function (funcDecl, container, scope, overloadGroupSym, addToScope) { + var isExported = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Exported | TypeScript.FncFlags.ClassPropertyMethodExported) || container == this.gloMod; + var isStatic = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static); + var isPrivate = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Private); + var isDefinition = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Definition); + var isAmbient = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Ambient); + var isConstructor = funcDecl.isConstructMember() || funcDecl.isConstructor; + var isGlobal = container == this.gloMod; + var signature = new TypeScript.Signature(); + var isLambda = funcDecl.fncFlags & TypeScript.FncFlags.IsFunctionExpression; + if(funcDecl.returnTypeAnnotation || isDefinition) { + signature.returnType = TypeScript.getTypeLink(funcDecl.returnTypeAnnotation, this, false); + } else { + signature.returnType = new TypeScript.TypeLink(); + signature.returnType.type = this.anyType; + } + signature.hasVariableArgList = funcDecl.variableArgList; + var sigData = this.getParameterList(funcDecl, container); + signature.parameters = sigData.parameters; + signature.nonOptionalParameterCount = sigData.nonOptionalParameterCount; + funcDecl.signature = signature; + signature.declAST = funcDecl; + var useOverloadGroupSym = overloadGroupSym && overloadGroupSym.getType() && !overloadGroupSym.isAccessor() && (funcDecl.isSignature() || (isAmbient == TypeScript.hasFlag(overloadGroupSym.flags, TypeScript.SymbolFlags.Ambient))); + if(useOverloadGroupSym && isPrivate != TypeScript.hasFlag(overloadGroupSym.flags, TypeScript.SymbolFlags.Private)) { + this.errorReporter.simpleError(funcDecl, "Public/Private visibility of overloads does not agree"); + } + var groupType = useOverloadGroupSym ? overloadGroupSym.getType() : new TypeScript.Type(); + if(isConstructor) { + if(groupType.construct == null) { + groupType.construct = new TypeScript.SignatureGroup(); + } + groupType.construct.addSignature(signature); + groupType.construct.hasImplementation = !(funcDecl.isSignature()); + if(groupType.construct.hasImplementation) { + groupType.setHasImplementation(); + } + } else { + if(funcDecl.isIndexerMember()) { + if(groupType.index == null) { + groupType.index = new TypeScript.SignatureGroup(); + groupType.index.flags |= TypeScript.SignatureFlags.IsIndexer; + } + groupType.index.addSignature(signature); + groupType.index.hasImplementation = !(funcDecl.isSignature()); + if(groupType.index.hasImplementation) { + groupType.setHasImplementation(); + } + } else { + if(groupType.call == null) { + groupType.call = new TypeScript.SignatureGroup(); + } + groupType.call.addSignature(signature); + groupType.call.hasImplementation = !(funcDecl.isSignature()); + if(groupType.call.hasImplementation) { + groupType.setHasImplementation(); + } + } + } + var instanceType = groupType.instanceType; + var funcName = null; + var usedHint = false; + if(funcDecl.name && !funcDecl.name.isMissing()) { + funcName = funcDecl.name.text; + } else { + if(funcDecl.hint) { + funcName = funcDecl.hint; + usedHint = true; + } + } + if(groupType.symbol == null) { + groupType.symbol = new TypeScript.TypeSymbol(funcName ? funcName : this.anon, funcDecl.minChar, funcDecl.limChar - funcDecl.minChar, this.locationInfo.unitIndex, groupType); + if(!useOverloadGroupSym) { + groupType.symbol.declAST = funcDecl; + } + } + if(isStatic) { + groupType.symbol.flags |= TypeScript.SymbolFlags.Static; + } + if(isAmbient) { + groupType.symbol.flags |= TypeScript.SymbolFlags.Ambient; + } + if(isPrivate) { + groupType.symbol.flags |= TypeScript.SymbolFlags.Private; + } + groupType.symbol.isMethod = funcDecl.isMethod(); + if(groupType.symbol.isMethod) { + groupType.symbol.flags |= TypeScript.SymbolFlags.Property; + } + funcDecl.type = groupType; + if(!isConstructor) { + if(funcName && !isLambda && !funcDecl.isAccessor() && !usedHint) { + if(addToScope) { + if(funcDecl.isMethod() && isStatic) { + if(!(container).type.members.publicMembers.add(funcName, groupType.symbol)) { + this.errorReporter.duplicateIdentifier(funcDecl, funcName); + } + groupType.symbol.container = container; + } else { + if(overloadGroupSym == null || (overloadGroupSym.declAST && !(overloadGroupSym.declAST).isOverload && (container.isType()))) { + scope.enter(container, funcDecl, groupType.symbol, this.errorReporter, !isPrivate && (isExported || isStatic || isGlobal), false, isAmbient); + } + } + } else { + if(!funcDecl.isSpecialFn()) { + groupType.symbol.container = container; + } + } + } else { + if(!funcDecl.isSpecialFn()) { + groupType.symbol.container = container; + } + } + } + if(useOverloadGroupSym) { + var overloadGroupType = overloadGroupSym ? overloadGroupSym.getType() : null; + var classType = groupType; + if(classType != overloadGroupType) { + if(classType.construct == null) { + if(overloadGroupType && overloadGroupType.construct) { + classType.construct = overloadGroupType.construct; + } else { + classType.construct = new TypeScript.SignatureGroup(); + } + } else { + if(overloadGroupType) { + if(overloadGroupType.construct) { + classType.construct.signatures.concat(overloadGroupType.construct.signatures); + } + } + } + if(overloadGroupType) { + if(classType.call == null) { + classType.call = overloadGroupType.call; + } else { + if(overloadGroupType.call) { + classType.call.signatures.concat(overloadGroupType.call.signatures); + } + } + if(!isStatic) { + if(classType.instanceType == null) { + classType.instanceType = overloadGroupType.instanceType; + } + var instanceType = classType.instanceType; + if(instanceType) { + if(instanceType.call == null) { + instanceType.call = overloadGroupType.call; + } else { + if(overloadGroupType.call) { + instanceType.call.signatures.concat(overloadGroupType.call.signatures); + } + } + } + } + if(classType.index == null) { + classType.index = overloadGroupType.index; + } else { + if(overloadGroupType.index) { + classType.index.signatures.concat(overloadGroupType.index.signatures); + } + } + } + } + } + return signature; + }; + TypeChecker.prototype.createAccessorSymbol = function (funcDecl, fgSym, enclosingClass, addToMembers, isClassProperty, scope, container) { + var accessorSym = null; + var sig = funcDecl.signature; + var nameText = funcDecl.name.text; + var isStatic = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static); + var isPrivate = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Private); + if(fgSym == null) { + var field = new TypeScript.ValueLocation(); + accessorSym = new TypeScript.FieldSymbol(nameText, funcDecl.minChar, this.locationInfo.unitIndex, false, field); + field.symbol = accessorSym; + accessorSym.declAST = funcDecl; + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { + if(accessorSym.getter) { + this.errorReporter.simpleError(funcDecl, "Redeclaration of property getter"); + } + accessorSym.getter = sig.declAST.type.symbol; + } else { + if(accessorSym.setter) { + this.errorReporter.simpleError(funcDecl, "Redeclaration of property setter"); + } + accessorSym.setter = sig.declAST.type.symbol; + } + field.typeLink = TypeScript.getTypeLink(null, this, false); + if(addToMembers) { + if(enclosingClass) { + if(!enclosingClass.members.publicMembers.add(nameText, accessorSym)) { + this.errorReporter.duplicateIdentifier(funcDecl, accessorSym.name); + } + accessorSym.container = enclosingClass.symbol; + } else { + this.errorReporter.simpleError(funcDecl, "Accessor property may not be added in this context"); + } + } else { + scope.enter(container, funcDecl, accessorSym, this.errorReporter, !isPrivate || isStatic, false, false); + } + if(isClassProperty) { + accessorSym.flags |= TypeScript.SymbolFlags.Property; + } + if(isStatic) { + accessorSym.flags |= TypeScript.SymbolFlags.Static; + } + if(isPrivate) { + accessorSym.flags |= TypeScript.SymbolFlags.Private; + } else { + accessorSym.flags |= TypeScript.SymbolFlags.Public; + } + } else { + accessorSym = (fgSym); + if(isPrivate != TypeScript.hasFlag(accessorSym.flags, TypeScript.SymbolFlags.Private)) { + this.errorReporter.simpleError(funcDecl, "Getter and setter accessors do not agree in visibility"); + } + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { + if(accessorSym.getter) { + this.errorReporter.simpleError(funcDecl, "Redeclaration of property getter"); + } + accessorSym.getter = funcDecl.type.symbol; + } else { + if(accessorSym.setter) { + this.errorReporter.simpleError(funcDecl, "Redeclaration of property setter"); + } + accessorSym.setter = funcDecl.type.symbol; + } + } + return accessorSym; + }; + TypeChecker.prototype.addBases = function (resultScope, type, baseContext) { + resultScope.addParentScope(new TypeScript.SymbolTableScope(type.members, type.ambientMembers, type.getAllEnclosedTypes(), type.getAllAmbientEnclosedTypes(), type.symbol)); + var i = 0; + var parent; + if(type.extendsList) { + for(var len = type.extendsList.length; i < len; i++) { + parent = type.extendsList[i]; + if(baseContext.baseId == parent.typeID) { + this.errorReporter.reportErrorFromSym(parent.symbol, "Type '" + baseContext.base + "' is recursively referenced as a base class of itself"); + parent.symbol.flags |= TypeScript.SymbolFlags.RecursivelyReferenced; + break; + } + this.addBases(resultScope, parent, baseContext); + } + } + }; + TypeChecker.prototype.scopeOf = function (type) { + var resultScope = new TypeScript.SymbolAggregateScope(type.symbol); + var baseContext = { + base: type.symbol && type.symbol.name ? type.symbol.name : "{}", + baseId: type.typeID + }; + this.addBases(resultScope, type, baseContext); + return resultScope; + }; + TypeChecker.prototype.lookupMemberTypeSymbol = function (containingType, name) { + var symbol = null; + if(containingType.containedScope) { + symbol = containingType.containedScope.find(name, false, true); + } else { + if(containingType.members) { + symbol = containingType.members.allMembers.lookup(name); + if(symbol == null && containingType.ambientMembers) { + symbol = containingType.ambientMembers.allMembers.lookup(name); + } + } + } + if(symbol == null) { + var typeMembers = containingType.getAllEnclosedTypes(); + var ambientTypeMembers = containingType.getAllAmbientEnclosedTypes(); + if(typeMembers) { + symbol = typeMembers.allMembers.lookup(name); + if(symbol == null && ambientTypeMembers) { + symbol = ambientTypeMembers.allMembers.lookup(name); + } + } + } + if(symbol && symbol.isType()) { + return symbol; + } else { + return null; + } + }; + TypeChecker.prototype.findSymbolForDynamicModule = function (idText, currentFileName, search) { + var originalIdText = idText; + var symbol = search(idText); + if(symbol == null) { + if(!symbol) { + idText = TypeScript.swapQuotes(originalIdText); + symbol = search(idText); + } + if(!symbol) { + idText = TypeScript.stripQuotes(originalIdText) + ".ts"; + symbol = search(idText); + } + if(!symbol) { + idText = TypeScript.stripQuotes(originalIdText) + ".str"; + symbol = search(idText); + } + if(!symbol) { + idText = TypeScript.stripQuotes(originalIdText) + ".d.ts"; + symbol = search(idText); + } + if(!symbol) { + idText = TypeScript.stripQuotes(originalIdText) + ".d.str"; + symbol = search(idText); + } + if(!symbol && !TypeScript.isRelative(originalIdText)) { + idText = originalIdText; + var strippedIdText = TypeScript.stripQuotes(idText); + var path = TypeScript.getRootFilePath(TypeScript.switchToForwardSlashes(currentFileName)); + while(symbol == null && path != "") { + idText = TypeScript.normalizePath(path + strippedIdText + ".ts"); + symbol = search(idText); + if(symbol == null) { + idText = TypeScript.changePathToSTR(idText); + symbol = search(idText); + } + if(symbol == null) { + idText = TypeScript.changePathToDTS(idText); + symbol = search(idText); + } + if(symbol == null) { + idText = TypeScript.changePathToDSTR(idText); + symbol = search(idText); + } + if(symbol == null) { + if(path === '/') { + path = ''; + } else { + path = TypeScript.normalizePath(path + ".."); + path = path && path != '/' ? path + '/' : path; + } + } + } + } + } + return symbol; + }; + TypeChecker.prototype.resolveTypeMember = function (scope, dotNode) { + var lhs = dotNode.operand1; + var rhs = dotNode.operand2; + var resultType = this.anyType; + var lhsType = this.anyType; + if(lhs && rhs && (rhs.nodeType == TypeScript.NodeType.Name)) { + if(lhs.nodeType == TypeScript.NodeType.Dot) { + lhsType = this.resolveTypeMember(scope, lhs); + } else { + if(lhs.nodeType == TypeScript.NodeType.Name) { + var identifier = lhs; + var symbol = scope.find(identifier.text, false, true); + if(symbol == null) { + this.errorReporter.unresolvedSymbol(identifier, identifier.actualText); + } else { + if(symbol.isType()) { + var typeSymbol = symbol; + if(typeSymbol.aliasLink && !typeSymbol.type && typeSymbol.aliasLink.alias.nodeType == TypeScript.NodeType.Name) { + var modPath = (typeSymbol.aliasLink.alias).text; + var modSym = this.findSymbolForDynamicModule(modPath, this.locationInfo.filename, function (id) { + return scope.find(id, false, true); + }); + if(modSym) { + typeSymbol.type = modSym.getType(); + } + } + if(TypeScript.optimizeModuleCodeGen && symbol) { + var symType = symbol.getType(); + if(symType && typeSymbol.aliasLink && typeSymbol.onlyReferencedAsTypeRef) { + var modDecl = symType.symbol.declAST; + if(modDecl && TypeScript.hasFlag(modDecl.modFlags, TypeScript.ModuleFlags.IsDynamic)) { + typeSymbol.onlyReferencedAsTypeRef = !this.resolvingBases; + } + } + } + if(!symbol.visible(scope, this)) { + this.errorReporter.simpleError(lhs, "The symbol '" + identifier.actualText + "' is not visible at this point"); + } + lhsType = symbol.getType(); + identifier.sym = symbol; + } else { + this.errorReporter.simpleError(lhs, "Expected type"); + } + } + } + } + if(!lhsType) { + lhsType = this.anyType; + } + if(lhsType != this.anyType) { + var rhsIdentifier = rhs; + var resultSymbol = this.lookupMemberTypeSymbol(lhsType, rhsIdentifier.text); + if(resultSymbol == null) { + resultType = this.anyType; + this.errorReporter.simpleError(dotNode, "Expected type"); + } else { + resultType = resultSymbol.getType(); + if(!resultSymbol.visible(scope, this)) { + this.errorReporter.simpleError(lhs, "The symbol '" + (rhs).actualText + "' is not visible at this point"); + } + } + rhsIdentifier.sym = resultType.symbol; + } + } + if(resultType.isClass()) { + resultType = resultType.instanceType; + } + return resultType; + }; + TypeChecker.prototype.resolveFuncDecl = function (funcDecl, scope, fgSym) { + var functionGroupSymbol = this.createFunctionSignature(funcDecl, scope.container, scope, fgSym, false).declAST.type.symbol; + var signatures; + if(funcDecl.isConstructMember()) { + signatures = functionGroupSymbol.type.construct.signatures; + } else { + if(funcDecl.isIndexerMember()) { + signatures = functionGroupSymbol.type.getInstanceType().index.signatures; + } else { + signatures = functionGroupSymbol.type.call.signatures; + } + } + var signature = signatures[signatures.length - 1]; + var len = signature.parameters.length; + for(var i = 0; i < len; i++) { + var paramSym = signature.parameters[i]; + this.resolveTypeLink(scope, paramSym.parameter.typeLink, true); + } + if(len && funcDecl.variableArgList) { + if(!signature.parameters[len - 1].parameter.typeLink.type.elementType) { + this.errorReporter.simpleErrorFromSym(signature.parameters[len - 1].parameter.symbol, "... parameter must have array type"); + signature.parameters[len - 1].parameter.typeLink.type = this.makeArrayType(signature.parameters[len - 1].parameter.typeLink.type); + } + } + this.resolveTypeLink(scope, signature.returnType, funcDecl.isSignature()); + return functionGroupSymbol; + }; + TypeChecker.prototype.resolveVarDecl = function (varDecl, scope) { + var field = new TypeScript.ValueLocation(); + var fieldSymbol = new TypeScript.FieldSymbol(varDecl.id.text, varDecl.minChar, this.locationInfo.unitIndex, (varDecl.varFlags & TypeScript.VarFlags.Readonly) == TypeScript.VarFlags.None, field); + fieldSymbol.transferVarFlags(varDecl.varFlags); + field.symbol = fieldSymbol; + fieldSymbol.declAST = varDecl; + field.typeLink = TypeScript.getTypeLink(varDecl.typeExpr, this, varDecl.init == null); + this.resolveTypeLink(scope, field.typeLink, true); + varDecl.sym = fieldSymbol; + varDecl.type = field.typeLink.type; + return fieldSymbol; + }; + TypeChecker.prototype.resolveTypeLink = function (scope, typeLink, supplyVar) { + var arrayCount = 0; + if(typeLink.type == null) { + var ast = typeLink.ast; + if(ast) { + while(typeLink.type == null) { + switch(ast.nodeType) { + case TypeScript.NodeType.Name: { + var identifier = ast; + var symbol = scope.find(identifier.text, false, true); + if(symbol == null) { + typeLink.type = this.anyType; + this.errorReporter.unresolvedSymbol(identifier, identifier.actualText); + } else { + if(symbol.isType()) { + if(!symbol.visible(scope, this)) { + this.errorReporter.simpleError(ast, "The symbol '" + identifier.actualText + "' is not visible at this point"); + } + identifier.sym = symbol; + typeLink.type = symbol.getType(); + if(typeLink.type) { + if(typeLink.type.isClass()) { + typeLink.type = typeLink.type.instanceType; + } + } else { + typeLink.type = this.anyType; + } + } else { + typeLink.type = this.anyType; + this.errorReporter.simpleError(ast, "Expected type"); + } + } + break; + + } + case TypeScript.NodeType.Dot: { + typeLink.type = this.resolveTypeMember(scope, ast); + break; + + } + case TypeScript.NodeType.TypeRef: { + var typeRef = ast; + arrayCount = typeRef.arrayCount; + ast = typeRef.term; + if(ast == null) { + typeLink.type = this.anyType; + } + break; + + } + case TypeScript.NodeType.InterfaceDeclaration: { + var interfaceDecl = ast; + var interfaceType = new TypeScript.Type(); + var interfaceSymbol = new TypeScript.TypeSymbol((interfaceDecl.name).text, ast.minChar, ast.limChar - ast.minChar, this.locationInfo.unitIndex, interfaceType); + interfaceType.symbol = interfaceSymbol; + interfaceType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + interfaceType.containedScope = new TypeScript.SymbolTableScope(interfaceType.members, null, null, null, interfaceSymbol); + interfaceType.containedScope.container = interfaceSymbol; + interfaceType.memberScope = interfaceType.containedScope; + var memberList = interfaceDecl.members; + var props = memberList.members; + var propsLen = props.length; + for(var j = 0; j < propsLen; j++) { + var propDecl = props[j]; + var propSym = null; + var addMember = true; + var id = null; + if(propDecl.nodeType == TypeScript.NodeType.FuncDecl) { + var funcDecl = propDecl; + id = funcDecl.name; + propSym = interfaceType.members.allMembers.lookup(funcDecl.getNameText()); + addMember = (propSym == null); + if(funcDecl.isSpecialFn()) { + addMember = false; + propSym = this.resolveFuncDecl(funcDecl, scope, interfaceSymbol); + } else { + propSym = this.resolveFuncDecl(funcDecl, scope, propSym); + } + funcDecl.type = (propSym).type; + } else { + id = (propDecl).id; + propSym = this.resolveVarDecl(propDecl, scope); + addMember = !id.isMissing(); + } + if(addMember) { + if(id && TypeScript.hasFlag(id.flags, TypeScript.ASTFlags.OptionalName)) { + propSym.flags |= TypeScript.SymbolFlags.Optional; + } + if(!interfaceType.members.allMembers.add(propSym.name, propSym)) { + this.errorReporter.duplicateIdentifier(ast, propSym.name); + } + } + } + ast.type = interfaceType; + typeLink.type = interfaceType; + break; + + } + case TypeScript.NodeType.FuncDecl: { + var tsym = this.resolveFuncDecl(ast, scope, null); + typeLink.type = tsym.type; + break; + + } + default: { + typeLink.type = this.anyType; + this.errorReporter.simpleError(ast, "Expected type"); + break; + + } + } + } + } + for(var count = arrayCount; count > 0; count--) { + typeLink.type = this.makeArrayType(typeLink.type); + } + if(supplyVar && (typeLink.type == null)) { + typeLink.type = this.anyType; + } + if(typeLink.ast) { + typeLink.ast.type = typeLink.type; + } + } + }; + TypeChecker.prototype.resolveBaseTypeLink = function (typeLink, scope) { + this.resolvingBases = true; + this.resolveTypeLink(scope, typeLink, true); + this.resolvingBases = false; + var extendsType = null; + if(typeLink.type.isClass()) { + extendsType = typeLink.type.instanceType; + } else { + extendsType = typeLink.type; + } + return extendsType; + }; + TypeChecker.prototype.findMostApplicableSignature = function (signatures, args) { + if(signatures.length == 1) { + return { + sig: signatures[0].signature, + ambiguous: false + }; + } + var best = signatures[0]; + var Q = null; + var AType = null; + var PType = null; + var QType = null; + var ambiguous = false; + for(var qSig = 1; qSig < signatures.length; qSig++) { + Q = signatures[qSig]; + var i = 0; + for(i = 0; args && i < args.members.length; i++) { + AType = args.members[i].type; + PType = i < best.signature.parameters.length ? best.signature.parameters[i].getType() : best.signature.parameters[best.signature.parameters.length - 1].getType().elementType; + QType = i < Q.signature.parameters.length ? Q.signature.parameters[i].getType() : Q.signature.parameters[Q.signature.parameters.length - 1].getType().elementType; + if(this.typesAreIdentical(PType, QType)) { + continue; + } else { + if(this.typesAreIdentical(AType, PType)) { + break; + } else { + if(this.typesAreIdentical(AType, QType)) { + best = Q; + break; + } else { + if(this.sourceIsSubtypeOfTarget(PType, QType)) { + break; + } else { + if(this.sourceIsSubtypeOfTarget(QType, PType)) { + best = Q; + break; + } else { + if(Q.hadProvisionalErrors) { + break; + } else { + if(best.hadProvisionalErrors) { + best = Q; + break; + } + } + } + } + } + } + } + } + if(!args || i == args.members.length) { + var collection = { + getLength: function () { + return 2; + }, + setTypeAtIndex: function (index, type) { + }, + getTypeAtIndex: function (index) { + return index ? Q.signature.returnType.type : best.signature.returnType.type; + } + }; + var bct = this.findBestCommonType(best.signature.returnType.type, null, collection, true); + ambiguous = !bct; + } else { + ambiguous = false; + } + } + return { + sig: best.signature, + ambiguous: ambiguous + }; + }; + TypeChecker.prototype.getApplicableSignatures = function (signatures, args, comparisonInfo) { + var applicableSigs = []; + var memberType = null; + var miss = false; + var cxt = null; + var hadProvisionalErrors = false; + for(var i = 0; i < signatures.length; i++) { + miss = false; + for(var j = 0; j < args.members.length; j++) { + if(j >= signatures[i].parameters.length) { + continue; + } + memberType = signatures[i].parameters[j].getType(); + if(signatures[i].declAST.variableArgList && (j >= signatures[i].nonOptionalParameterCount - 1) && memberType.isArray()) { + memberType = memberType.elementType; + } + if(memberType == this.anyType) { + continue; + } else { + if(args.members[j].nodeType == TypeScript.NodeType.FuncDecl) { + if(this.typeFlow.functionInterfaceType && memberType == this.typeFlow.functionInterfaceType) { + continue; + } + if(!this.canContextuallyTypeFunction(memberType, args.members[j], true)) { + if(this.canContextuallyTypeFunction(memberType, args.members[j], false)) { + this.typeFlow.typeCheck(args.members[j]); + if(!this.sourceIsAssignableToTarget(args.members[j].type, memberType, comparisonInfo)) { + break; + } + } else { + break; + } + } else { + this.typeCheckWithContextualType(memberType, true, true, args.members[j]); + this.cleanStartedPTO(); + hadProvisionalErrors = this.hadProvisionalErrors(); + if(!this.sourceIsAssignableToTarget(args.members[j].type, memberType, comparisonInfo)) { + if(comparisonInfo) { + comparisonInfo.setMessage("Could not apply type '" + memberType.getTypeName() + "' to argument " + (j + 1) + ", which is of type '" + args.members[j].type.getTypeName() + "'"); + } + miss = true; + } + this.resetProvisionalErrors(); + if(miss) { + break; + } + } + } else { + if(args.members[j].nodeType == TypeScript.NodeType.ObjectLit) { + if(this.typeFlow.objectInterfaceType && memberType == this.typeFlow.objectInterfaceType) { + continue; + } + this.typeCheckWithContextualType(memberType, true, true, args.members[j]); + this.cleanStartedPTO(); + hadProvisionalErrors = this.hadProvisionalErrors(); + if(!this.sourceIsAssignableToTarget(args.members[j].type, memberType, comparisonInfo)) { + if(comparisonInfo) { + comparisonInfo.setMessage("Could not apply type '" + memberType.getTypeName() + "' to argument " + (j + 1) + ", which is of type '" + args.members[j].type.getTypeName() + "'"); + } + miss = true; + } + this.resetProvisionalErrors(); + if(miss) { + break; + } + } else { + if(args.members[j].nodeType == TypeScript.NodeType.ArrayLit) { + if(this.typeFlow.arrayInterfaceType && memberType == this.typeFlow.arrayInterfaceType) { + continue; + } + this.typeCheckWithContextualType(memberType, true, true, args.members[j]); + this.cleanStartedPTO(); + hadProvisionalErrors = this.hadProvisionalErrors(); + if(!this.sourceIsAssignableToTarget(args.members[j].type, memberType, comparisonInfo)) { + if(comparisonInfo) { + comparisonInfo.setMessage("Could not apply type '" + memberType.getTypeName() + "' to argument " + (j + 1) + ", which is of type '" + args.members[j].type.getTypeName() + "'"); + } + break; + } + this.resetProvisionalErrors(); + if(miss) { + break; + } + } + } + } + } + } + if(j == args.members.length) { + applicableSigs[applicableSigs.length] = { + signature: signatures[i], + hadProvisionalErrors: hadProvisionalErrors + }; + } + hadProvisionalErrors = false; + } + return applicableSigs; + }; + TypeChecker.prototype.canContextuallyTypeFunction = function (candidateType, funcDecl, beStringent) { + if(funcDecl.isParenthesized || funcDecl.isMethod() || beStringent && funcDecl.returnTypeAnnotation || funcDecl.isInlineCallLiteral) { + return false; + } + beStringent = beStringent || (this.typeFlow.functionInterfaceType == candidateType); + if(!beStringent) { + return true; + } + if(!funcDecl.signature) { + this.createFunctionSignature(funcDecl, this.typeFlow.scope.container, this.typeFlow.scope, null, null); + this.typeFlow.typeCheck(funcDecl); + } + var signature = funcDecl.signature; + var paramLen = signature.parameters.length; + for(var i = 0; i < paramLen; i++) { + var param = signature.parameters[i]; + var symbol = param; + var argDecl = symbol.declAST; + if(beStringent && argDecl.typeExpr) { + return false; + } + } + if(candidateType.construct && candidateType.call) { + return false; + } + var candidateSigs = candidateType.construct ? candidateType.construct : candidateType.call; + if(!candidateSigs || candidateSigs.signatures.length > 1) { + return false; + } + return true; + }; + TypeChecker.prototype.canContextuallyTypeObjectLiteral = function (targetType, objectLit) { + if(targetType == this.typeFlow.objectInterfaceType) { + return true; + } + var memberDecls = objectLit.operand; + if(!(memberDecls && targetType.memberScope)) { + return false; + } + var id = null; + var targetMember = null; + var text = ""; + var foundSyms = { + }; + for(var i = 0; i < memberDecls.members.length; i++) { + id = (memberDecls.members[i]).operand1; + if(id.nodeType == TypeScript.NodeType.Name) { + text = (id).text; + } else { + if(id.nodeType == TypeScript.NodeType.QString) { + var idText = (id).text; + text = idText.substring(1, idText.length - 1); + } else { + return false; + } + } + targetMember = targetType.memberScope.find(text, true, false); + if(!targetMember) { + return false; + } + foundSyms[text] = true; + } + var targetMembers = targetType.memberScope.getAllValueSymbolNames(true); + for(var i = 0; i < targetMembers.length; i++) { + var memberName = targetMembers[i]; + var memberSym = targetType.memberScope.find(memberName, true, false); + if(!foundSyms[targetMembers[i]] && !TypeScript.hasFlag(memberSym.flags, TypeScript.SymbolFlags.Optional)) { + return false; + } + } + return true; + }; + TypeChecker.prototype.widenType = function (t) { + if(t == this.undefinedType || t == this.nullType) { + return this.anyType; + } + return t; + }; + TypeChecker.prototype.isNullOrUndefinedType = function (t) { + return t == this.undefinedType || t == this.nullType; + }; + TypeChecker.prototype.findBestCommonType = function (initialType, targetType, collection, acceptVoid, comparisonInfo) { + var i = 0; + var len = collection.getLength(); + var nlastChecked = 0; + var bestCommonType = initialType; + if(targetType) { + bestCommonType = bestCommonType ? bestCommonType.mergeOrdered(targetType, this, acceptVoid) : targetType; + } + var convergenceType = bestCommonType; + while(nlastChecked < len) { + for(i = 0; i < len; i++) { + if(i == nlastChecked) { + continue; + } + if(convergenceType && (bestCommonType = convergenceType.mergeOrdered(collection.getTypeAtIndex(i), this, acceptVoid, comparisonInfo))) { + convergenceType = bestCommonType; + } + if(bestCommonType == this.anyType || bestCommonType == null) { + break; + } else { + if(targetType) { + collection.setTypeAtIndex(i, targetType); + } + } + } + if(convergenceType && bestCommonType) { + break; + } + nlastChecked++; + if(nlastChecked < len) { + convergenceType = collection.getTypeAtIndex(nlastChecked); + } + } + return acceptVoid ? bestCommonType : (bestCommonType == this.voidType ? null : bestCommonType); + }; + TypeChecker.prototype.typesAreIdentical = function (t1, t2) { + if(t1 == t2) { + return true; + } + if(!t1 || !t2) { + return false; + } + if(t1.isClass() || t1.isClassInstance()) { + return false; + } + var comboId = (t2.typeID << 16) | t1.typeID; + if(this.identicalCache[comboId]) { + return true; + } + if((t1.typeFlags & TypeScript.TypeFlags.IsEnum) || (t2.typeFlags & TypeScript.TypeFlags.IsEnum)) { + return false; + } + if(t1.isArray() || t2.isArray()) { + if(!(t1.isArray() && t2.isArray())) { + return false; + } + this.identicalCache[comboId] = false; + var ret = this.typesAreIdentical(t1.elementType, t2.elementType); + if(ret) { + this.subtypeCache[comboId] = true; + } else { + this.subtypeCache[comboId] = undefined; + } + return ret; + } + if(t1.primitiveTypeClass != t2.primitiveTypeClass) { + return false; + } + this.identicalCache[comboId] = false; + if(t1.memberScope && t2.memberScope) { + var t1MemberKeys = t1.memberScope.getAllValueSymbolNames(true).sort(); + var t2MemberKeys = t2.memberScope.getAllValueSymbolNames(true).sort(); + if(t1MemberKeys.length != t2MemberKeys.length) { + this.identicalCache[comboId] = undefined; + return false; + } + var t1MemberSymbol = null; + var t2MemberSymbol = null; + var t1MemberType = null; + var t2MemberType = null; + for(var iMember = 0; iMember < t1MemberKeys.length; iMember++) { + if(t1MemberKeys[iMember] != t2MemberKeys[iMember]) { + this.identicalCache[comboId] = undefined; + return false; + } + t1MemberSymbol = t1.memberScope.find(t1MemberKeys[iMember], false, false); + t2MemberSymbol = t2.memberScope.find(t2MemberKeys[iMember], false, false); + if((t1MemberSymbol.flags & TypeScript.SymbolFlags.Optional) != (t2MemberSymbol.flags & TypeScript.SymbolFlags.Optional)) { + this.identicalCache[comboId] = undefined; + return false; + } + t1MemberType = t1MemberSymbol.getType(); + t2MemberType = t2MemberSymbol.getType(); + if(t1MemberType && t2MemberType && (this.identicalCache[(t2MemberType.typeID << 16) | t1MemberType.typeID] != undefined)) { + continue; + } + if(!this.typesAreIdentical(t1MemberType, t2MemberType)) { + this.identicalCache[comboId] = undefined; + return false; + } + } + } else { + if(t1.memberScope || t2.memberScope) { + this.identicalCache[comboId] = undefined; + return false; + } + } + if(!this.signatureGroupsAreIdentical(t1.call, t2.call)) { + this.identicalCache[comboId] = undefined; + return false; + } + if(!this.signatureGroupsAreIdentical(t1.construct, t2.construct)) { + this.identicalCache[comboId] = undefined; + return false; + } + if(!this.signatureGroupsAreIdentical(t1.index, t2.index)) { + this.identicalCache[comboId] = undefined; + return false; + } + this.identicalCache[comboId] = true; + return true; + }; + TypeChecker.prototype.signatureGroupsAreIdentical = function (sg1, sg2) { + if(sg1 == sg2) { + return true; + } + if(!sg1 || !sg2) { + return false; + } + if(sg1.signatures.length != sg2.signatures.length) { + return false; + } + var sig1 = null; + var sig2 = null; + var sigsMatch = false; + for(var iSig1 = 0; iSig1 < sg1.signatures.length; iSig1++) { + sig1 = sg1.signatures[iSig1]; + for(var iSig2 = 0; iSig2 < sg2.signatures.length; iSig2++) { + sig2 = sg2.signatures[iSig2]; + if(this.signaturesAreIdentical(sig1, sig2)) { + sigsMatch = true; + break; + } + } + if(sigsMatch) { + sigsMatch = false; + continue; + } + return false; + } + return true; + }; + TypeChecker.prototype.signaturesAreIdentical = function (s1, s2) { + if(s1.hasVariableArgList != s2.hasVariableArgList) { + return false; + } + if(s1.nonOptionalParameterCount != s2.nonOptionalParameterCount) { + return false; + } + if(s1.parameters.length != s2.parameters.length) { + return false; + } + if(!this.typesAreIdentical(s1.returnType.type, s2.returnType.type)) { + return false; + } + for(var iParam = 0; iParam < s1.parameters.length; iParam++) { + if(!this.typesAreIdentical(s1.parameters[iParam].parameter.typeLink.type, s2.parameters[iParam].parameter.typeLink.type)) { + return false; + } + } + return true; + }; + TypeChecker.prototype.sourceIsSubtypeOfTarget = function (source, target, comparisonInfo) { + return this.sourceIsRelatableToTarget(source, target, false, this.subtypeCache, comparisonInfo); + }; + TypeChecker.prototype.signatureGroupIsSubtypeOfTarget = function (sg1, sg2, comparisonInfo) { + return this.signatureGroupIsRelatableToTarget(sg1, sg2, false, this.subtypeCache, comparisonInfo); + }; + TypeChecker.prototype.signatureIsSubtypeOfTarget = function (s1, s2, comparisonInfo) { + return this.signatureIsRelatableToTarget(s1, s2, false, this.subtypeCache, comparisonInfo); + }; + TypeChecker.prototype.sourceIsAssignableToTarget = function (source, target, comparisonInfo) { + return this.sourceIsRelatableToTarget(source, target, true, this.assignableCache, comparisonInfo); + }; + TypeChecker.prototype.signatureGroupIsAssignableToTarget = function (sg1, sg2, comparisonInfo) { + return this.signatureGroupIsRelatableToTarget(sg1, sg2, true, this.assignableCache, comparisonInfo); + }; + TypeChecker.prototype.signatureIsAssignableToTarget = function (s1, s2, comparisonInfo) { + return this.signatureIsRelatableToTarget(s1, s2, true, this.assignableCache, comparisonInfo); + }; + TypeChecker.prototype.sourceIsRelatableToTarget = function (source, target, assignableTo, comparisonCache, comparisonInfo) { + if(source == target) { + return true; + } + if(!(source && target)) { + return true; + } + var comboId = (source.typeID << 16) | target.typeID; + if(comparisonCache[comboId] != undefined) { + return true; + } + if(assignableTo) { + if(source == this.anyType || target == this.anyType) { + return true; + } + } else { + if(target == this.anyType) { + return true; + } + } + if(source == this.undefinedType) { + return true; + } + if((source == this.nullType) && (target != this.undefinedType && target != this.voidType)) { + return true; + } + if(target == this.numberType && (source.typeFlags & TypeScript.TypeFlags.IsEnum)) { + return true; + } + if(source == this.numberType && (target.typeFlags & TypeScript.TypeFlags.IsEnum)) { + return true; + } + if((source.typeFlags & TypeScript.TypeFlags.IsEnum) || (target.typeFlags & TypeScript.TypeFlags.IsEnum)) { + return false; + } + if(source.isArray() || target.isArray()) { + if(!(source.isArray() && target.isArray())) { + return false; + } + comparisonCache[comboId] = false; + var ret = this.sourceIsRelatableToTarget(source.elementType, target.elementType, assignableTo, comparisonCache, comparisonInfo); + if(ret) { + comparisonCache[comboId] = true; + } else { + comparisonCache[comboId] = undefined; + } + return ret; + } + if(source.primitiveTypeClass != target.primitiveTypeClass) { + if(target.primitiveTypeClass == TypeScript.Primitive.None) { + if(source == this.numberType && this.typeFlow.numberInterfaceType) { + source = this.typeFlow.numberInterfaceType; + } else { + if(source == this.stringType && this.typeFlow.stringInterfaceType) { + source = this.typeFlow.stringInterfaceType; + } else { + if(source == this.booleanType && this.typeFlow.booleanInterfaceType) { + source = this.typeFlow.booleanInterfaceType; + } else { + return false; + } + } + } + } else { + return false; + } + } + comparisonCache[comboId] = false; + if(source.hasBase(target)) { + comparisonCache[comboId] = true; + return true; + } + if(this.typeFlow.objectInterfaceType && target == this.typeFlow.objectInterfaceType) { + return true; + } + if(this.typeFlow.functionInterfaceType && (source.call || source.construct) && target == this.typeFlow.functionInterfaceType) { + return true; + } + if(target.isClass() || target.isClassInstance()) { + comparisonCache[comboId] = undefined; + return false; + } + if(target.memberScope && source.memberScope) { + var mPropKeys = target.memberScope.getAllValueSymbolNames(true); + var mProp = null; + var nProp = null; + var mPropType = null; + var nPropType = null; + var inferenceSymbol = null; + for(var iMProp = 0; iMProp < mPropKeys.length; iMProp++) { + mProp = target.memberScope.find(mPropKeys[iMProp], false, false); + nProp = source.memberScope.find(mPropKeys[iMProp], false, false); + if(mProp.name == "arguments" && this.typeFlow.iargumentsInterfaceType && (this.typeFlow.iargumentsInterfaceType.symbol.flags & TypeScript.SymbolFlags.CompilerGenerated) && mProp.kind() == TypeScript.SymbolKind.Variable && (mProp).variable.typeLink.type == this.typeFlow.iargumentsInterfaceType) { + continue; + } + if(mProp.isInferenceSymbol()) { + inferenceSymbol = mProp; + if(inferenceSymbol.typeCheckStatus == TypeScript.TypeCheckStatus.NotStarted) { + this.typeFlow.typeCheck(mProp.declAST); + } + } + mPropType = mProp.getType(); + if(!nProp) { + if(this.typeFlow.objectInterfaceType) { + nProp = this.typeFlow.objectInterfaceType.memberScope.find(mPropKeys[iMProp], false, false); + } + if(!nProp) { + if(this.typeFlow.functionInterfaceType && (mPropType.call || mPropType.construct)) { + nProp = this.typeFlow.functionInterfaceType.memberScope.find(mPropKeys[iMProp], false, false); + } + if(!nProp) { + if(!(mProp.flags & TypeScript.SymbolFlags.Optional)) { + comparisonCache[comboId] = undefined; + if(comparisonInfo) { + comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.RequiredPropertyIsMissing; + comparisonInfo.addMessageToFront("Type '" + source.getTypeName() + "' is missing property '" + mPropKeys[iMProp] + "' from type '" + target.getTypeName() + "'"); + } + return false; + } else { + continue; + } + } + } + } + if(nProp.isInferenceSymbol()) { + inferenceSymbol = nProp; + if(inferenceSymbol.typeCheckStatus == TypeScript.TypeCheckStatus.NotStarted) { + this.typeFlow.typeCheck(nProp.declAST); + } + } + nPropType = nProp.getType(); + if(mPropType && nPropType && (comparisonCache[(nPropType.typeID << 16) | mPropType.typeID] != undefined)) { + continue; + } + if(!this.sourceIsRelatableToTarget(nPropType, mPropType, assignableTo, comparisonCache, comparisonInfo)) { + comparisonCache[comboId] = undefined; + if(comparisonInfo) { + comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatiblePropertyTypes; + comparisonInfo.addMessageToFront("Types of property '" + mProp.name + "' of types '" + source.getTypeName() + "' and '" + target.getTypeName() + "' are incompatible"); + } + return false; + } + } + } + if(source.call || target.call) { + if(!this.signatureGroupIsRelatableToTarget(source.call, target.call, assignableTo, comparisonCache, comparisonInfo)) { + if(comparisonInfo) { + if(source.call && target.call) { + comparisonInfo.addMessageToFront("Call signatures of types '" + source.getTypeName() + "' and '" + target.getTypeName() + "' are incompatible"); + } else { + var hasSig = target.call ? target.getTypeName() : source.getTypeName(); + var lacksSig = !target.call ? target.getTypeName() : source.getTypeName(); + comparisonInfo.setMessage("Type '" + hasSig + "' requires a call signature, but Type '" + lacksSig + "' lacks one"); + } + comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleSignatures; + } + comparisonCache[comboId] = undefined; + return false; + } + } + if(source.construct || target.construct) { + if(!this.signatureGroupIsRelatableToTarget(source.construct, target.construct, assignableTo, comparisonCache, comparisonInfo)) { + if(comparisonInfo) { + if(source.construct && target.construct) { + comparisonInfo.addMessageToFront("Construct signatures of types '" + source.getTypeName() + "' and '" + target.getTypeName() + "' are incompatible"); + } else { + var hasSig = target.construct ? target.getTypeName() : source.getTypeName(); + var lacksSig = !target.construct ? target.getTypeName() : source.getTypeName(); + comparisonInfo.setMessage("Type '" + hasSig + "' requires a construct signature, but Type '" + lacksSig + "' lacks one"); + } + comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleSignatures; + } + comparisonCache[comboId] = undefined; + return false; + } + } + if(target.index) { + var targetIndex = !target.index && this.typeFlow.objectInterfaceType ? this.typeFlow.objectInterfaceType.index : target.index; + var sourceIndex = !source.index && this.typeFlow.objectInterfaceType ? this.typeFlow.objectInterfaceType.index : source.index; + if(!this.signatureGroupIsRelatableToTarget(sourceIndex, targetIndex, assignableTo, comparisonCache, comparisonInfo)) { + if(comparisonInfo) { + comparisonInfo.addMessageToFront("Index signatures of types '" + source.getTypeName() + "' and '" + target.getTypeName() + "' are incompatible"); + comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleSignatures; + } + comparisonCache[comboId] = undefined; + return false; + } + } + comparisonCache[comboId] = true; + return true; + }; + TypeChecker.prototype.signatureGroupIsRelatableToTarget = function (sourceSG, targetSG, assignableTo, comparisonCache, comparisonInfo) { + if(sourceSG == targetSG) { + return true; + } + if(!(sourceSG && targetSG)) { + return false; + } + var mSig = null; + var nSig = null; + var foundMatch = false; + for(var iMSig = 0; iMSig < targetSG.signatures.length; iMSig++) { + mSig = targetSG.signatures[iMSig]; + for(var iNSig = 0; iNSig < sourceSG.signatures.length; iNSig++) { + nSig = sourceSG.signatures[iNSig]; + if(this.signatureIsRelatableToTarget(nSig, mSig, assignableTo, comparisonCache, comparisonInfo)) { + foundMatch = true; + break; + } + } + if(foundMatch) { + foundMatch = false; + continue; + } + return false; + } + return true; + }; + TypeChecker.prototype.signatureIsRelatableToTarget = function (sourceSig, targetSig, assignableTo, comparisonCache, comparisonInfo) { + if(!sourceSig.parameters || !targetSig.parameters) { + return false; + } + var targetVarArgCount = targetSig.hasVariableArgList ? targetSig.nonOptionalParameterCount - 1 : targetSig.nonOptionalParameterCount; + var sourceVarArgCount = sourceSig.hasVariableArgList ? sourceSig.nonOptionalParameterCount - 1 : sourceSig.nonOptionalParameterCount; + if(sourceVarArgCount > targetVarArgCount && !targetSig.hasVariableArgList) { + if(comparisonInfo) { + comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.SourceSignatureHasTooManyParameters; + comparisonInfo.addMessageToFront("Call signature expects " + targetVarArgCount + " or fewer parameters"); + } + return false; + } + var sourceReturnType = sourceSig.returnType.type; + var targetReturnType = targetSig.returnType.type; + if(targetReturnType != this.voidType) { + if(!this.sourceIsRelatableToTarget(sourceReturnType, targetReturnType, assignableTo, comparisonCache, comparisonInfo)) { + if(comparisonInfo) { + comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleReturnTypes; + } + return false; + } + } + var len = (sourceVarArgCount < targetVarArgCount && sourceSig.hasVariableArgList) ? targetVarArgCount : sourceVarArgCount; + var sourceParamType = null; + var targetParamType = null; + var sourceParamName = ""; + var targetParamName = ""; + for(var iSource = 0, iTarget = 0; iSource < len; iSource++ , iTarget++) { + if(!sourceSig.hasVariableArgList || iSource < sourceVarArgCount) { + sourceParamType = (sourceSig.parameters[iSource]).parameter.typeLink.type; + sourceParamName = (sourceSig.parameters[iSource]).parameter.symbol.name; + } else { + if(iSource == sourceVarArgCount) { + sourceParamType = (sourceSig.parameters[iSource]).parameter.typeLink.type; + if(sourceParamType.elementType) { + sourceParamType = sourceParamType.elementType; + } + sourceParamName = (sourceSig.parameters[iSource]).parameter.symbol.name; + } + } + if(iTarget < targetSig.parameters.length && iTarget < targetVarArgCount) { + targetParamType = (targetSig.parameters[iTarget]).parameter.typeLink.type; + targetParamName = (targetSig.parameters[iTarget]).parameter.symbol.name; + } else { + if(targetSig.hasVariableArgList && iTarget == targetVarArgCount) { + targetParamType = (targetSig.parameters[iTarget]).parameter.typeLink.type; + if(targetParamType.elementType) { + targetParamType = targetParamType.elementType; + } + targetParamName = (targetSig.parameters[iTarget]).parameter.symbol.name; + } + } + if(!(this.sourceIsRelatableToTarget(sourceParamType, targetParamType, assignableTo, comparisonCache, comparisonInfo) || this.sourceIsRelatableToTarget(targetParamType, sourceParamType, assignableTo, comparisonCache, comparisonInfo))) { + if(comparisonInfo) { + comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleParameterTypes; + } + return false; + } + } + return true; + }; + return TypeChecker; + })(); + TypeScript.TypeChecker = TypeChecker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Continuation = (function () { + function Continuation(normalBlock) { + this.normalBlock = normalBlock; + this.exceptionBlock = -1; + } + return Continuation; + })(); + TypeScript.Continuation = Continuation; + function getBaseTypeLinks(bases, baseTypeLinks) { + if(bases) { + var len = bases.members.length; + if(baseTypeLinks == null) { + baseTypeLinks = new Array(); + } + for(var i = 0; i < len; i++) { + var baseExpr = bases.members[i]; + var name = baseExpr; + var typeLink = new TypeScript.TypeLink(); + typeLink.ast = name; + baseTypeLinks[baseTypeLinks.length] = typeLink; + } + } + return baseTypeLinks; + } + function getBases(type, typeDecl) { + type.extendsTypeLinks = getBaseTypeLinks(typeDecl.extendsList, type.extendsTypeLinks); + type.implementsTypeLinks = getBaseTypeLinks(typeDecl.implementsList, type.implementsTypeLinks); + } + function addPrototypeField(classType, ast, context) { + var field = new TypeScript.ValueLocation(); + field.typeLink = new TypeScript.TypeLink(); + field.typeLink.ast = ast; + field.typeLink.type = classType.instanceType; + var fieldSymbol = new TypeScript.FieldSymbol("prototype", ast.minChar, context.checker.locationInfo.unitIndex, true, field); + fieldSymbol.flags |= (TypeScript.SymbolFlags.Property | TypeScript.SymbolFlags.BuiltIn); + field.symbol = fieldSymbol; + fieldSymbol.declAST = ast; + classType.members.addPublicMember("prototype", fieldSymbol); + } + function createNewConstructGroupForType(type) { + var signature = new TypeScript.Signature(); + signature.returnType = new TypeScript.TypeLink(); + signature.returnType.type = type.instanceType; + signature.parameters = []; + type.construct = new TypeScript.SignatureGroup(); + type.construct.addSignature(signature); + } + TypeScript.createNewConstructGroupForType = createNewConstructGroupForType; + function cloneParentConstructGroupForChildType(child, parent) { + child.construct = new TypeScript.SignatureGroup(); + var sig = null; + if(!parent.construct) { + createNewConstructGroupForType(parent); + } + for(var i = 0; i < parent.construct.signatures.length; i++) { + sig = new TypeScript.Signature(); + sig.parameters = parent.construct.signatures[i].parameters; + sig.nonOptionalParameterCount = parent.construct.signatures[i].nonOptionalParameterCount; + sig.typeCheckStatus = parent.construct.signatures[i].typeCheckStatus; + sig.declAST = parent.construct.signatures[i].declAST; + sig.returnType = new TypeScript.TypeLink(); + sig.returnType.type = child.instanceType; + child.construct.addSignature(sig); + } + } + TypeScript.cloneParentConstructGroupForChildType = cloneParentConstructGroupForChildType; + TypeScript.globalId = "__GLO"; + function findTypeSymbolInScopeChain(name, scopeChain) { + var symbol = scopeChain.scope.find(name, false, true); + if(symbol == null && scopeChain.previous) { + symbol = findTypeSymbolInScopeChain(name, scopeChain.previous); + } + return symbol; + } + function findSymbolFromAlias(alias, context) { + var symbol = null; + switch(alias.nodeType) { + case TypeScript.NodeType.Name: { + var name = (alias).text; + var isDynamic = TypeScript.isQuoted(name); + var findSym = function (id) { + if(context.members) { + return context.members.lookup(name); + } else { + return findTypeSymbolInScopeChain(name, context.topLevelScope); + } + }; + if(isDynamic) { + symbol = context.tcContext.checker.findSymbolForDynamicModule(name, context.tcContext.script.locationInfo.filename, findSym); + } else { + symbol = findSym(name); + } + break; + + } + case TypeScript.NodeType.Dot: { + var dottedExpr = alias; + var op1Sym = findSymbolFromAlias(dottedExpr.operand1, context); + if(op1Sym && op1Sym.getType()) { + symbol = findSymbolFromAlias(dottedExpr.operand2, context); + } + break; + + } + default: { + break; + + } + } + if(symbol) { + var symType = symbol.getType(); + if(symType) { + var members = symType.members; + if(members) { + context.members = members.publicMembers; + } + } + } + return symbol; + } + function preCollectImportTypes(ast, parent, context) { + var scopeChain = context.scopeChain; + var typeSymbol = null; + var modType = null; + var importDecl = ast; + var aliasedModSymbol = findSymbolFromAlias(importDecl.alias, { + topLevelScope: scopeChain, + members: null, + tcContext: context + }); + var isGlobal = context.scopeChain.container == context.checker.gloMod; + if(aliasedModSymbol) { + var aliasedModType = aliasedModSymbol.getType(); + if(aliasedModType) { + modType = aliasedModType; + } + } + typeSymbol = new TypeScript.TypeSymbol(importDecl.id.text, importDecl.id.minChar, importDecl.limChar - importDecl.minChar, context.checker.locationInfo.unitIndex, modType); + typeSymbol.aliasLink = importDecl; + if(context.scopeChain.moduleDecl) { + typeSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; + typeSymbol.declModule = context.scopeChain.moduleDecl; + } + typeSymbol.declAST = importDecl; + importDecl.id.sym = typeSymbol; + scopeChain.scope.enter(scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isGlobal, true, false); + scopeChain.scope.enter(scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isGlobal, false, false); + return true; + } + TypeScript.preCollectImportTypes = preCollectImportTypes; + function preCollectModuleTypes(ast, parent, context) { + var scopeChain = context.scopeChain; + var moduleDecl = ast; + var isAmbient = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.Ambient); + var isEnum = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsEnum); + var isGlobal = context.scopeChain.container == context.checker.gloMod; + var isExported = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.Exported); + var modName = (moduleDecl.name).text; + var isDynamic = TypeScript.isQuoted(modName); + var symbol = scopeChain.scope.findLocal(modName, false, false); + var typeSymbol = null; + var modType = null; + if((symbol == null) || (symbol.kind() != TypeScript.SymbolKind.Type)) { + if(modType == null) { + var enclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + var ambientEnclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + modType = new TypeScript.ModuleType(enclosedTypes, ambientEnclosedTypes); + if(isEnum) { + modType.typeFlags |= TypeScript.TypeFlags.IsEnum; + } + modType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + modType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + modType.setHasImplementation(); + } + typeSymbol = new TypeScript.TypeSymbol(modName, moduleDecl.name.minChar, modName.length, context.checker.locationInfo.unitIndex, modType); + typeSymbol.isDynamic = TypeScript.isQuoted(moduleDecl.prettyName); + if(context.scopeChain.moduleDecl) { + typeSymbol.declModule = context.scopeChain.moduleDecl; + } + typeSymbol.declAST = moduleDecl; + typeSymbol.prettyName = moduleDecl.prettyName; + scopeChain.scope.enter(scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, true, isAmbient); + scopeChain.scope.enter(scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, false, isAmbient); + modType.symbol = typeSymbol; + } else { + if(symbol && symbol.declAST && symbol.declAST.nodeType != TypeScript.NodeType.ModuleDeclaration) { + context.checker.errorReporter.simpleError(moduleDecl, "Conflicting symbol name for module '" + modName + "'"); + } + typeSymbol = symbol; + var publicEnclosedTypes = typeSymbol.type.getAllEnclosedTypes().publicMembers; + var publicEnclosedTypesTable = (publicEnclosedTypes == null) ? new TypeScript.StringHashTable() : publicEnclosedTypes; + var enclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(publicEnclosedTypesTable, new TypeScript.StringHashTable())); + var publicEnclosedAmbientTypes = typeSymbol.type.getAllAmbientEnclosedTypes().publicMembers; + var publicAmbientEnclosedTypesTable = (publicEnclosedAmbientTypes == null) ? new TypeScript.StringHashTable() : publicEnclosedAmbientTypes; + var ambientEnclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(publicAmbientEnclosedTypesTable, new TypeScript.StringHashTable())); + var publicMembers = typeSymbol.type.members.publicMembers; + var publicMembersTable = (publicMembers == null) ? new TypeScript.StringHashTable() : publicMembers; + var members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(publicMembersTable, new TypeScript.StringHashTable())); + var publicAmbientMembers = typeSymbol.type.ambientMembers.publicMembers; + var publicAmbientMembersTable = (publicAmbientMembers == null) ? new TypeScript.StringHashTable() : publicAmbientMembers; + var ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(publicAmbientMembersTable, new TypeScript.StringHashTable())); + modType = new TypeScript.ModuleType(enclosedTypes, ambientEnclosedTypes); + if(isEnum) { + modType.typeFlags |= TypeScript.TypeFlags.IsEnum; + } + modType.members = members; + modType.ambientMembers = ambientMembers; + modType.setHasImplementation(); + modType.symbol = typeSymbol; + typeSymbol.addLocation(moduleDecl.minChar); + typeSymbol.expansions.push(modType); + typeSymbol.expansionsDeclAST.push(moduleDecl); + } + if(context.scopeChain.moduleDecl) { + context.scopeChain.moduleDecl.recordNonInterface(); + } + if(isExported) { + typeSymbol.flags |= TypeScript.SymbolFlags.Exported; + } + if((context.scopeChain.moduleDecl) || (context.scopeChain.container == context.checker.gloMod)) { + typeSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; + } + moduleDecl.mod = modType; + TypeScript.pushTypeCollectionScope(typeSymbol, modType.members, modType.ambientMembers, modType.enclosedTypes, modType.ambientEnclosedTypes, context, null, null, moduleDecl); + return true; + } + TypeScript.preCollectModuleTypes = preCollectModuleTypes; + function preCollectClassTypes(ast, parent, context) { + var scopeChain = context.scopeChain; + var classDecl = ast; + var classType; + var instanceType; + var typeSymbol = null; + var className = (classDecl.name).text; + var alreadyInScope = false; + var isAmbient = TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Ambient); + var isExported = TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Exported); + var isGlobal = context.scopeChain.container == context.checker.gloMod; + var containerMod = scopeChain.container; + var foundValSymbol = false; + typeSymbol = scopeChain.scope.findLocal(className, false, true); + if(!typeSymbol) { + var valTypeSymbol = scopeChain.scope.findLocal(className, false, false); + if(valTypeSymbol && valTypeSymbol.isType() && valTypeSymbol.declAST && valTypeSymbol.declAST.nodeType == TypeScript.NodeType.FuncDecl && (valTypeSymbol.declAST).isSignature()) { + typeSymbol = valTypeSymbol; + foundValSymbol = true; + if(isExported) { + typeSymbol.flags |= TypeScript.SymbolFlags.Exported; + } + if(isAmbient) { + typeSymbol.flags |= TypeScript.SymbolFlags.Ambient; + } + context.scopeChain.scope.enter(context.scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, true, isAmbient); + } + } + if(typeSymbol && !foundValSymbol && (typeSymbol.declAST != classDecl)) { + typeSymbol = null; + } + if(typeSymbol == null) { + var valueSymbol = scopeChain.scope.findLocal(className, false, false); + classType = new TypeScript.Type(); + classType.setHasImplementation(); + instanceType = new TypeScript.Type(); + instanceType.setHasImplementation(); + classType.instanceType = instanceType; + classType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + classType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + addPrototypeField(classType, classDecl, context); + instanceType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + instanceType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + typeSymbol = new TypeScript.TypeSymbol(className, classDecl.name.minChar, className.length, context.checker.locationInfo.unitIndex, classType); + typeSymbol.declAST = classDecl; + typeSymbol.instanceType = instanceType; + classType.symbol = typeSymbol; + instanceType.symbol = typeSymbol; + if(context.scopeChain.moduleDecl) { + context.scopeChain.moduleDecl.recordNonInterface(); + typeSymbol.declModule = context.scopeChain.moduleDecl; + typeSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; + } + if(isExported) { + typeSymbol.flags |= TypeScript.SymbolFlags.Exported; + } + if(isAmbient) { + typeSymbol.flags |= TypeScript.SymbolFlags.Ambient; + } + ast.type = classType; + context.scopeChain.scope.enter(context.scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, true, isAmbient); + if(valueSymbol == null) { + context.scopeChain.scope.enter(context.scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, false, isAmbient); + } + } else { + classType = typeSymbol.type; + if(classType.instanceType == null) { + classType.instanceType = new TypeScript.Type(); + classType.instanceType.setHasImplementation(); + classType.instanceType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + classType.instanceType.symbol = classType.symbol; + classType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + classType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + } + instanceType = classType.instanceType; + ast.type = classType; + } + if(!classDecl.constructorDecl) { + if(typeSymbol && typeSymbol.declAST && typeSymbol.declAST.type && typeSymbol.declAST.type.call && !(typeSymbol.declAST).isOverload) { + context.checker.errorReporter.duplicateIdentifier(typeSymbol.declAST, typeSymbol.name); + } + createNewConstructGroupForType(classDecl.type); + } + classType.typeFlags |= TypeScript.TypeFlags.IsClass; + instanceType.typeFlags |= TypeScript.TypeFlags.IsClass; + getBases(instanceType, classDecl); + TypeScript.pushTypeCollectionScope(typeSymbol, instanceType.members, instanceType.ambientMembers, null, null, context, instanceType, classType, null); + return true; + } + TypeScript.preCollectClassTypes = preCollectClassTypes; + function preCollectInterfaceTypes(ast, parent, context) { + var scopeChain = context.scopeChain; + var interfaceDecl = ast; + var interfaceSymbol = null; + var interfaceType = null; + var isExported = TypeScript.hasFlag(interfaceDecl.varFlags, TypeScript.VarFlags.Exported); + var isGlobal = context.scopeChain.container == context.checker.gloMod; + var alreadyInScope = true; + alreadyInScope = false; + var interfaceName = (interfaceDecl.name).text; + interfaceSymbol = scopeChain.scope.findLocal(interfaceName, false, true); + if(interfaceSymbol == null) { + interfaceType = new TypeScript.Type(); + interfaceSymbol = new TypeScript.TypeSymbol(interfaceName, interfaceDecl.name.minChar, interfaceName.length, context.checker.locationInfo.unitIndex, interfaceType); + interfaceType.symbol = interfaceSymbol; + interfaceType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + interfaceType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + interfaceSymbol.declAST = interfaceDecl; + interfaceSymbol.declModule = context.scopeChain.moduleDecl; + } else { + alreadyInScope = true; + interfaceType = interfaceSymbol.type; + } + if(!interfaceType) { + interfaceType = context.checker.anyType; + } + ast.type = interfaceType; + getBases(interfaceType, interfaceDecl); + if(isExported) { + interfaceSymbol.flags |= TypeScript.SymbolFlags.Exported; + } + if(context.scopeChain.moduleDecl) { + interfaceSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; + } + if(!alreadyInScope) { + context.scopeChain.scope.enter(context.scopeChain.container, ast, interfaceSymbol, context.checker.errorReporter, isGlobal || isExported, true, false); + } + TypeScript.pushTypeCollectionScope(interfaceSymbol, interfaceType.members, interfaceType.ambientMembers, null, null, context, interfaceType, null, null); + return true; + } + TypeScript.preCollectInterfaceTypes = preCollectInterfaceTypes; + function preCollectArgDeclTypes(ast, parent, context) { + var scopeChain = context.scopeChain; + var argDecl = ast; + if(TypeScript.hasFlag(argDecl.varFlags, TypeScript.VarFlags.Public | TypeScript.VarFlags.Private)) { + var field = new TypeScript.ValueLocation(); + var isPrivate = TypeScript.hasFlag(argDecl.varFlags, TypeScript.VarFlags.Private); + var fieldSymbol = new TypeScript.FieldSymbol(argDecl.id.text, argDecl.id.minChar, context.checker.locationInfo.unitIndex, !TypeScript.hasFlag(argDecl.varFlags, TypeScript.VarFlags.Readonly), field); + fieldSymbol.transferVarFlags(argDecl.varFlags); + field.symbol = fieldSymbol; + fieldSymbol.declAST = ast; + argDecl.parameterPropertySym = fieldSymbol; + context.scopeChain.scope.enter(context.scopeChain.container, ast, fieldSymbol, context.checker.errorReporter, !isPrivate, false, false); + field.typeLink = TypeScript.getTypeLink(argDecl.typeExpr, context.checker, argDecl.init == null); + argDecl.sym = fieldSymbol; + } + return false; + } + TypeScript.preCollectArgDeclTypes = preCollectArgDeclTypes; + function preCollectVarDeclTypes(ast, parent, context) { + var scopeChain = context.scopeChain; + var varDecl = ast; + var isAmbient = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Ambient); + var isExported = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Exported); + var isGlobal = context.scopeChain.container == context.checker.gloMod; + var isProperty = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Property); + var isStatic = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static); + var isPrivate = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Private); + var isOptional = TypeScript.hasFlag(varDecl.id.flags, TypeScript.ASTFlags.OptionalName); + if(context.scopeChain.moduleDecl) { + context.scopeChain.moduleDecl.recordNonInterface(); + } + if(isProperty || isExported || (context.scopeChain.container == context.checker.gloMod) || context.scopeChain.moduleDecl) { + if(isAmbient) { + var existingSym = scopeChain.scope.findLocal(varDecl.id.text, false, false); + if(existingSym) { + varDecl.sym = existingSym; + return false; + } + } + if(varDecl.id == null) { + context.checker.errorReporter.simpleError(varDecl, "Expected variable identifier at this location"); + return false; + } + var field = new TypeScript.ValueLocation(); + var fieldSymbol = new TypeScript.FieldSymbol(varDecl.id.text, varDecl.id.minChar, context.checker.locationInfo.unitIndex, (varDecl.varFlags & TypeScript.VarFlags.Readonly) == TypeScript.VarFlags.None, field); + fieldSymbol.transferVarFlags(varDecl.varFlags); + if(isOptional) { + fieldSymbol.flags |= TypeScript.SymbolFlags.Optional; + } + field.symbol = fieldSymbol; + fieldSymbol.declAST = ast; + if((context.scopeChain.moduleDecl) || (context.scopeChain.container == context.checker.gloMod)) { + fieldSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; + fieldSymbol.declModule = context.scopeChain.moduleDecl; + } + if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Property) && isStatic && context.scopeChain.classType) { + if(!context.scopeChain.classType.members.publicMembers.add(varDecl.id.text, fieldSymbol)) { + context.checker.errorReporter.duplicateIdentifier(ast, fieldSymbol.name); + } + fieldSymbol.container = context.scopeChain.classType.symbol; + } else { + context.scopeChain.scope.enter(context.scopeChain.container, ast, fieldSymbol, context.checker.errorReporter, !isPrivate && (isProperty || isExported || isGlobal || isStatic), false, isAmbient); + } + if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Exported)) { + fieldSymbol.flags |= TypeScript.SymbolFlags.Exported; + } + field.typeLink = TypeScript.getTypeLink(varDecl.typeExpr, context.checker, varDecl.init == null); + varDecl.sym = fieldSymbol; + } + return false; + } + TypeScript.preCollectVarDeclTypes = preCollectVarDeclTypes; + function preCollectFuncDeclTypes(ast, parent, context) { + var scopeChain = context.scopeChain; + if(context.scopeChain.moduleDecl) { + context.scopeChain.moduleDecl.recordNonInterface(); + } + var funcDecl = ast; + var fgSym = null; + var nameText = funcDecl.getNameText(); + var isExported = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Exported | TypeScript.FncFlags.ClassPropertyMethodExported); + var isStatic = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static); + var isPrivate = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Private); + var isConstructor = funcDecl.isConstructMember() || funcDecl.isConstructor; + var containerSym = (((funcDecl.isMethod() && isStatic) || funcDecl.isAccessor()) && context.scopeChain.classType ? context.scopeChain.classType.symbol : context.scopeChain.container); + var containerScope = context.scopeChain.scope; + var isGlobal = containerSym == context.checker.gloMod; + var isOptional = funcDecl.name && TypeScript.hasFlag(funcDecl.name.flags, TypeScript.ASTFlags.OptionalName); + var go = false; + var foundSymbol = false; + if(isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { + containerSym = containerSym.container; + containerScope = scopeChain.previous.scope; + } + funcDecl.unitIndex = context.checker.locationInfo.unitIndex; + if(!funcDecl.isConstructor && containerSym && containerSym.declAST && containerSym.declAST.nodeType == TypeScript.NodeType.FuncDecl && (containerSym.declAST).isConstructor && !funcDecl.isMethod()) { + return go; + } + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Signature)) { + var instType = context.scopeChain.thisType; + if(nameText && nameText != "__missing") { + if(isStatic) { + fgSym = containerSym.type.members.allMembers.lookup(nameText); + } else { + fgSym = containerScope.findLocal(nameText, false, false); + if(fgSym == null) { + fgSym = containerScope.findLocal(nameText, false, true); + } + } + if(fgSym) { + foundSymbol = true; + if(!funcDecl.isSignature() && (TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Ambient) != TypeScript.hasFlag(fgSym.flags, TypeScript.SymbolFlags.Ambient))) { + fgSym = null; + } + } + } + if(fgSym == null) { + if(!(funcDecl.isSpecialFn())) { + fgSym = context.checker.createFunctionSignature(funcDecl, containerSym, containerScope, null, !foundSymbol).declAST.type.symbol; + } else { + fgSym = context.checker.createFunctionSignature(funcDecl, containerSym, containerScope, containerSym, false).declAST.type.symbol; + } + if(fgSym.declAST == null || !funcDecl.isSpecialFn()) { + fgSym.declAST = ast; + } + } else { + if((fgSym.kind() == TypeScript.SymbolKind.Type)) { + fgSym = context.checker.createFunctionSignature(funcDecl, containerSym, containerScope, fgSym, false).declAST.type.symbol; + } else { + context.checker.errorReporter.simpleError(funcDecl, "Function or method '" + funcDecl.name.actualText + "' already declared as a property"); + } + } + if(funcDecl.isSpecialFn() && !isStatic) { + funcDecl.type = instType ? instType : fgSym.type; + } else { + funcDecl.type = fgSym.type; + } + } else { + if(nameText) { + if(isStatic) { + fgSym = containerSym.type.members.allMembers.lookup(nameText); + } else { + if(funcDecl.isConstructor && context.scopeChain.previous) { + fgSym = context.scopeChain.previous.scope.findLocal(nameText, false, false); + } + if(fgSym == null) { + fgSym = containerScope.findLocal(nameText, false, false); + } + } + if(fgSym) { + foundSymbol = true; + if(!isConstructor && fgSym.declAST.nodeType == TypeScript.NodeType.FuncDecl && !(fgSym.declAST).isAccessor() && !(fgSym.declAST).isSignature()) { + fgSym = null; + foundSymbol = false; + } + } + } + if(fgSym && !fgSym.isAccessor() && fgSym.type && fgSym.type.construct && fgSym.type.construct.signatures != [] && (fgSym.type.construct.signatures[0].declAST == null || !TypeScript.hasFlag(fgSym.type.construct.signatures[0].declAST.fncFlags, TypeScript.FncFlags.Ambient)) && !funcDecl.isConstructor) { + context.checker.errorReporter.simpleError(funcDecl, "Functions may not have class overloads"); + } + if(fgSym && !(fgSym.kind() == TypeScript.SymbolKind.Type) && funcDecl.isMethod() && !funcDecl.isAccessor() && !funcDecl.isConstructor) { + context.checker.errorReporter.simpleError(funcDecl, "Function or method '" + funcDecl.name.actualText + "' already declared as a property"); + fgSym.type = context.checker.anyType; + } + var sig = context.checker.createFunctionSignature(funcDecl, containerSym, containerScope, fgSym, !foundSymbol); + if(((!fgSym || fgSym.declAST.nodeType != TypeScript.NodeType.FuncDecl) && funcDecl.isAccessor()) || (fgSym && fgSym.isAccessor())) { + funcDecl.accessorSymbol = context.checker.createAccessorSymbol(funcDecl, fgSym, containerSym.type, (funcDecl.isMethod() && isStatic), true, containerScope, containerSym); + } + funcDecl.type.symbol.declAST = ast; + if(funcDecl.isConstructor) { + go = true; + } + ; ; + } + if(isExported) { + if(funcDecl.type.call) { + funcDecl.type.symbol.flags |= TypeScript.SymbolFlags.Exported; + } + if(fgSym && !fgSym.isAccessor() && fgSym.kind() == TypeScript.SymbolKind.Type && fgSym.type.call) { + fgSym.flags |= TypeScript.SymbolFlags.Exported; + } + } + if(context.scopeChain.moduleDecl && !funcDecl.isSpecialFn()) { + funcDecl.type.symbol.flags |= TypeScript.SymbolFlags.ModuleMember; + funcDecl.type.symbol.declModule = context.scopeChain.moduleDecl; + } + if(fgSym && isOptional) { + fgSym.flags |= TypeScript.SymbolFlags.Optional; + } + return go; + } + TypeScript.preCollectFuncDeclTypes = preCollectFuncDeclTypes; + function preCollectTypes(ast, parent, walker) { + var context = walker.state; + var go = false; + var scopeChain = context.scopeChain; + if(ast.nodeType == TypeScript.NodeType.Script) { + var script = ast; + context.script = script; + go = true; + } else { + if(ast.nodeType == TypeScript.NodeType.List) { + go = true; + } else { + if(ast.nodeType == TypeScript.NodeType.ImportDeclaration) { + go = preCollectImportTypes(ast, parent, context); + } else { + if(ast.nodeType == TypeScript.NodeType.With) { + go = false; + } else { + if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { + go = preCollectModuleTypes(ast, parent, context); + } else { + if(ast.nodeType == TypeScript.NodeType.ClassDeclaration) { + go = preCollectClassTypes(ast, parent, context); + } else { + if(ast.nodeType == TypeScript.NodeType.Block) { + go = true; + } else { + if(ast.nodeType == TypeScript.NodeType.InterfaceDeclaration) { + go = preCollectInterfaceTypes(ast, parent, context); + } else { + if(ast.nodeType == TypeScript.NodeType.ArgDecl) { + go = preCollectArgDeclTypes(ast, parent, context); + } else { + if(ast.nodeType == TypeScript.NodeType.VarDecl) { + go = preCollectVarDeclTypes(ast, parent, context); + } else { + if(ast.nodeType == TypeScript.NodeType.FuncDecl) { + go = preCollectFuncDeclTypes(ast, parent, context); + } else { + if(ast.isStatementOrExpression() && context.scopeChain.moduleDecl) { + context.scopeChain.moduleDecl.recordNonInterface(); + } + } + } + } + } + } + } + } + } + } + } + } + walker.options.goChildren = go; + return ast; + } + TypeScript.preCollectTypes = preCollectTypes; + function postCollectTypes(ast, parent, walker) { + var context = walker.state; + if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { + TypeScript.popTypeCollectionScope(context); + } else { + if(ast.nodeType == TypeScript.NodeType.ClassDeclaration) { + TypeScript.popTypeCollectionScope(context); + } else { + if(ast.nodeType == TypeScript.NodeType.InterfaceDeclaration) { + TypeScript.popTypeCollectionScope(context); + } + } + } + return ast; + } + TypeScript.postCollectTypes = postCollectTypes; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ScopeChain = (function () { + function ScopeChain(container, previous, scope) { + this.container = container; + this.previous = previous; + this.scope = scope; + } + return ScopeChain; + })(); + TypeScript.ScopeChain = ScopeChain; + var BBUseDefInfo = (function () { + function BBUseDefInfo(bb) { + this.bb = bb; + this.defsBySymbol = new Array(); + this.useIndexBySymbol = new Array(); + } + BBUseDefInfo.prototype.updateTop = function () { + var temp = new BitVector(this.top.bitCount); + for(var i = 0, succLen = this.bb.successors.length; i < succLen; i++) { + var succ = this.bb.successors[i]; + if(succ.useDef) { + temp.union(succ.useDef.top); + } + } + temp.difference(this.kill); + temp.union(this.gen); + var changed = temp.notEq(this.top); + this.top = temp; + return changed; + }; + BBUseDefInfo.prototype.initialize = function (useDefContext) { + var _this = this; + var defSym = function (sym, context) { + if(context.isLocalSym(sym)) { + var index = context.getSymbolIndex(sym); + _this.useIndexBySymbol[index] = new Array(); + _this.defsBySymbol[index] = true; + } + }; + var useSym = function (sym, context, ast) { + if(context.isLocalSym(sym)) { + var symIndex = context.getSymbolIndex(sym); + if(_this.useIndexBySymbol[symIndex] == undefined) { + _this.useIndexBySymbol[symIndex] = new Array(); + } + var symUses = _this.useIndexBySymbol[symIndex]; + var astIndex = context.getUseIndex(ast); + context.addUse(symIndex, astIndex); + symUses.push(astIndex); + } + }; + function initUseDefPre(cur, parent, walker) { + var context = walker.state; + if(cur == null) { + cur = null; + } + if(cur.nodeType == TypeScript.NodeType.VarDecl) { + var varDecl = cur; + if(varDecl.init || TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.AutoInit)) { + defSym(varDecl.sym, context); + } + } else { + if(cur.nodeType == TypeScript.NodeType.Name) { + if(parent) { + if(parent.nodeType == TypeScript.NodeType.Asg) { + var asg = parent; + if(asg.operand1 == cur) { + return cur; + } + } else { + if(parent.nodeType == TypeScript.NodeType.VarDecl) { + var parentDecl = parent; + if(parentDecl.id == cur) { + return cur; + } + } + } + } + var id = cur; + useSym(id.sym, context, cur); + } else { + if((cur.nodeType >= TypeScript.NodeType.Asg) && (cur.nodeType <= TypeScript.NodeType.LastAsg)) { + var asg = cur; + if(asg.operand1 && (asg.operand1.nodeType == TypeScript.NodeType.Name)) { + var id = asg.operand1; + defSym(id.sym, context); + } + } else { + if(cur.nodeType == TypeScript.NodeType.FuncDecl) { + walker.options.goChildren = false; + } + } + } + } + return cur; + } + var options = new TypeScript.AstWalkOptions(); + options.reverseSiblings = true; + TypeScript.getAstWalkerFactory().walk(this.bb.content, initUseDefPre, null, options, useDefContext); + }; + BBUseDefInfo.prototype.initializeGen = function (useDefContext) { + var symbolLen = this.useIndexBySymbol.length; + var bitCount = useDefContext.uses.length; + this.gen = new BitVector(bitCount); + for(var s = 0; s < symbolLen; s++) { + var symUses = this.useIndexBySymbol[s]; + if((symUses != undefined) && (symUses.length > 0)) { + for(var u = 0, uLen = symUses.length; u < uLen; u++) { + this.gen.set(symUses[u], true); + } + } + } + this.top = this.gen; + }; + BBUseDefInfo.prototype.initializeKill = function (useDefContext) { + this.kill = new BitVector(this.gen.bitCount); + for(var s = 0, symbolLen = this.defsBySymbol.length; s < symbolLen; s++) { + if(this.defsBySymbol[s]) { + var globalSymUses = useDefContext.useIndexBySymbol[s]; + if(globalSymUses) { + for(var u = 0, useLen = globalSymUses.length; u < useLen; u++) { + this.kill.set(globalSymUses[u], true); + } + } + } + } + }; + return BBUseDefInfo; + })(); + TypeScript.BBUseDefInfo = BBUseDefInfo; + var UseDefContext = (function () { + function UseDefContext() { + this.useIndexBySymbol = new Array(); + this.uses = new Array(); + this.symbols = new Array(); + this.symbolMap = new TypeScript.StringHashTable(); + this.symbolCount = 0; + } + UseDefContext.prototype.getSymbolIndex = function (sym) { + var name = sym.name; + var index = (this.symbolMap.lookup(name)); + if(index == null) { + index = this.symbolCount++; + this.symbols[index] = sym; + this.symbolMap.add(name, index); + } + return index; + }; + UseDefContext.prototype.addUse = function (symIndex, astIndex) { + var useBySym = this.useIndexBySymbol[symIndex]; + if(useBySym == undefined) { + useBySym = new Array(); + this.useIndexBySymbol[symIndex] = useBySym; + } + useBySym[useBySym.length] = astIndex; + }; + UseDefContext.prototype.getUseIndex = function (ast) { + this.uses[this.uses.length] = ast; + return this.uses.length - 1; + }; + UseDefContext.prototype.isLocalSym = function (sym) { + return (sym && (sym.container == this.func) && (sym.kind() == TypeScript.SymbolKind.Variable)); + }; + UseDefContext.prototype.killSymbol = function (sym, bbUses) { + var index = this.symbolMap.lookup(sym.name); + var usesOfSym = this.useIndexBySymbol[index]; + for(var k = 0, len = usesOfSym.length; k < len; k++) { + bbUses.set(usesOfSym[k], true); + } + }; + return UseDefContext; + })(); + TypeScript.UseDefContext = UseDefContext; + var BitVector = (function () { + function BitVector(bitCount) { + this.bitCount = bitCount; + this.firstBits = 0; + this.restOfBits = null; + if(this.bitCount > BitVector.packBits) { + this.restOfBits = new Array(); + var len = Math.floor(this.bitCount / BitVector.packBits); + for(var i = 0; i < len; i++) { + this.restOfBits[i] = 0; + } + } + } + BitVector.packBits = 30; + BitVector.prototype.set = function (bitIndex, value) { + if(bitIndex < BitVector.packBits) { + if(value) { + this.firstBits |= (1 << bitIndex); + } else { + this.firstBits &= (~(1 << bitIndex)); + } + } else { + var offset = Math.floor(bitIndex / BitVector.packBits) - 1; + var localIndex = bitIndex % BitVector.packBits; + if(value) { + this.restOfBits[offset] |= (1 << localIndex); + } else { + this.restOfBits[offset] &= (~(1 << localIndex)); + } + } + }; + BitVector.prototype.map = function (fn) { + var k; + for(k = 0; k < BitVector.packBits; k++) { + if(k == this.bitCount) { + return; + } + if(((1 << k) & this.firstBits) != 0) { + fn(k); + } + } + if(this.restOfBits) { + var len; + var cumu = BitVector.packBits; + for(k = 0 , len = this.restOfBits.length; k < len; k++) { + var myBits = this.restOfBits[k]; + for(var j = 0; j < BitVector.packBits; j++) { + if(((1 << j) & myBits) != 0) { + fn(cumu); + } + cumu++; + if(cumu == this.bitCount) { + return; + } + } + } + } + }; + BitVector.prototype.union = function (b) { + this.firstBits |= b.firstBits; + if(this.restOfBits) { + for(var k = 0, len = this.restOfBits.length; k < len; k++) { + var myBits = this.restOfBits[k]; + var bBits = b.restOfBits[k]; + this.restOfBits[k] = myBits | bBits; + } + } + }; + BitVector.prototype.intersection = function (b) { + this.firstBits &= b.firstBits; + if(this.restOfBits) { + for(var k = 0, len = this.restOfBits.length; k < len; k++) { + var myBits = this.restOfBits[k]; + var bBits = b.restOfBits[k]; + this.restOfBits[k] = myBits & bBits; + } + } + }; + BitVector.prototype.notEq = function (b) { + if(this.firstBits != b.firstBits) { + return true; + } + if(this.restOfBits) { + for(var k = 0, len = this.restOfBits.length; k < len; k++) { + var myBits = this.restOfBits[k]; + var bBits = b.restOfBits[k]; + if(myBits != bBits) { + return true; + } + } + } + return false; + }; + BitVector.prototype.difference = function (b) { + var oldFirstBits = this.firstBits; + this.firstBits &= (~b.firstBits); + if(this.restOfBits) { + for(var k = 0, len = this.restOfBits.length; k < len; k++) { + var myBits = this.restOfBits[k]; + var bBits = b.restOfBits[k]; + this.restOfBits[k] &= (~bBits); + } + } + }; + return BitVector; + })(); + TypeScript.BitVector = BitVector; + var BasicBlock = (function () { + function BasicBlock() { + this.predecessors = new Array(); + this.index = -1; + this.markValue = 0; + this.successors = new Array(); + this.useDef = null; + this.content = new TypeScript.ASTList(); + } + BasicBlock.prototype.marked = function (markBase) { + return this.markValue > markBase; + }; + BasicBlock.prototype.mark = function () { + this.markValue++; + }; + BasicBlock.prototype.addSuccessor = function (successor) { + this.successors[this.successors.length] = successor; + successor.predecessors[successor.predecessors.length] = this; + }; + return BasicBlock; + })(); + TypeScript.BasicBlock = BasicBlock; + var ControlFlowContext = (function () { + function ControlFlowContext(current, exit) { + this.current = current; + this.exit = exit; + this.entry = null; + this.unreachable = null; + this.noContinuation = false; + this.statementStack = new Array(); + this.currentSwitch = new Array(); + this.markBase = 0; + this.linearBBs = new Array(); + this.entry = this.current; + } + ControlFlowContext.prototype.walk = function (ast, parent) { + return this.walker.walk(ast, parent); + }; + ControlFlowContext.prototype.pushSwitch = function (bb) { + this.currentSwitch.push(bb); + }; + ControlFlowContext.prototype.popSwitch = function () { + return this.currentSwitch.pop(); + }; + ControlFlowContext.prototype.reportUnreachable = function (er) { + if(this.unreachable && (this.unreachable.length > 0)) { + var len = this.unreachable.length; + for(var i = 0; i < len; i++) { + var unreachableAST = this.unreachable[i]; + if(unreachableAST.nodeType != TypeScript.NodeType.EndCode) { + er.simpleError(unreachableAST, "unreachable code"); + } + } + } + }; + ControlFlowContext.prototype.printAST = function (ast, outfile) { + var printContext = new TypeScript.PrintContext(outfile, null); + printContext.increaseIndent(); + TypeScript.getAstWalkerFactory().walk(ast, TypeScript.prePrintAST, TypeScript.postPrintAST, null, printContext); + printContext.decreaseIndent(); + }; + ControlFlowContext.prototype.printBlockContent = function (bb, outfile) { + var content = bb.content; + for(var i = 0, len = content.members.length; i < len; i++) { + var ast = content.members[i]; + this.printAST(ast, outfile); + } + }; + ControlFlowContext.prototype.bfs = function (nodeFunc, edgeFunc, preEdges, postEdges) { + var markValue = this.markBase++; + var q = new Array(); + q[q.length] = this.entry; + while(q.length > 0) { + var bb = q.pop(); + if(!(bb.marked(markValue))) { + bb.mark(); + if(nodeFunc) { + nodeFunc(bb); + } + var succLen = bb.successors.length; + if(succLen > 0) { + if(preEdges) { + preEdges(); + } + for(var j = succLen - 1; j >= 0; j--) { + var successor = bb.successors[j]; + if(!(successor.marked(this.markBase))) { + if(edgeFunc) { + edgeFunc(bb, successor); + } + q[q.length] = successor; + } + } + if(postEdges) { + postEdges(); + } + } + } + } + }; + ControlFlowContext.prototype.useDef = function (er, funcSym) { + var _this = this; + var useDefContext = new UseDefContext(); + useDefContext.func = funcSym; + var useDefInit = function (bb) { + bb.useDef = new BBUseDefInfo(bb); + bb.useDef.initialize(useDefContext); + _this.linearBBs[_this.linearBBs.length] = bb; + }; + this.bfs(useDefInit, null, null, null); + var i, bbLen; + for(i = 0 , bbLen = this.linearBBs.length; i < bbLen; i++) { + this.linearBBs[i].useDef.initializeGen(useDefContext); + this.linearBBs[i].useDef.initializeKill(useDefContext); + } + var changed = true; + while(changed) { + changed = false; + for(i = 0; i < bbLen; i++) { + changed = this.linearBBs[i].useDef.updateTop() || changed; + } + } + var top = this.entry.useDef.top; + top.map(function (index) { + var ast = useDefContext.uses[index]; + er.simpleError(ast, "use of variable '" + ast.actualText + "' that is not definitely assigned"); + }); + }; + ControlFlowContext.prototype.print = function (outfile) { + var _this = this; + var index = 0; + var node = function (bb) { + if(bb.index < 0) { + bb.index = index++; + } + if(bb == _this.exit) { + outfile.WriteLine("Exit block with index " + bb.index); + } else { + outfile.WriteLine("Basic block with index " + bb.index); + _this.printBlockContent(bb, outfile); + } + }; + function preEdges() { + outfile.Write(" Branches to "); + } + function postEdges() { + outfile.WriteLine(""); + } + function edge(node1, node2) { + if(node2.index < 0) { + node2.index = index++; + } + outfile.Write(node2.index + " "); + } + this.bfs(node, edge, preEdges, postEdges); + if(this.unreachable != null) { + for(var i = 0, len = this.unreachable.length; i < len; i++) { + outfile.WriteLine("Unreachable basic block ..."); + this.printAST(this.unreachable[i], outfile); + } + } + }; + ControlFlowContext.prototype.pushStatement = function (stmt, continueBB, breakBB) { + this.statementStack.push({ + stmt: stmt, + continueBB: continueBB, + breakBB: breakBB + }); + }; + ControlFlowContext.prototype.popStatement = function () { + return this.statementStack.pop(); + }; + ControlFlowContext.prototype.returnStmt = function () { + this.current.addSuccessor(this.exit); + this.setUnreachable(); + }; + ControlFlowContext.prototype.setUnreachable = function () { + this.current = null; + this.noContinuation = true; + }; + ControlFlowContext.prototype.addUnreachable = function (ast) { + if(this.unreachable === null) { + this.unreachable = new Array(); + } + this.unreachable[this.unreachable.length] = ast; + }; + ControlFlowContext.prototype.unconditionalBranch = function (target, isContinue) { + var targetBB = null; + for(var i = 0, len = this.statementStack.length; i < len; i++) { + var targetInfo = this.statementStack[i]; + if(targetInfo.stmt == target) { + if(isContinue) { + targetBB = targetInfo.continueBB; + } else { + targetBB = targetInfo.breakBB; + } + break; + } + } + if(targetBB) { + this.current.addSuccessor(targetBB); + } + this.setUnreachable(); + }; + ControlFlowContext.prototype.addContent = function (ast) { + if(this.current) { + this.current.content.append(ast); + } + }; + return ControlFlowContext; + })(); + TypeScript.ControlFlowContext = ControlFlowContext; + var ResolutionDataCache = (function () { + function ResolutionDataCache() { + this.cacheSize = 16; + this.rdCache = []; + this.nextUp = 0; + for(var i = 0; i < this.cacheSize; i++) { + this.rdCache[i] = { + actuals: new Array(), + exactCandidates: new Array(), + conversionCandidates: new Array(), + id: i + }; + } + } + ResolutionDataCache.prototype.getResolutionData = function () { + var rd = null; + if(this.nextUp < this.cacheSize) { + rd = this.rdCache[this.nextUp]; + } + if(rd == null) { + this.cacheSize++; + rd = { + actuals: new Array(), + exactCandidates: new Array(), + conversionCandidates: new Array(), + id: this.cacheSize + }; + this.rdCache[this.cacheSize] = rd; + } + this.nextUp++; + return rd; + }; + ResolutionDataCache.prototype.returnResolutionData = function (rd) { + rd.actuals.length = 0; + rd.exactCandidates.length = 0; + rd.conversionCandidates.length = 0; + this.nextUp = rd.id; + }; + return ResolutionDataCache; + })(); + TypeScript.ResolutionDataCache = ResolutionDataCache; + var TypeFlow = (function () { + function TypeFlow(logger, initScope, parser, checker) { + this.logger = logger; + this.initScope = initScope; + this.parser = parser; + this.checker = checker; + this.thisFnc = null; + this.thisClassNode = null; + this.enclosingFncIsMethod = false; + this.arrayInterfaceType = null; + this.stringInterfaceType = null; + this.objectInterfaceType = null; + this.functionInterfaceType = null; + this.numberInterfaceType = null; + this.booleanInterfaceType = null; + this.iargumentsInterfaceType = null; + this.currentScript = null; + this.inImportTypeCheck = false; + this.inTypeRefTypeCheck = false; + this.inArrayElementTypeCheck = false; + this.resolutionDataCache = new ResolutionDataCache(); + this.nestingLevel = 0; + this.inSuperCall = false; + this.checker.typeFlow = this; + this.scope = this.initScope; + this.globalScope = this.initScope; + this.doubleType = this.checker.numberType; + this.booleanType = this.checker.booleanType; + this.stringType = this.checker.stringType; + this.anyType = this.checker.anyType; + this.regexType = this.anyType; + this.nullType = this.checker.nullType; + this.voidType = this.checker.voidType; + this.arrayAnyType = this.checker.makeArrayType(this.anyType); + } + TypeFlow.prototype.initLibs = function () { + var arraySym = this.globalScope.find("Array", false, true); + if(arraySym && (arraySym.kind() == TypeScript.SymbolKind.Type)) { + this.arrayInterfaceType = (arraySym).type; + } + var stringSym = this.globalScope.find("String", false, true); + if(stringSym && (stringSym.kind() == TypeScript.SymbolKind.Type)) { + this.stringInterfaceType = (stringSym).type; + } + var objectSym = this.globalScope.find("Object", false, true); + if(objectSym && (objectSym.kind() == TypeScript.SymbolKind.Type)) { + this.objectInterfaceType = (objectSym).type; + } + var fnSym = this.globalScope.find("Function", false, true); + if(fnSym && (fnSym.kind() == TypeScript.SymbolKind.Type)) { + this.functionInterfaceType = (fnSym).type; + } + var numberSym = this.globalScope.find("Number", false, true); + if(numberSym && (numberSym.kind() == TypeScript.SymbolKind.Type)) { + this.numberInterfaceType = (numberSym).type; + } + var booleanSym = this.globalScope.find("Boolean", false, true); + if(booleanSym && (booleanSym.kind() == TypeScript.SymbolKind.Type)) { + this.booleanInterfaceType = (booleanSym).type; + } + var regexSym = this.globalScope.find("RegExp", false, true); + if(regexSym && (regexSym.kind() == TypeScript.SymbolKind.Type)) { + this.regexType = (regexSym).type; + } + }; + TypeFlow.prototype.cast = function (ast, type) { + return this.castWithCoercion(ast, type, true, false); + }; + TypeFlow.prototype.castWithCoercion = function (ast, type, applyCoercion, typeAssertion) { + var comparisonInfo = new TypeScript.TypeComparisonInfo(); + if(this.checker.sourceIsAssignableToTarget(ast.type, type, comparisonInfo) || (typeAssertion && this.checker.sourceIsAssignableToTarget(type, ast.type, comparisonInfo))) { + if(applyCoercion) { + if(type == null) { + ast.type = this.anyType; + } else { + if(type.isClass()) { + ast.type = type.instanceType; + } else { + ast.type = type; + } + } + } + return ast; + } else { + this.checker.errorReporter.incompatibleTypes(ast, ast.type, type, null, this.scope, comparisonInfo); + return ast; + } + }; + TypeFlow.prototype.inScopeTypeCheck = function (ast, enclosingScope) { + var prevScope = this.scope; + this.scope = enclosingScope; + var svThisFnc = this.thisFnc; + var svThisType = this.thisType; + var svThisClassNode = this.thisClassNode; + var svCurrentModDecl = this.checker.currentModDecl; + var prevMethodStatus = this.enclosingFncIsMethod; + var container = this.scope.container; + var fnc = null; + while(container) { + if(container.kind() == TypeScript.SymbolKind.Type) { + var typeSym = container; + var type = typeSym.type; + if(type.call) { + if(fnc == null) { + this.enclosingFncIsMethod = typeSym.isMethod; + fnc = container.declAST; + } + } + if(type.isClass()) { + this.thisType = type.instanceType; + if(typeSym.declAST && (typeSym.declAST.nodeType == TypeScript.NodeType.ClassDeclaration)) { + this.thisClassNode = typeSym.declAST; + } + break; + } + if(type.isModuleType()) { + this.checker.currentModDecl = typeSym.declAST; + break; + } + } + container = container.container; + } + this.thisFnc = fnc; + var updated = this.typeCheck(ast); + this.thisFnc = svThisFnc; + this.thisType = svThisType; + this.thisClassNode = svThisClassNode; + this.checker.currentModDecl = svCurrentModDecl; + this.enclosingFncIsMethod = prevMethodStatus; + this.scope = prevScope; + return updated; + }; + TypeFlow.prototype.typeCheck = function (ast) { + if(ast) { + return ast.typeCheck(this); + } else { + return null; + } + }; + TypeFlow.prototype.inScopeTypeCheckDecl = function (ast) { + if(ast.nodeType == TypeScript.NodeType.VarDecl || ast.nodeType == TypeScript.NodeType.ArgDecl) { + this.inScopeTypeCheckBoundDecl(ast); + } else { + if(ast.nodeType == TypeScript.NodeType.FuncDecl) { + var funcDecl = ast; + if(funcDecl.isAccessor()) { + this.typeCheckFunction(funcDecl); + } + } + } + }; + TypeFlow.prototype.inScopeTypeCheckBoundDecl = function (varDecl) { + var sym = varDecl.sym; + var svThisFnc = this.thisFnc; + var svThisType = this.thisType; + var prevMethodStatus = this.enclosingFncIsMethod; + var prevLocationInfo = this.checker.locationInfo; + if(sym && sym.container) { + var instanceScope = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.ClassConstructorProperty) ? sym.container.getType().constructorScope : sym.container.instanceScope(); + if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Property) && sym.container.declAST.nodeType == TypeScript.NodeType.FuncDecl) { + this.thisFnc = sym.container.declAST; + } + if(instanceScope) { + var prevScope = this.scope; + this.scope = instanceScope; + var container = sym.container; + if(this.checker.units && (sym.unitIndex >= 0) && (sym.unitIndex < this.checker.units.length)) { + this.checker.locationInfo = this.checker.units[sym.unitIndex]; + } else { + this.checker.locationInfo = TypeScript.unknownLocationInfo; + } + while(container) { + if(container.kind() == TypeScript.SymbolKind.Type) { + var typeSym = container; + var type = typeSym.type; + if(type.call) { + this.enclosingFncIsMethod = typeSym.isMethod; + } + if(type.isClass()) { + this.thisType = type.instanceType; + break; + } + } + container = container.container; + } + this.typeCheckBoundDecl(varDecl); + this.scope = prevScope; + } + } + this.thisFnc = svThisFnc; + this.thisType = svThisType; + this.checker.locationInfo = prevLocationInfo; + this.enclosingFncIsMethod = prevMethodStatus; + }; + TypeFlow.prototype.resolveBoundDecl = function (varDecl) { + if(varDecl.typeExpr) { + if(varDecl.typeExpr.type == null || (varDecl.typeExpr.type && varDecl.typeExpr.type == this.anyType && this.scope) || varDecl.typeExpr.type.symbol == null || !this.checker.typeStatusIsFinished(varDecl.typeExpr.type.symbol.typeCheckStatus)) { + this.typeCheck(varDecl.typeExpr); + } + varDecl.type = varDecl.typeExpr.type; + if(varDecl.sym) { + varDecl.sym.setType(varDecl.type); + } + } else { + if(varDecl.init == null) { + if(this.checker.styleSettings.implicitAny) { + this.checker.errorReporter.styleError(varDecl, "type implicitly set to 'any'"); + } + varDecl.type = this.anyType; + if(varDecl.sym) { + if(varDecl.sym.isType()) { + var tsym = varDecl.sym; + if(tsym.isMethod) { + this.checker.errorReporter.simpleError(varDecl, "Cannot bind method group to variable. (Did you mean to use 'declare function' instead of 'declare var'?)"); + return; + } else { + this.checker.errorReporter.simpleError(varDecl, "Cannot bind type to variable"); + return; + } + } + varDecl.sym.setType(varDecl.type); + } + } + } + }; + TypeFlow.prototype.typeCheckBoundDecl = function (varDecl) { + var _this = this; + var infSym = varDecl.sym; + if(infSym == null) { + if(varDecl.init) { + varDecl.init = this.typeCheck(varDecl.init); + varDecl.type = this.checker.widenType(varDecl.init.type); + } else { + if(this.checker.styleSettings.implicitAny) { + this.checker.errorReporter.styleError(varDecl, "type implicitly set to 'any'"); + } + varDecl.type = this.anyType; + } + } else { + if(infSym.typeCheckStatus == TypeScript.TypeCheckStatus.Started) { + if(this.checker.styleSettings.implicitAny) { + this.checker.errorReporter.styleError(varDecl, "type implicitly set to 'any'"); + } + varDecl.type = this.anyType; + infSym.setType(this.anyType); + } else { + if(infSym.typeCheckStatus == TypeScript.TypeCheckStatus.NotStarted) { + infSym.typeCheckStatus = TypeScript.TypeCheckStatus.Started; + this.checker.addStartedPTO(infSym); + var resolved = false; + if(varDecl.type == null) { + if(varDecl.typeExpr) { + this.resolveBoundDecl(varDecl); + resolved = true; + varDecl.type = varDecl.typeExpr.type; + infSym.typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); + } + } + if(varDecl.init) { + var isLocalStatic = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.LocalStatic); + var prevScope = this.scope; + var applyTargetType = !varDecl.init.isParenthesized; + if(isLocalStatic) { + this.scope = varDecl.sym.container.getType().memberScope; + } + if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Property) && this.thisClassNode) { + TypeScript.getAstWalkerFactory().walk(varDecl.init, function (ast, parent, walker) { + if(ast && ast.nodeType == TypeScript.NodeType.FuncDecl) { + if(TypeScript.hasFlag((ast).fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { + (ast).fncFlags |= TypeScript.FncFlags.IsPropertyBound; + } + walker.options.goChildren = false; + } + return ast; + }); + } + this.checker.typeCheckWithContextualType(varDecl.type, this.checker.inProvisionalTypecheckMode(), applyTargetType, varDecl.init); + this.scope = prevScope; + if(varDecl.type) { + var preserveScope = false; + var preservedContainedScope = null; + if(varDecl.init.type) { + preservedContainedScope = varDecl.init.type.containedScope; + preserveScope = true; + if(varDecl.init.type == this.voidType) { + this.checker.errorReporter.simpleError(varDecl, "Cannot assign type 'void' to variable '" + varDecl.id.actualText + "'"); + } + } + varDecl.init = this.castWithCoercion(varDecl.init, varDecl.type, applyTargetType && !this.checker.inProvisionalTypecheckMode(), false); + if(preserveScope && varDecl.init.type.containedScope == null) { + varDecl.init.type.containedScope = preservedContainedScope; + } + } else { + varDecl.type = this.checker.widenType(varDecl.init.type); + if(varDecl.type == this.voidType) { + this.checker.errorReporter.simpleError(varDecl, "Cannot assign type 'void' to variable '" + varDecl.id.actualText + "'"); + varDecl.type = this.anyType; + } + } + infSym.setType(varDecl.type); + } else { + if(!resolved) { + this.resolveBoundDecl(varDecl); + } + } + infSym.typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); + } else { + if(this.checker.typeStatusIsFinished(infSym.typeCheckStatus) && (infSym.declAST != varDecl)) { + if(varDecl.init) { + varDecl.init = this.typeCheck(varDecl.init); + varDecl.type = infSym.getType(); + varDecl.init = this.cast(varDecl.init, varDecl.type); + } + } + } + } + } + if(varDecl.id && varDecl.sym) { + varDecl.id.sym = varDecl.sym; + } + if(varDecl.sym && varDecl.sym.container) { + this.checkTypePrivacy(varDecl.sym.getType(), varDecl.sym, function (typeName, isModuleName) { + return _this.varPrivacyErrorReporter(varDecl, typeName, isModuleName); + }); + } + return varDecl; + }; + TypeFlow.prototype.varPrivacyErrorReporter = function (varDecl, typeName, isModuleName) { + var typestring = ""; + if(isModuleName) { + var quotestring = ""; + if(!TypeScript.isQuoted(typeName)) { + quotestring = "'"; + } + typestring = " is using inaccessible module " + quotestring + typeName + quotestring; + } else { + typestring = " has or is using private type '" + typeName + "'"; + } + if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Public)) { + if(varDecl.sym.container.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) { + this.checker.errorReporter.simpleError(varDecl, "property '" + varDecl.sym.name + "' of exported interface" + typestring); + } else { + this.checker.errorReporter.simpleError(varDecl, "public member '" + varDecl.sym.name + "' of exported class" + typestring); + } + } else { + this.checker.errorReporter.simpleError(varDecl, "exported variable '" + varDecl.sym.name + "'" + typestring); + } + }; + TypeFlow.prototype.typeCheckSuper = function (ast) { + if(this.thisType && (this.enclosingFncIsMethod && !this.thisFnc.isStatic()) && this.thisType.baseClass()) { + ast.type = this.thisType.baseClass(); + } else { + if(!this.enclosingFncIsMethod && this.thisType && this.thisType.baseClass() && this.thisFnc && TypeScript.hasFlag(this.thisFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { + var enclosingFnc = this.thisFnc.enclosingFnc; + while(TypeScript.hasFlag(enclosingFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { + enclosingFnc = enclosingFnc.enclosingFnc; + } + if(enclosingFnc && (enclosingFnc.isMethod() || enclosingFnc.isConstructor) && !enclosingFnc.isStatic()) { + ast.type = this.thisType.baseClass(); + enclosingFnc.setHasSuperReferenceInFatArrowFunction(); + return ast; + } + } + ast.type = this.anyType; + this.checker.errorReporter.invalidSuperReference(ast); + } + return ast; + }; + TypeFlow.prototype.typeCheckThis = function (ast) { + ast.type = this.anyType; + var illegalThisRef = false; + if(this.thisFnc == null) { + if(this.thisType) { + if(this.thisClassNode && this.thisClassNode.nodeType == TypeScript.NodeType.ClassDeclaration) { + illegalThisRef = true; + } else { + ast.type = this.thisType; + } + } else { + if(this.checker.currentModDecl) { + this.checker.errorReporter.simpleError(ast, "'this' may not be referenced within module bodies"); + } + } + } else { + if(this.thisClassNode && (TypeScript.hasFlag(this.thisFnc.fncFlags, TypeScript.FncFlags.IsPropertyBound) || (this.inSuperCall && TypeScript.hasFlag((this.thisClassNode).varFlags, TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor)))) { + illegalThisRef = true; + } + if(this.thisFnc.isMethod() || this.thisFnc.isConstructor || this.thisFnc.isTargetTypedAsMethod) { + if(this.thisType && !(this.thisFnc.fncFlags & TypeScript.FncFlags.Static)) { + ast.type = this.thisType; + } + } + } + if(!this.enclosingFncIsMethod && this.thisFnc && TypeScript.hasFlag(this.thisFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { + if(this.thisFnc.boundToProperty) { + var container = this.thisFnc.boundToProperty.sym.container; + if(container.declAST.nodeType == TypeScript.NodeType.FuncDecl) { + (container.declAST).setHasSelfReference(); + } + } else { + var encFnc = this.thisFnc.enclosingFnc; + var firstEncFnc = encFnc; + while(encFnc) { + if(this.thisClassNode && TypeScript.hasFlag(encFnc.fncFlags, TypeScript.FncFlags.IsPropertyBound)) { + illegalThisRef = true; + } + if(!TypeScript.hasFlag(encFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction) || encFnc.hasSelfReference()) { + encFnc.setHasSelfReference(); + break; + } + encFnc = encFnc.enclosingFnc; + } + if(!encFnc && firstEncFnc) { + encFnc = firstEncFnc; + encFnc.setHasSelfReference(); + } else { + if(!encFnc) { + if(this.thisClassNode) { + (this.thisClassNode).varFlags |= TypeScript.VarFlags.MustCaptureThis; + } else { + if(this.checker.currentModDecl) { + this.checker.currentModDecl.modFlags |= TypeScript.ModuleFlags.MustCaptureThis; + } else { + this.checker.mustCaptureGlobalThis = true; + } + } + } + } + if(encFnc && (encFnc.isMethod() || encFnc.isConstructor) && this.thisType && !TypeScript.hasFlag(encFnc.fncFlags, TypeScript.FncFlags.Static)) { + ast.type = this.thisType; + } + } + } + if(illegalThisRef) { + this.checker.errorReporter.simpleError(ast, "Keyword 'this' cannot be referenced in initializers in a class body, or in super constructor calls"); + } + return ast; + }; + TypeFlow.prototype.setTypeFromSymbol = function (ast, symbol) { + if(symbol.isVariable()) { + if(symbol.isInferenceSymbol()) { + var infSym = symbol; + if(infSym.declAST && !this.checker.typeStatusIsFinished(infSym.typeCheckStatus)) { + this.inScopeTypeCheckDecl(infSym.declAST); + } + if(!this.checker.styleSettings.innerScopeDeclEscape) { + if(infSym.declAST && (infSym.declAST.nodeType == TypeScript.NodeType.VarDecl)) { + if(this.nestingLevel < (infSym.declAST).nestingLevel) { + this.checker.errorReporter.styleError(ast, "Illegal reference to a variable defined in more nested scope"); + } + } + } + } + ast.type = symbol.getType(); + if(!symbol.writeable()) { + ast.flags = ast.flags & (~(TypeScript.ASTFlags.Writeable)); + } + } else { + if(symbol.isType()) { + ast.type = symbol.getType(); + ast.flags = ast.flags & (~(TypeScript.ASTFlags.Writeable)); + } else { + ast.type = this.anyType; + this.checker.errorReporter.symbolDoesNotReferToAValue(ast, symbol.name); + } + } + }; + TypeFlow.prototype.typeCheckName = function (ast) { + var _this = this; + var identifier = ast; + if(this.checker.inWith) { + identifier.type = this.anyType; + } else { + var typespace = this.inTypeRefTypeCheck; + var idText = identifier.text; + var originalIdText = idText; + var isDynamicModuleName = TypeScript.isQuoted(identifier.text); + var symbol = this.scope.find(idText, false, typespace); + if(symbol == null && isDynamicModuleName) { + symbol = this.checker.findSymbolForDynamicModule(idText, this.currentScript.locationInfo.filename, function (id) { + return _this.scope.find(id, false, typespace); + }); + } + if(!symbol) { + if(!identifier.isMissing()) { + this.checker.errorReporter.unresolvedSymbol(identifier, identifier.text); + } + identifier.type = this.anyType; + } else { + if(TypeScript.optimizeModuleCodeGen && symbol && symbol.isType()) { + var symType = symbol.getType(); + if(symType && (symbol).aliasLink && (symbol).onlyReferencedAsTypeRef) { + var modDecl = symType.symbol.declAST; + if(modDecl && TypeScript.hasFlag(modDecl.modFlags, TypeScript.ModuleFlags.IsDynamic)) { + (symbol).onlyReferencedAsTypeRef = this.inTypeRefTypeCheck; + } + } + } + if(symbol.declAST && symbol.declAST.nodeType == TypeScript.NodeType.FuncDecl && !(symbol.declAST).returnTypeAnnotation && (symbol.declAST).signature.typeCheckStatus == TypeScript.TypeCheckStatus.Started) { + (symbol.declAST).type.symbol.flags |= TypeScript.SymbolFlags.RecursivelyReferenced; + (symbol.declAST).signature.returnType.type = this.anyType; + } + this.setTypeFromSymbol(ast, symbol); + identifier.sym = symbol; + if(this.thisFnc) { + if(this.thisFnc.type && symbol.container != this.thisFnc.type.symbol) { + this.thisFnc.freeVariables[this.thisFnc.freeVariables.length] = symbol; + } + } + } + } + return ast; + }; + TypeFlow.prototype.typeCheckScript = function (script) { + this.checker.locationInfo = script.locationInfo; + this.scope = this.checker.globalScope; + if(!script.topLevelMod) { + this.addLocalsFromScope(this.scope, this.checker.gloMod, script.vars, this.checker.globals, true); + } + this.currentScript = script; + script.bod = this.typeCheck(script.bod); + this.currentScript = null; + return script; + }; + TypeFlow.prototype.typeCheckBitNot = function (ast) { + var unex = ast; + unex.operand = this.typeCheck(unex.operand); + unex.type = this.doubleType; + return unex; + }; + TypeFlow.prototype.typeCheckUnaryNumberOperator = function (ast) { + var unex = ast; + unex.operand = this.typeCheck(unex.operand); + unex.type = this.doubleType; + return ast; + }; + TypeFlow.prototype.typeCheckLogNot = function (ast) { + var unex = ast; + unex.operand = this.typeCheck(unex.operand); + unex.type = this.booleanType; + return unex; + }; + TypeFlow.prototype.astIsWriteable = function (ast) { + return TypeScript.hasFlag(ast.flags, TypeScript.ASTFlags.Writeable); + }; + TypeFlow.prototype.typeCheckIncOrDec = function (ast) { + var unex = ast; + var lval = unex.operand; + if(!this.astIsWriteable(unex)) { + this.checker.errorReporter.valueCannotBeModified(unex); + unex.type = this.doubleType; + } else { + unex = this.typeCheckUnaryNumberOperator(ast); + if(unex.operand.type != this.checker.numberType && unex.operand.type != this.checker.anyType && !(unex.operand.type.typeFlags & TypeScript.TypeFlags.IsEnum)) { + this.checker.errorReporter.simpleError(ast, "'++' and '--' may only be applied to operands of type 'number' or 'any'"); + } + } + return unex; + }; + TypeFlow.prototype.typeCheckBitwiseOperator = function (ast, assignment) { + var binex = ast; + var resultType = null; + binex.operand1 = this.typeCheck(binex.operand1); + binex.operand2 = this.typeCheck(binex.operand2); + var leftType = binex.operand1.type; + var rightType = binex.operand2.type; + if(assignment && (!this.astIsWriteable(binex))) { + this.checker.errorReporter.valueCannotBeModified(binex); + } + if(this.checker.styleSettings.bitwise) { + this.checker.errorReporter.styleError(ast, "use of " + TypeScript.nodeTypeTable[binex.nodeType]); + } + if(this.checker.sourceIsSubtypeOfTarget(leftType, this.doubleType) && (this.checker.sourceIsSubtypeOfTarget(rightType, this.doubleType))) { + resultType = this.doubleType; + } else { + if((leftType == this.booleanType) && (rightType == this.booleanType)) { + resultType = this.booleanType; + } else { + if(leftType == this.anyType) { + if((rightType == this.anyType) || (rightType == this.doubleType) || (rightType == this.booleanType)) { + resultType = this.anyType; + } + } else { + if(rightType == this.anyType) { + if((leftType == this.anyType) || (leftType == this.doubleType) || (leftType == this.booleanType)) { + resultType = this.anyType; + } + } + } + } + } + if(resultType == null) { + resultType = this.anyType; + this.checker.errorReporter.incompatibleTypes(binex, leftType, rightType, binex.printLabel(), this.scope); + } + binex.type = resultType; + return binex; + }; + TypeFlow.prototype.typeCheckArithmeticOperator = function (ast, assignment) { + var binex = ast; + binex.operand1 = this.typeCheck(binex.operand1); + binex.operand2 = this.typeCheck(binex.operand2); + var leftType = binex.operand1.type; + var rightType = binex.operand2.type; + if(assignment && (!this.astIsWriteable(binex.operand1))) { + this.checker.errorReporter.valueCannotBeModified(binex); + } + if(this.checker.styleSettings.bitwise && ((binex.nodeType == TypeScript.NodeType.And) || (binex.nodeType == TypeScript.NodeType.Or) || (binex.nodeType == TypeScript.NodeType.AsgAnd) || (binex.nodeType == TypeScript.NodeType.AsgOr))) { + this.checker.errorReporter.styleError(ast, "use of " + TypeScript.nodeTypeTable[binex.nodeType]); + } + if(leftType == null || rightType == null) { + this.checker.errorReporter.simpleError(binex, "Could not typecheck arithmetic operation. Possible recursive typecheck error?"); + binex.type = this.anyType; + return binex; + } + var nodeType = binex.nodeType; + if(this.checker.isNullOrUndefinedType(leftType)) { + leftType = rightType; + } + if(this.checker.isNullOrUndefinedType(rightType)) { + rightType = leftType; + } + leftType = this.checker.widenType(leftType); + rightType = this.checker.widenType(rightType); + if(nodeType == TypeScript.NodeType.Add || nodeType == TypeScript.NodeType.AsgAdd) { + if(leftType == this.checker.stringType || rightType == this.checker.stringType) { + binex.type = this.checker.stringType; + } else { + if(leftType == this.checker.numberType && rightType == this.checker.numberType) { + binex.type = this.checker.numberType; + } else { + if(this.checker.sourceIsSubtypeOfTarget(leftType, this.checker.numberType) && this.checker.sourceIsSubtypeOfTarget(rightType, this.checker.numberType)) { + binex.type = this.checker.numberType; + } else { + if(leftType == this.checker.anyType || rightType == this.checker.anyType) { + binex.type = this.checker.anyType; + } else { + binex.type = this.anyType; + this.checker.errorReporter.incompatibleTypes(binex, leftType, rightType, binex.printLabel(), this.scope); + } + } + } + } + } else { + if(leftType == this.checker.numberType && rightType == this.checker.numberType) { + binex.type = this.checker.numberType; + } else { + if(this.checker.sourceIsSubtypeOfTarget(leftType, this.checker.numberType) && this.checker.sourceIsSubtypeOfTarget(rightType, this.checker.numberType)) { + binex.type = this.checker.numberType; + } else { + if(leftType == this.checker.anyType || rightType == this.checker.anyType) { + binex.type = this.checker.numberType; + } else { + binex.type = this.anyType; + this.checker.errorReporter.incompatibleTypes(binex, leftType, rightType, binex.printLabel(), this.scope); + } + } + } + } + return binex; + }; + TypeFlow.prototype.typeCheckDotOperator = function (ast) { + var binex = ast; + var leftIsFnc = false; + binex.operand1 = this.typeCheck(binex.operand1); + var leftType = binex.operand1.type; + var leftScope = null; + if(leftType) { + if(leftType == this.anyType) { + binex.type = this.anyType; + return binex; + } else { + if(leftType == this.stringType) { + if(this.stringInterfaceType) { + leftScope = this.stringInterfaceType.memberScope; + } else { + binex.type = this.anyType; + return binex; + } + } else { + if(leftType == this.doubleType) { + if(this.numberInterfaceType) { + leftScope = this.numberInterfaceType.memberScope; + } else { + binex.type = this.anyType; + return binex; + } + } else { + if(leftType == this.booleanType) { + if(this.booleanInterfaceType) { + leftScope = this.booleanInterfaceType.memberScope; + } else { + binex.type = this.anyType; + return binex; + } + } else { + if((leftType.call || leftType.construct) && leftType.members == null) { + if(this.functionInterfaceType) { + leftScope = this.functionInterfaceType.memberScope; + } else { + binex.type = this.anyType; + return binex; + } + } else { + if(leftType.elementType) { + if(this.arrayInterfaceType) { + var arrInstType = leftType.elementType.getArrayBase(this.arrayInterfaceType, this.checker); + leftScope = arrInstType.memberScope; + } else { + binex.type = this.anyType; + return binex; + } + } else { + leftScope = leftType.memberScope; + } + } + } + } + } + } + } + if(leftScope == null) { + this.checker.errorReporter.expectedClassOrInterface(binex); + binex.type = this.anyType; + } else { + var propertyName = binex.operand2; + var lhsIsEnclosingType = (this.thisClassNode && binex.operand1.type == this.thisClassNode.type.instanceType) || this.inTypeRefTypeCheck; + var symbol = leftScope.find(propertyName.text, !lhsIsEnclosingType, this.inTypeRefTypeCheck); + if(!symbol) { + if(this.objectInterfaceType && leftType) { + if(leftType.isReferenceType()) { + symbol = this.objectInterfaceType.memberScope.find(propertyName.text, false, this.inTypeRefTypeCheck); + } + if(!symbol) { + if(this.functionInterfaceType && (leftType.call || leftType.construct)) { + symbol = this.functionInterfaceType.memberScope.find(propertyName.text, false, this.inTypeRefTypeCheck); + } + } + } + } + if(!symbol || (!symbol.visible(leftScope, this.checker))) { + binex.type = this.anyType; + if(symbol == null) { + this.checker.errorReporter.simpleError(propertyName, "The property '" + propertyName.actualText + "' does not exist on value of type '" + leftType.getScopedTypeName(this.scope) + "'"); + } else { + if(!this.inTypeRefTypeCheck) { + this.checker.errorReporter.simpleError(binex, "The property '" + propertyName.actualText + " on type '" + leftType.getScopedTypeName(this.scope) + "' is not visible"); + } + } + } else { + if(symbol.isVariable()) { + if(symbol.isInferenceSymbol()) { + var infSym = symbol; + if(infSym.declAST && !this.checker.typeStatusIsFinished(infSym.typeCheckStatus)) { + this.inScopeTypeCheckDecl(infSym.declAST); + } + } + } + propertyName.sym = symbol; + binex.type = symbol.getType(); + } + } + if(binex.type == null) { + binex.type = this.anyType; + } + return binex; + }; + TypeFlow.prototype.typeCheckBooleanOperator = function (ast) { + var binex = ast; + binex.operand1 = this.typeCheck(binex.operand1); + binex.operand2 = this.typeCheck(binex.operand2); + var leftType = binex.operand1.type; + var rightType = binex.operand2.type; + if((!(this.checker.sourceIsAssignableToTarget(leftType, rightType))) && (!(this.checker.sourceIsAssignableToTarget(rightType, leftType)))) { + this.checker.errorReporter.incompatibleTypes(binex, leftType, rightType, binex.printLabel(), this.scope); + } + binex.type = this.booleanType; + return binex; + }; + TypeFlow.prototype.typeCheckAsgOperator = function (ast) { + var binex = ast; + var applyTargetType = !binex.operand2.isParenthesized; + binex.operand1 = this.typeCheck(binex.operand1); + this.checker.typeCheckWithContextualType(binex.operand1.type, this.checker.inProvisionalTypecheckMode(), applyTargetType, binex.operand2); + var leftType = binex.operand1.type; + var rightType = binex.operand2.type; + if(!(this.astIsWriteable(binex.operand1))) { + this.checker.errorReporter.valueCannotBeModified(binex); + } + if(binex.operand1.nodeType == TypeScript.NodeType.Call) { + var callEx = binex.operand1; + } + var preserveScope = false; + var preservedContainedScope = null; + if(binex.operand2.type) { + preservedContainedScope = binex.operand2.type.containedScope; + preserveScope = true; + } + binex.operand2 = this.castWithCoercion(binex.operand2, leftType, applyTargetType && !this.checker.inProvisionalTypecheckMode(), false); + if(preserveScope && binex.operand2.type.containedScope == null) { + binex.operand2.type.containedScope = preservedContainedScope; + } + binex.type = rightType; + return binex; + }; + TypeFlow.prototype.typeCheckIndex = function (ast) { + var binex = ast; + binex.operand1 = this.typeCheck(binex.operand1); + binex.operand2 = this.typeCheck(binex.operand2); + if(!this.checker.styleSettings.literalSubscript) { + if(binex.operand2.nodeType == TypeScript.NodeType.QString) { + this.checker.errorReporter.styleError(ast, "use literal subscript ('.') notation instead)"); + } + } + var objExprType = binex.operand1.type; + var indexExprType = binex.operand2.type; + if(objExprType.elementType) { + if(indexExprType == this.checker.anyType || indexExprType == this.checker.numberType || TypeScript.hasFlag(indexExprType.typeFlags, TypeScript.TypeFlags.IsEnum)) { + binex.type = objExprType.elementType; + } else { + if(indexExprType == this.checker.stringType) { + binex.type = this.checker.anyType; + } else { + this.checker.errorReporter.simpleError(binex, "Illegal property access"); + binex.type = this.checker.anyType; + } + } + } else { + if(objExprType.index) { + if(indexExprType == this.checker.anyType || !((objExprType.index.flags & TypeScript.SignatureFlags.IsStringIndexer) || (objExprType.index.flags & TypeScript.SignatureFlags.IsNumberIndexer)) || ((objExprType.index.flags & TypeScript.SignatureFlags.IsStringIndexer) && indexExprType == this.checker.stringType) || ((objExprType.index.flags & TypeScript.SignatureFlags.IsNumberIndexer) && (indexExprType == this.checker.numberType || TypeScript.hasFlag(indexExprType.typeFlags, TypeScript.TypeFlags.IsEnum)))) { + var sig = this.resolveOverload(ast, objExprType.index); + if(sig) { + binex.type = sig.returnType.type; + } else { + binex.type = this.checker.anyType; + } + } else { + if(indexExprType == this.checker.stringType) { + binex.type = this.checker.anyType; + } else { + this.checker.errorReporter.simpleError(binex, "Illegal property access"); + binex.type = this.checker.anyType; + } + } + } else { + if((objExprType == this.checker.anyType || objExprType == this.checker.stringType || objExprType == this.checker.numberType || objExprType == this.checker.booleanType || objExprType.isReferenceType()) && (indexExprType == this.checker.anyType || indexExprType == this.checker.stringType || (indexExprType == this.checker.numberType || TypeScript.hasFlag(indexExprType.typeFlags, TypeScript.TypeFlags.IsEnum)))) { + binex.type = this.checker.anyType; + } else { + this.checker.errorReporter.simpleError(binex, "Illegal property access"); + binex.type = this.checker.anyType; + } + } + } + return binex; + }; + TypeFlow.prototype.typeCheckInOperator = function (binex) { + binex.operand1 = this.cast(this.typeCheck(binex.operand1), this.stringType); + binex.operand2 = this.typeCheck(binex.operand2); + if(!((binex.operand1.type == this.checker.anyType || binex.operand1.type == this.checker.stringType) && (binex.operand2.type == this.anyType || this.checker.sourceIsSubtypeOfTarget(binex.operand2.type, this.objectInterfaceType)))) { + this.checker.errorReporter.simpleError(binex, "The in operator requires the left operand to be of type Any or the String primitive type, and the right operand to be of type Any or an object type"); + } + binex.type = this.booleanType; + return binex; + }; + TypeFlow.prototype.typeCheckShift = function (binex, assignment) { + binex.operand1 = this.cast(this.typeCheck(binex.operand1), this.doubleType); + binex.operand2 = this.cast(this.typeCheck(binex.operand2), this.doubleType); + if(assignment && (!(this.astIsWriteable(binex.operand1)))) { + this.checker.errorReporter.valueCannotBeModified(binex); + } + binex.type = this.doubleType; + return binex; + }; + TypeFlow.prototype.typeCheckQMark = function (trinex) { + trinex.operand1 = this.typeCheck(trinex.operand1); + trinex.operand2 = this.typeCheck(trinex.operand2); + trinex.operand3 = this.typeCheck(trinex.operand3); + var leftType = trinex.operand2.type; + var rightType = trinex.operand3.type; + if(leftType == rightType) { + trinex.type = leftType; + } else { + if(this.checker.sourceIsSubtypeOfTarget(leftType, rightType)) { + trinex.type = rightType; + } else { + if(this.checker.sourceIsSubtypeOfTarget(rightType, leftType)) { + trinex.type = leftType; + } else { + trinex.type = this.anyType; + this.checker.errorReporter.incompatibleTypes(trinex, leftType, rightType, trinex.printLabel(), this.scope); + } + } + } + return trinex; + }; + TypeFlow.prototype.addFormals = function (container, signature, table) { + var len = signature.parameters.length; + for(var i = 0; i < len; i++) { + var symbol = signature.parameters[i]; + symbol.container = container; + table.add(symbol.name, symbol); + } + }; + TypeFlow.prototype.addLocalsFromScope = function (scope, container, vars, table, isModContainer) { + var len = vars.members.length; + var hasArgsDef = false; + for(var i = 0; i < len; i++) { + var local = vars.members[i]; + if(((local.sym == null) || (local.sym.kind() != TypeScript.SymbolKind.Field))) { + var result = null; + if((result = table.lookup(local.id.text)) == null) { + var localVar = new TypeScript.ValueLocation(); + localVar.typeLink = new TypeScript.TypeLink(); + var varSym = null; + if(TypeScript.hasFlag(local.varFlags, TypeScript.VarFlags.Static)) { + local.varFlags |= TypeScript.VarFlags.LocalStatic; + varSym = new TypeScript.FieldSymbol(local.id.text, local.minChar, this.checker.locationInfo.unitIndex, true, localVar); + } else { + varSym = new TypeScript.VariableSymbol(local.id.text, local.minChar, this.checker.locationInfo.unitIndex, localVar); + } + varSym.transferVarFlags(local.varFlags); + localVar.symbol = varSym; + varSym.declAST = local; + localVar.typeLink.ast = local.typeExpr; + this.checker.resolveTypeLink(scope, localVar.typeLink, false); + if((local.type == null) && (local.init == null)) { + local.type = this.anyType; + } + localVar.typeLink.type = local.type; + localVar.symbol.container = container; + local.sym = localVar.symbol; + table.add(local.id.text, varSym); + if(local.id.text == "arguments") { + hasArgsDef = true; + } + } else { + local.type = result.getType(); + local.sym = result; + } + } + } + if(!isModContainer) { + if(!hasArgsDef) { + var argLoc = new TypeScript.ValueLocation(); + argLoc.typeLink = new TypeScript.TypeLink(); + var theArgSym = new TypeScript.VariableSymbol("arguments", vars.minChar, this.checker.locationInfo.unitIndex, argLoc); + if(!this.iargumentsInterfaceType) { + var argumentsSym = scope.find("IArguments", false, true); + if(argumentsSym) { + argumentsSym.flags |= TypeScript.SymbolFlags.CompilerGenerated; + this.iargumentsInterfaceType = argumentsSym.getType(); + } else { + this.iargumentsInterfaceType = this.anyType; + } + } + argLoc.typeLink.type = this.iargumentsInterfaceType; + table.add("arguments", theArgSym); + } + } + }; + TypeFlow.prototype.addConstructorLocalArgs = function (container, args, table, isClass) { + if(args) { + var len = args.members.length; + for(var i = 0; i < len; i++) { + var local = args.members[i]; + if((local.sym == null) || (isClass || (local.sym.kind() != TypeScript.SymbolKind.Field))) { + var result = null; + if((result = table.lookup(local.id.text)) == null) { + this.resolveBoundDecl(local); + var localVar = new TypeScript.ValueLocation(); + localVar.typeLink = new TypeScript.TypeLink(); + var varSym = new TypeScript.ParameterSymbol(local.id.text, local.minChar, this.checker.locationInfo.unitIndex, localVar); + varSym.declAST = local; + localVar.symbol = varSym; + localVar.typeLink.type = local.type; + localVar.symbol.container = container; + local.sym = localVar.symbol; + table.add(local.id.text, varSym); + } else { + local.type = result.getType(); + local.sym = result; + } + } + } + } + }; + TypeFlow.prototype.checkInitSelf = function (funcDecl) { + if(!funcDecl.isMethod()) { + var freeVars = funcDecl.freeVariables; + for(var k = 0, len = freeVars.length; k < len; k++) { + var sym = freeVars[k]; + if(sym.isInstanceProperty()) { + return true; + } + } + } + var fns = funcDecl.scopes; + var fnsLen = fns.members.length; + for(var j = 0; j < fnsLen; j++) { + var fn = fns.members[j]; + if(this.checkInitSelf(fn)) { + return true; + } + } + return false; + }; + TypeFlow.prototype.checkPromoteFreeVars = function (funcDecl, constructorSym) { + var freeVars = funcDecl.freeVariables; + for(var k = 0, len = freeVars.length; k < len; k++) { + var sym = freeVars[k]; + if((!sym.isInstanceProperty()) && (sym.container == constructorSym)) { + TypeScript.instanceFilter.reset(); + if(this.scope.search(TypeScript.instanceFilter, sym.name, false, false)) { + this.checker.errorReporter.simpleError(funcDecl, "Constructor-local variable shadows class property '" + sym.name + "'. To access the class property, use 'self." + sym.name + "'"); + } + this.checker.errorReporter.simpleError(funcDecl, "Constructor-local variables may not be accessed from instance method bodies. Consider changing local variable '" + sym.name + "' to a class property"); + } + } + }; + TypeFlow.prototype.allReturnsAreVoid = function (funcDecl) { + var allReturnsAreVoid = true; + if(funcDecl.signature.returnType.type == null) { + var preFindReturnExpressionTypes = function (ast, parent, walker) { + var go = true; + switch(ast.nodeType) { + case TypeScript.NodeType.FuncDecl: { + go = false; + break; + + } + case TypeScript.NodeType.Return: { + var returnStmt = ast; + if(returnStmt.returnExpression) { + allReturnsAreVoid = false; + go = false; + } + + } + default: { + break; + + } + } + walker.options.goChildren = go; + walker.options.goNextSibling = go; + return ast; + }; + TypeScript.getAstWalkerFactory().walk(funcDecl.bod, preFindReturnExpressionTypes); + } + return allReturnsAreVoid; + }; + TypeFlow.prototype.classConstructorHasSuperCall = function (funcDecl) { + var foundSuper = false; + var preFindSuperCall = function (ast, parent, walker) { + var go = true; + switch(ast.nodeType) { + case TypeScript.NodeType.FuncDecl: { + go = false; + break; + + } + case TypeScript.NodeType.Call: { + var call = ast; + if(call.target.nodeType == TypeScript.NodeType.Super) { + go = false; + foundSuper = true; + break; + } + break; + + } + default: { + break; + + } + } + walker.options.goChildren = go; + return ast; + }; + TypeScript.getAstWalkerFactory().walk(funcDecl.bod, preFindSuperCall); + return foundSuper; + }; + TypeFlow.prototype.baseListPrivacyErrorReporter = function (bases, i, declSymbol, extendsList, typeName, isModuleName) { + var baseSymbol = bases.members[i].type.symbol; + var declTypeString = (declSymbol.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) ? "interface" : "class"; + var baseListTypeString = extendsList ? "extends" : "implements"; + var baseTypeString = (baseSymbol.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) ? "interface" : "class"; + var typestring = ""; + if(isModuleName) { + var quotestring = ""; + if(!TypeScript.isQuoted(typeName)) { + quotestring = "'"; + } + typestring = " is using inaccessible module "; + baseTypeString = " " + baseTypeString + " from private module " + quotestring + typeName + quotestring; + } else { + baseTypeString = " private " + baseTypeString + " '" + typeName + "'"; + } + this.checker.errorReporter.simpleError(bases.members[i], "exported " + declTypeString + " '" + declSymbol.name + "' " + baseListTypeString + baseTypeString); + }; + TypeFlow.prototype.typeCheckBaseListPrivacy = function (bases, declSymbol, extendsList) { + var _this = this; + if(bases) { + var basesLen = bases.members.length; + for(var i = 0; i < basesLen; i++) { + if(!bases.members[i].type || bases.members[i].type == this.checker.anyType) { + continue; + } + this.checkSymbolPrivacy(bases.members[i].type.symbol, declSymbol, function (typeName, isModuleName) { + return _this.baseListPrivacyErrorReporter(bases, i, declSymbol, extendsList, typeName, isModuleName); + }); + } + } + }; + TypeFlow.prototype.checkSymbolPrivacy = function (typeSymbol, declSymbol, errorCallback) { + var externalModuleSymbol = null; + var declSymbolPath = null; + if(typeSymbol.isExternallyVisible(this.checker)) { + var typeSymbolPath = typeSymbol.pathToRoot(); + declSymbolPath = declSymbol.pathToRoot(); + var typeSymbolLength = typeSymbolPath.length; + var declSymbolPathLength = declSymbolPath.length; + if(typeSymbolLength > 0) { + if(typeSymbolPath[typeSymbolLength - 1].getType().isModuleType() && (typeSymbolPath[typeSymbolLength - 1]).isDynamic && typeSymbolPath[typeSymbolLength - 1] != declSymbolPath[declSymbolPathLength - 1]) { + externalModuleSymbol = typeSymbolPath[typeSymbolLength - 1]; + } else { + if(typeSymbolLength > 1) { + if(typeSymbolPath[typeSymbolLength - 2].getType().isModuleType() && (typeSymbolPath[typeSymbolLength - 2]).isDynamic && (declSymbolPathLength == 1 || typeSymbolPath[typeSymbolLength - 2] != declSymbolPath[declSymbolPathLength - 2])) { + externalModuleSymbol = typeSymbolPath[typeSymbolLength - 2]; + } + } + } + } + if(externalModuleSymbol == null) { + return; + } + } + var interfaceDecl = declSymbol.getInterfaceDeclFromSymbol(this.checker); + if(interfaceDecl && !TypeScript.hasFlag(interfaceDecl.varFlags, TypeScript.VarFlags.Exported)) { + return; + } + var checkVisibilitySymbol = declSymbol; + var varDecl = declSymbol.getVarDeclFromSymbol(); + if(varDecl) { + if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Private)) { + return; + } else { + if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Public)) { + checkVisibilitySymbol = declSymbol.container; + } + } + } + if(checkVisibilitySymbol.isExternallyVisible(this.checker)) { + var privateSymbolName = typeSymbol.name; + if(externalModuleSymbol != null) { + var prettyName = externalModuleSymbol.getPrettyNameOfDynamicModule(declSymbolPath); + if(prettyName != null) { + this.currentScript.AddExternallyVisibleImportedSymbol(prettyName.symbol, this.checker); + return; + } else { + privateSymbolName = externalModuleSymbol.prettyName; + } + } + errorCallback(privateSymbolName, typeSymbol.name != privateSymbolName); + } + }; + TypeFlow.prototype.checkTypePrivacy = function (type, declSymbol, errorCallback) { + var _this = this; + if(!(type && type.primitiveTypeClass == TypeScript.Primitive.None)) { + return; + } + if(type.isArray()) { + return this.checkTypePrivacy(type.elementType, declSymbol, errorCallback); + } + if(type.symbol && type.symbol.name && type.symbol.name != "_anonymous" && (((type.call == null) && (type.construct == null) && (type.index == null)) || (type.members && (!type.isClass())))) { + return this.checkSymbolPrivacy(type.symbol, declSymbol, errorCallback); + } + if(type.members) { + type.members.allMembers.map(function (key, s, unused) { + var sym = s; + if(!TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.BuiltIn)) { + _this.checkTypePrivacy(sym.getType(), declSymbol, errorCallback); + } + }, null); + } + this.checkSignatureGroupPrivacy(type.call, declSymbol, errorCallback); + this.checkSignatureGroupPrivacy(type.construct, declSymbol, errorCallback); + this.checkSignatureGroupPrivacy(type.index, declSymbol, errorCallback); + }; + TypeFlow.prototype.checkSignatureGroupPrivacy = function (sgroup, declSymbol, errorCallback) { + if(sgroup) { + var len = sgroup.signatures.length; + for(var i = 0; i < sgroup.signatures.length; i++) { + var signature = sgroup.signatures[i]; + if(len > 1 && signature == sgroup.definitionSignature) { + continue; + } + if(signature.returnType) { + this.checkTypePrivacy(signature.returnType.type, declSymbol, errorCallback); + } + var paramLen = signature.parameters.length; + for(var j = 0; j < paramLen; j++) { + var param = signature.parameters[j]; + this.checkTypePrivacy(param.getType(), declSymbol, errorCallback); + } + } + } + }; + TypeFlow.prototype.functionArgumentPrivacyErrorReporter = function (funcDecl, p, paramSymbol, typeName, isModuleName) { + var isGetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor); + var isSetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.SetAccessor); + var isPublicFunc = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Public); + var isContainerInterface = funcDecl.type.symbol.getInterfaceDeclFromSymbol(this.checker) != null; + var typestring = ""; + if(isModuleName) { + var quotestring = ""; + if(!TypeScript.isQuoted(typeName)) { + quotestring = "'"; + } + typestring = " is using inaccessible module " + quotestring + typeName + quotestring; + } else { + typestring = " has or is using private type '" + typeName + "'"; + } + if(!isContainerInterface) { + if(funcDecl.isConstructor) { + this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], "exported class's constructor parameter '" + paramSymbol.name + "'" + typestring); + } else { + if(isSetter) { + this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], (isPublicFunc ? "public" : "exported") + " setter parameter '" + paramSymbol.name + "'" + typestring); + } else { + if(!isGetter) { + this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], (isPublicFunc ? "public" : "exported") + " function parameter '" + paramSymbol.name + "'" + typestring); + } + } + } + } else { + if(funcDecl.isConstructMember()) { + this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], "exported interface's constructor parameter '" + paramSymbol.name + "'" + typestring); + } else { + if(funcDecl.isCallMember()) { + this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], "exported interface's call parameter '" + paramSymbol.name + "'" + typestring); + } else { + if(!funcDecl.isIndexerMember()) { + this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], "exported interface's function parameter '" + paramSymbol.name + "'" + typestring); + } + } + } + } + }; + TypeFlow.prototype.returnTypePrivacyError = function (astError, funcDecl, typeName, isModuleName) { + var isGetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor); + var isSetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.SetAccessor); + var isPublicFunc = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Public); + var isContainerInterface = funcDecl.type.symbol.getInterfaceDeclFromSymbol(this.checker) != null; + var typestring = ""; + if(isModuleName) { + var quotestring = ""; + if(!TypeScript.isQuoted(typeName)) { + quotestring = "'"; + } + typestring = " is using inaccessible module " + quotestring + typeName + quotestring; + } else { + typestring = " has or is using private type '" + typeName + "'"; + } + if(!isContainerInterface) { + if(isGetter) { + this.checker.errorReporter.simpleError(astError, (isPublicFunc ? "public" : "exported") + " getter return type" + typestring); + } else { + if(!isSetter) { + this.checker.errorReporter.simpleError(astError, (isPublicFunc ? "public" : "exported") + " function return type" + typestring); + } + } + } else { + if(funcDecl.isConstructMember()) { + this.checker.errorReporter.simpleError(astError, "exported interface's constructor return type" + typestring); + } else { + if(funcDecl.isCallMember()) { + this.checker.errorReporter.simpleError(astError, "exported interface's call return type" + typestring); + } else { + if(funcDecl.isIndexerMember()) { + this.checker.errorReporter.simpleError(astError, "exported interface's indexer return type" + typestring); + } else { + this.checker.errorReporter.simpleError(astError, "exported interface's function return type" + typestring); + } + } + } + } + }; + TypeFlow.prototype.functionReturnTypePrivacyErrorReporter = function (funcDecl, signature, typeName, isModuleName) { + var reportOnFuncDecl = false; + if(funcDecl.returnTypeAnnotation != null && funcDecl.returnTypeAnnotation.type == signature.returnType.type) { + this.returnTypePrivacyError(funcDecl.returnTypeAnnotation, funcDecl, typeName, isModuleName); + } + for(var i = 0; i < funcDecl.returnStatementsWithExpressions.length; i++) { + if(funcDecl.returnStatementsWithExpressions[i].type == signature.returnType.type) { + this.returnTypePrivacyError(funcDecl.returnStatementsWithExpressions[i], funcDecl, typeName, isModuleName); + } else { + reportOnFuncDecl = true; + } + } + if(reportOnFuncDecl) { + this.returnTypePrivacyError(funcDecl, funcDecl, typeName, isModuleName); + } + }; + TypeFlow.prototype.typeCheckFunction = function (funcDecl) { + var _this = this; + this.nestingLevel = 0; + var fnType = funcDecl.type; + var fgSym = fnType.symbol; + var signature = funcDecl.signature; + if(this.checker.typeStatusIsFinished(signature.typeCheckStatus)) { + return funcDecl; + } else { + if(signature.typeCheckStatus == TypeScript.TypeCheckStatus.Started) { + if(!funcDecl.returnTypeAnnotation && funcDecl.bod && !funcDecl.isSignature() && !(funcDecl.isConstructor) && this.allReturnsAreVoid(funcDecl)) { + signature.returnType.type = this.voidType; + return funcDecl; + } else { + if(funcDecl.returnTypeAnnotation == null) { + if(this.checker.styleSettings.implicitAny) { + this.checker.errorReporter.styleError(funcDecl, "type implicitly set to 'any'"); + } + signature.returnType.type = this.anyType; + fgSym.flags |= TypeScript.SymbolFlags.RecursivelyReferenced; + } + return funcDecl; + } + } + } + signature.typeCheckStatus = TypeScript.TypeCheckStatus.Started; + this.checker.addStartedPTO(signature); + var prevScope = this.scope; + var prevFnc = this.thisFnc; + var prevMethodStatus = this.enclosingFncIsMethod; + var prevClassNode = this.thisClassNode; + this.enclosingFncIsMethod = funcDecl.isMethod() || funcDecl.isConstructor; + this.thisFnc = funcDecl; + var container = funcDecl.type.symbol; + var prevThisType = this.thisType; + var prevLocationInfo = this.checker.locationInfo; + var funcTable = null; + var acceptedContextualType = false; + var targetParams = null; + var targetReturnType = null; + var isGetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor); + var isSetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.SetAccessor); + var accessorType = (isGetter || isSetter) && funcDecl.accessorSymbol ? funcDecl.accessorSymbol.getType() : null; + var prevModDecl = this.checker.currentModDecl; + if(funcDecl.isConstructor && !funcDecl.isOverload) { + if(fnType.instanceType == null) { + this.checker.errorReporter.simpleError(funcDecl, "Malformed function body (is this a class named the same as an existing interface?)"); + return funcDecl; + } + this.scope = fnType.instanceType.constructorScope; + var ssb = this.scope; + funcTable = ssb.valueMembers.allMembers; + } else { + if((funcDecl.isSpecialFn() && !(funcDecl.fncFlags & TypeScript.FncFlags.Signature)) || funcDecl.isOverload) { + funcTable = funcDecl.symbols; + if(!TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static) && fnType.containedScope) { + this.scope = fnType.containedScope; + } + } else { + if(funcDecl.bod) { + this.scope = fnType.containedScope; + } + var ssb = this.scope; + if(ssb && ssb.valueMembers) { + funcTable = ssb.valueMembers.allMembers; + } + } + } + if(funcDecl.isConstructor && funcDecl.bod && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { + var hasBaseType = TypeScript.hasFlag(funcDecl.classDecl.type.instanceType.typeFlags, TypeScript.TypeFlags.HasBaseType); + var noSuperCallAllowed = !hasBaseType || TypeScript.hasFlag(funcDecl.classDecl.type.instanceType.typeFlags, TypeScript.TypeFlags.HasBaseTypeOfObject); + var superCallMustBeFirst = TypeScript.hasFlag((funcDecl.classDecl).varFlags, TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor); + if(noSuperCallAllowed && this.classConstructorHasSuperCall(funcDecl)) { + this.checker.errorReporter.simpleError(funcDecl, "Calls to 'super' constructor are not allowed in classes that either inherit directly from 'Object' or have no base class"); + } else { + if(hasBaseType) { + if(superCallMustBeFirst) { + if(!funcDecl.bod || !funcDecl.bod.members.length || !((funcDecl.bod.members[0].nodeType == TypeScript.NodeType.Call && (funcDecl.bod.members[0]).target.nodeType == TypeScript.NodeType.Super) || (TypeScript.hasFlag(funcDecl.bod.flags, TypeScript.ASTFlags.StrictMode) && funcDecl.bod.members.length > 1 && funcDecl.bod.members[1].nodeType == TypeScript.NodeType.Call && (funcDecl.bod.members[1]).target.nodeType == TypeScript.NodeType.Super))) { + this.checker.errorReporter.simpleError(funcDecl, "If a derived class contains initialized properties or constructor parameter properties, the first statement in the constructor body must be a call to the super constructor"); + } + } else { + if(!this.classConstructorHasSuperCall(funcDecl)) { + this.checker.errorReporter.simpleError(funcDecl, "Constructors for derived classes must contain a call to the class's 'super' constructor"); + } + } + } + } + } + if(funcDecl.isMethod() && funcDecl.type.enclosingType) { + var enclosingClassNode = null; + if(funcDecl.type.enclosingType.symbol.declAST.nodeType == TypeScript.NodeType.FuncDecl) { + enclosingClassNode = (funcDecl.type.enclosingType.symbol.declAST).classDecl; + } else { + if(funcDecl.type.enclosingType.symbol.declAST.nodeType == TypeScript.NodeType.ClassDeclaration) { + enclosingClassNode = funcDecl.type.enclosingType.symbol.declAST; + } + } + if(enclosingClassNode) { + this.thisClassNode = enclosingClassNode; + } + } + if(fnType.enclosingType) { + ; ; + var enclosingSym = fnType.symbol.container; + if(enclosingSym && enclosingSym.isType() && enclosingSym.getType().isClass()) { + enclosingSym = enclosingSym.container; + } + if(enclosingSym && enclosingSym.declAST && enclosingSym.declAST.nodeType == TypeScript.NodeType.ModuleDeclaration) { + this.checker.currentModDecl = enclosingSym.declAST; + } + } + if(funcDecl.unitIndex > 0) { + if(this.checker.units && (funcDecl.unitIndex < this.checker.units.length)) { + this.checker.locationInfo = this.checker.units[funcDecl.unitIndex]; + } else { + this.checker.locationInfo = TypeScript.unknownLocationInfo; + } + } + if(fnType.enclosingType) { + this.thisType = fnType.enclosingType; + } else { + this.thisType = prevThisType; + } + var paramLen = signature.parameters.length; + if(!funcDecl.isConstructor && funcDecl.bod && !funcDecl.isSignature()) { + var tmpParamScope = this.scope; + var ssb = this.scope; + if(!funcDecl.isMethod() && funcDecl.returnTypeAnnotation == null) { + if(prevScope && funcDecl.name && !funcDecl.name.isMissing()) { + var considerSym = prevScope.findAmbient(funcDecl.name.text, false, false); + if(considerSym && considerSym.declAST && considerSym.declAST.type) { + this.checker.setContextualType(considerSym.declAST.type, false); + } + } + if(this.checker.hasTargetType()) { + var candidateTypeContext = this.checker.getTargetTypeContext(); + var candidateType = candidateTypeContext.contextualType; + if(this.checker.canContextuallyTypeFunction(candidateType, funcDecl, true)) { + var candidateSigs = candidateType.construct ? candidateType.construct : candidateType.call; + candidateTypeContext.targetSig = candidateSigs.signatures[0]; + var candidateParams = candidateTypeContext.targetSig.parameters; + targetParams = candidateParams; + targetReturnType = candidateTypeContext.targetSig.returnType.type; + if(candidateTypeContext.targetSig.declAST) { + if(candidateTypeContext.targetSig.declAST.isConstructor) { + funcDecl.isTargetTypedAsMethod = true; + } else { + if(candidateTypeContext.targetSig.declAST.isMethod()) { + funcDecl.isTargetTypedAsMethod = true; + } + } + } + fgSym.type = candidateTypeContext.contextualType; + acceptedContextualType = true; + } else { + if(candidateType && funcDecl.isAccessor()) { + accessorType = candidateType; + candidateTypeContext.targetAccessorType = accessorType; + } else { + this.checker.killCurrentContextualType(); + } + } + } + } + var paramTable = ssb.valueMembers; + this.scope = new TypeScript.SymbolScopeBuilder(paramTable, null, null, null, prevScope, container); + for(var p = 0; p < paramLen; p++) { + var symbol = signature.parameters[p]; + var ast = symbol.declAST; + if(this.checker.hasTargetType() && (targetParams && (this.checker.getTargetTypeContext().targetSig.hasVariableArgList || p < targetParams.length))) { + var candidateTypeContext = this.checker.getTargetTypeContext(); + var hasVarArgList = candidateTypeContext.targetSig.hasVariableArgList; + ast.type = hasVarArgList && p >= targetParams.length - 1 ? targetParams[targetParams.length - 1].getType().elementType : targetParams[p].getType(); + ast.sym.setType(ast.type); + (ast.sym).typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); + } else { + this.typeCheck(ast); + } + if(isSetter && accessorType) { + ast = this.cast(ast, accessorType); + } + symbol.container = container; + this.checkTypePrivacy(symbol.getType(), container, function (typeName, isModuleName) { + return _this.functionArgumentPrivacyErrorReporter(funcDecl, p, symbol, typeName, isModuleName); + }); + paramTable.publicMembers.add(symbol.name, symbol); + } + this.scope = tmpParamScope; + } else { + this.typeCheck(funcDecl.arguments); + for(var p = 0; p < paramLen; p++) { + signature.parameters[p].parameter.typeLink.type = funcDecl.arguments.members[p].type; + this.checkTypePrivacy(signature.parameters[p].getType(), container, function (typeName, isModuleName) { + return _this.functionArgumentPrivacyErrorReporter(funcDecl, p, signature.parameters[p], typeName, isModuleName); + }); + if((funcDecl.arguments.members[p]).parameterPropertySym) { + (funcDecl.arguments.members[p]).parameterPropertySym.setType(funcDecl.arguments.members[p].type); + } + } + if((funcDecl.fncFlags & TypeScript.FncFlags.IndexerMember)) { + if(!paramLen || paramLen > 1) { + this.checker.errorReporter.simpleError(funcDecl, "Index signatures may take one and only one parameter"); + } else { + if(funcDecl.arguments.members[0].type == this.checker.numberType) { + fnType.index.flags |= TypeScript.SignatureFlags.IsNumberIndexer; + } else { + if(funcDecl.arguments.members[0].type == this.checker.stringType) { + fnType.index.flags |= TypeScript.SignatureFlags.IsStringIndexer; + } else { + this.checker.errorReporter.simpleError(funcDecl.arguments.members[0], "Index signatures may only take 'string' or 'number' as their parameter"); + } + } + } + } + } + if(funcDecl.bod && (!funcDecl.isSignature())) { + if(!(funcDecl.isConstructor)) { + this.addFormals(container, signature, funcTable); + } else { + this.addConstructorLocalArgs(funcDecl.type.symbol, funcDecl.arguments, funcTable, TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)); + if(this.thisClassNode && this.thisClassNode.extendsList) { + var tmpScope = this.scope; + var funcMembers = new TypeScript.ScopedMembers(funcTable); + this.scope = new TypeScript.FilteredSymbolScopeBuilder(funcMembers, prevScope, funcDecl.type.symbol, function (sym) { + return sym.kind() == TypeScript.SymbolKind.Parameter; + }); + this.typeCheckBaseCalls(this.thisClassNode.extendsList); + this.scope = tmpScope; + } + } + var prevMod = this.checker.currentModDecl; + if(funcDecl.type && funcDecl.type.symbol && !funcDecl.isMethod() && funcDecl.type.symbol.declModule) { + this.checker.currentModDecl = funcDecl.type.symbol.declModule; + } + if(acceptedContextualType) { + this.checker.setContextualType(null, this.checker.inProvisionalTypecheckMode()); + } + this.typeCheck(funcDecl.bod); + if(acceptedContextualType) { + this.checker.unsetContextualType(); + } + this.checker.currentModDecl = prevMod; + if(this.checker.checkControlFlow) { + var cfg = funcDecl.buildControlFlow(); + if(this.checker.printControlFlowGraph) { + cfg.print(this.checker.errorReporter.outfile); + } + cfg.reportUnreachable(this.checker.errorReporter); + if(this.checker.checkControlFlowUseDef) { + cfg.useDef(this.checker.errorReporter, funcDecl.type.symbol); + } + } + if(funcDecl.isConstructor) { + var fns = funcDecl.scopes; + var fnsLen = fns.members.length; + var freeVars; + var sym; + var j = 0; + for(; j < fnsLen; j++) { + var fn = fns.members[j]; + if(!fn.isSignature()) { + if(TypeScript.hasFlag(fn.fncFlags, TypeScript.FncFlags.Method) && (!TypeScript.hasFlag(fn.fncFlags, TypeScript.FncFlags.Static))) { + this.checkPromoteFreeVars(fn, funcDecl.type.symbol); + } + } + } + } + } + this.scope = prevScope; + this.thisFnc = prevFnc; + this.thisClassNode = prevClassNode; + this.enclosingFncIsMethod = prevMethodStatus; + this.thisType = prevThisType; + this.checker.locationInfo = prevLocationInfo; + this.checker.currentModDecl = prevModDecl; + signature.typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); + if(funcDecl.returnTypeAnnotation) { + this.checkForVoidConstructor(funcDecl.returnTypeAnnotation.type, funcDecl.returnTypeAnnotation); + if(signature.returnType.type == null) { + this.checker.resolveTypeLink(this.scope, signature.returnType, false); + } + } else { + if(targetReturnType) { + signature.returnType.type = targetReturnType; + } + } + if(!(fgSym.flags & TypeScript.SymbolFlags.RecursivelyReferenced) && funcDecl.returnStatementsWithExpressions.length > 0) { + var collection = { + getLength: function () { + return funcDecl.returnStatementsWithExpressions.length; + }, + setTypeAtIndex: function (index, type) { + funcDecl.returnStatementsWithExpressions[index].type = type; + }, + getTypeAtIndex: function (index) { + return funcDecl.returnStatementsWithExpressions[index].type; + } + }; + var bestCommonReturnType = funcDecl.returnStatementsWithExpressions[0].type; + bestCommonReturnType = this.checker.findBestCommonType(bestCommonReturnType, null, collection, true); + if(bestCommonReturnType) { + signature.returnType.type = this.checker.widenType(bestCommonReturnType); + } else { + for(var i = 0; i < funcDecl.returnStatementsWithExpressions.length; i++) { + this.checker.errorReporter.simpleError(funcDecl.returnStatementsWithExpressions[i], "Incompatible return type"); + } + signature.returnType.type = this.anyType; + } + } + var onlyHasThrow = false; + if(signature.returnType.type == null) { + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.HasReturnExpression)) { + if(this.checker.styleSettings.implicitAny) { + this.checker.errorReporter.styleError(funcDecl, "type implicitly set to 'any'"); + } + signature.returnType.type = this.anyType; + } else { + signature.returnType.type = this.voidType; + } + } else { + if(signature.returnType.type == this.nullType || signature.returnType.type == this.checker.undefinedType) { + signature.returnType.type = this.anyType; + } else { + if((signature.returnType.type != this.voidType && signature.returnType.type != this.checker.undefinedType && signature.returnType.type != this.anyType)) { + if(!funcDecl.isSignature() && !funcDecl.isConstructor && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.HasReturnExpression) && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { + onlyHasThrow = (funcDecl.bod.members.length > 0) && (funcDecl.bod.members[0].nodeType == TypeScript.NodeType.Throw); + if(!onlyHasThrow) { + this.checker.errorReporter.simpleError(funcDecl.returnTypeAnnotation || funcDecl, "Function declared a non-void return type, but has no return expression"); + } + } + this.checkTypePrivacy(signature.returnType.type, container, function (typeName, isModuleName) { + return _this.functionReturnTypePrivacyErrorReporter(funcDecl, signature, typeName, isModuleName); + }); + } + } + } + if(funcDecl.accessorSymbol) { + var accessorType = funcDecl.accessorSymbol.getType(); + if(!onlyHasThrow && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor) && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.HasReturnExpression)) { + this.checker.errorReporter.simpleError(funcDecl, "Getters must return a value"); + } + if(accessorType) { + if((TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor) && accessorType != signature.returnType.type) || (funcDecl.arguments.members.length > 0 && accessorType != funcDecl.arguments.members[0].type)) { + this.checker.errorReporter.simpleError(funcDecl, "Getter and setter types do not agree"); + } + } else { + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { + funcDecl.accessorSymbol.setType(signature.returnType.type); + } else { + if(funcDecl.arguments.members.length != 1) { + this.checker.errorReporter.simpleError(funcDecl, "Setters may have one and only one argument"); + } else { + funcDecl.accessorSymbol.setType(funcDecl.arguments.members[0].type); + } + } + } + } + this.typeCheckOverloadSignatures(fnType, funcDecl); + return funcDecl; + }; + TypeFlow.prototype.typeCheckBases = function (type) { + var seenInterface = false; + var bases = type.extendsList; + var baseLinks = type.extendsTypeLinks; + if(bases) { + var len = bases.length; + if(len > 0) { + type.typeFlags |= TypeScript.TypeFlags.HasBaseType; + } + for(var i = 0; i < len; i++) { + if(bases[i] == this.checker.anyType) { + baseLinks[i].type = null; + var oldErrors = this.checker.errorReporter.getCapturedErrors(); + TypeScript.CompilerDiagnostics.assert(oldErrors.length == 0, "There shouldnt be any contextual errors when typechecking base type names"); + this.checker.errorReporter.pushToErrorSink = true; + bases[i] = this.checker.resolveBaseTypeLink(baseLinks[i], type.containedScope); + this.checker.errorReporter.pushToErrorSink = false; + this.checker.errorReporter.freeCapturedErrors(); + } + var base = bases[i]; + var baseRef = baseLinks[i].ast; + var baseTypeOfObject = base.symbol && base.symbol.name == "Object" && base.symbol.container == this.checker.gloMod; + if(baseTypeOfObject) { + type.typeFlags |= TypeScript.TypeFlags.HasBaseTypeOfObject; + } + if(base.isClassInstance()) { + if(!(type.isClassInstance())) { + this.checker.errorReporter.simpleError(baseRef, "Interface base type must be interface"); + } else { + if(seenInterface) { + this.checker.errorReporter.simpleError(baseRef, "Class may not follow interface as base type"); + } + } + } else { + if(base.isModuleType()) { + this.checker.errorReporter.simpleError(baseRef, "Types may not be derived from module types"); + } else { + if(base.members) { + if(!seenInterface) { + seenInterface = true; + } + } else { + if(!(type.isClassInstance())) { + this.checker.errorReporter.simpleError(baseRef, "Interface base type must be interface"); + } else { + this.checker.errorReporter.simpleError(baseRef, "Base type must be interface or class"); + } + break; + } + } + } + } + } + }; + TypeFlow.prototype.checkMembersImplementInterfaces = function (implementingType) { + var instanceType = implementingType.getInstanceType(); + if(instanceType.implementsList) { + var len = instanceType.implementsList.length; + for(var i = 0; i < len; i++) { + var interfaceType = instanceType.implementsList[i]; + var comparisonInfo = new TypeScript.TypeComparisonInfo(); + if(!this.checker.sourceIsSubtypeOfTarget(instanceType, interfaceType, comparisonInfo)) { + var emsg = "Class '" + instanceType.getTypeName() + "' declares interface '" + interfaceType.getTypeName() + "' but does not implement it"; + if(!comparisonInfo.message) { + this.checker.errorReporter.simpleErrorFromSym(instanceType.symbol, emsg); + } else { + this.checker.errorReporter.simpleErrorFromSym(instanceType.symbol, emsg + ": " + comparisonInfo.message); + } + } + } + } + }; + TypeFlow.prototype.typeCheckBaseCalls = function (bases) { + if(bases == null) { + return; + } + var basesLen = bases.members.length; + for(var i = 0; i < basesLen; i++) { + var baseExpr = bases.members[i]; + var baseSymbol = null; + if(baseExpr.nodeType == TypeScript.NodeType.Call) { + this.typeCheckNew(baseExpr); + } + } + }; + TypeFlow.prototype.assertUniqueNamesInBaseTypes = function (names, type, classDecl, checkUnique) { + var _this = this; + if(type) { + if(type.members) { + type.members.publicMembers.map(function (key, s, c) { + var sym = s; + var dup = names.lookup(sym.name); + if(dup) { + if(checkUnique) { + _this.checker.errorReporter.simpleError(classDecl, "duplicate member name in bases for " + classDecl.name.actualText + ": " + type.symbol.name + " and " + dup.container.name + " both contain member with name " + sym.name); + } + } else { + names.add(sym.name, sym); + } + }, null); + } + if(type.extendsList) { + var len = type.extendsList.length; + for(var i = 0; i < len; i++) { + if(!(type.extendsList[i].symbol.flags & TypeScript.SymbolFlags.RecursivelyReferenced)) { + this.assertUniqueNamesInBaseTypes(names, type.extendsList[i], classDecl, checkUnique); + } + } + } + } + }; + TypeFlow.prototype.checkBaseTypeMemberInheritance = function (derivedType, derivedTypeDecl) { + var _this = this; + var instanceType = derivedType.getInstanceType(); + if(instanceType.extendsList == null) { + return; + } + var len = instanceType.extendsList.length; + if(len > 0) { + var names = new TypeScript.StringHashTable(); + if(instanceType.isClassInstance()) { + for(var i = 0; i < len; i++) { + this.assertUniqueNamesInBaseTypes(names, instanceType.extendsList[i], derivedTypeDecl, i > 0); + } + } + if(instanceType.members) { + instanceType.members.publicMembers.map(function (key, s, c) { + var sym = s; + for(var j = 0; j < len; j++) { + var base = instanceType.extendsList[j]; + if(base.memberScope == null) { + _this.checker.errorReporter.simpleError(derivedTypeDecl, "Base type '" + base.symbol.name + "' lacks an implementation."); + } else { + var bSym = base.memberScope.find(sym.name, false, false); + if(bSym) { + var aType = sym.getType(); + var bType = bSym.getType(); + if(!(_this.checker.sourceIsSubtypeOfTarget(aType, bType))) { + _this.checker.errorReporter.simpleErrorFromSym(sym, "Type of overridden member '" + sym.name + "' is not subtype of original member defined by type '" + bSym.container.name + "'"); + } else { + if((sym.kind() == TypeScript.SymbolKind.Type) && (bSym.kind() == TypeScript.SymbolKind.Field)) { + _this.checker.errorReporter.simpleErrorFromSym(sym, "Cannot override field '" + sym.name + "' with method"); + } + } + } + } + } + }, null); + } + } + }; + TypeFlow.prototype.typeCheckClass = function (classDecl) { + var typeSymbol = classDecl.type.symbol; + if(typeSymbol.typeCheckStatus == TypeScript.TypeCheckStatus.Finished) { + return classDecl; + } else { + if(typeSymbol.typeCheckStatus == TypeScript.TypeCheckStatus.Started) { + return classDecl; + } else { + typeSymbol.typeCheckStatus = TypeScript.TypeCheckStatus.Started; + this.checker.addStartedPTO(typeSymbol); + } + } + var prevScope = this.scope; + var svClassNode = this.thisClassNode; + this.thisClassNode = classDecl; + var classType = classDecl.type; + this.typeCheckBases(classType.instanceType); + this.typeCheckBaseListPrivacy(classDecl.extendsList, typeSymbol, true); + this.typeCheckBaseListPrivacy(classDecl.implementsList, typeSymbol, false); + var prevThisType = this.thisType; + this.thisType = classType.instanceType; + this.scope = classType.instanceType.containedScope; + if(classDecl.constructorDecl) { + this.scope = classType.instanceType.constructorScope; + var ssb = this.scope; + var funcTable = ssb.valueMembers.allMembers; + this.addConstructorLocalArgs(classDecl.constructorDecl.type.symbol, classDecl.constructorDecl.arguments, funcTable, true); + } + this.typeCheck(classDecl.members); + typeSymbol.typeCheckStatus = TypeScript.TypeCheckStatus.Finished; + this.checkBaseTypeMemberInheritance(classType, classDecl); + this.checkMembersImplementInterfaces(classType); + this.typeCheckOverloadSignatures(classType, classDecl); + this.typeCheckOverloadSignatures(classType.instanceType, classDecl); + if(!classDecl.constructorDecl) { + if(classDecl.extendsList && classDecl.extendsList.members.length && classDecl.extendsList.members[0].type && classDecl.extendsList.members[0].type.symbol.type.isClass()) { + TypeScript.cloneParentConstructGroupForChildType(classDecl.type, classDecl.extendsList.members[0].type.symbol.type); + } + } + this.thisType = prevThisType; + this.thisClassNode = svClassNode; + this.scope = prevScope; + return classDecl; + }; + TypeFlow.prototype.typeCheckOverloadSignatures = function (type, ast) { + if(type.call) { + type.call.typeCheck(this.checker, ast, type.construct != null); + } + if(type.construct) { + type.construct.typeCheck(this.checker, ast, false); + } + if(type.index) { + type.index.typeCheck(this.checker, ast, false); + } + }; + TypeFlow.prototype.typeCheckInterface = function (interfaceDecl) { + this.typeCheckBases(interfaceDecl.type); + this.typeCheckBaseListPrivacy(interfaceDecl.extendsList, interfaceDecl.type.symbol, true); + this.typeCheck(interfaceDecl.members); + this.checkBaseTypeMemberInheritance(interfaceDecl.type, interfaceDecl); + if(interfaceDecl.extendsList) { + for(var i = 0; i < interfaceDecl.extendsList.members.length; i++) { + if(interfaceDecl.extendsList.members[i].type.call) { + if(interfaceDecl.type.call) { + interfaceDecl.type.call.signatures = interfaceDecl.type.call.signatures.concat(interfaceDecl.extendsList.members[i].type.call.signatures); + } else { + interfaceDecl.type.call = interfaceDecl.extendsList.members[i].type.call; + } + } + if(interfaceDecl.extendsList.members[i].type.construct) { + if(interfaceDecl.type.construct) { + interfaceDecl.type.construct.signatures = interfaceDecl.type.construct.signatures.concat(interfaceDecl.extendsList.members[i].type.construct.signatures); + } else { + interfaceDecl.type.construct = interfaceDecl.extendsList.members[i].type.construct; + } + } + if(interfaceDecl.extendsList.members[i].type.index) { + if(interfaceDecl.type.index) { + interfaceDecl.type.index.signatures = interfaceDecl.type.index.signatures.concat(interfaceDecl.extendsList.members[i].type.index.signatures); + } else { + interfaceDecl.type.index = interfaceDecl.extendsList.members[i].type.index; + } + } + } + } + return interfaceDecl; + }; + TypeFlow.prototype.typeCheckImportDecl = function (importDecl) { + var mod = importDecl.alias.type; + var sym = null; + var prevInImportTC = this.inImportTypeCheck; + this.inImportTypeCheck = true; + this.typeCheck(importDecl.alias); + mod = importDecl.alias.type; + if(mod == null) { + this.checker.errorReporter.simpleError(importDecl.alias, "Could not resolve module alias '" + importDecl.id.actualText + "'"); + mod = this.checker.anyType; + (importDecl.id.sym).type = mod; + } + importDecl.id.type = mod; + sym = mod.symbol; + if(!mod.isModuleType()) { + this.checker.errorReporter.simpleError(importDecl.alias, "A module cannot be aliased to a non-module type"); + } else { + sym.type = mod; + if(this.checker.typeFlow.currentScript && this.checker.typeFlow.currentScript.topLevelMod && this.checker.typeFlow.currentScript.topLevelMod.mod) { + this.checker.typeFlow.currentScript.topLevelMod.mod.importedModules.push(importDecl); + } + (importDecl.id.sym).type = mod; + if(mod.symbol && mod.symbol.declAST) { + (mod.symbol.declAST).modFlags &= ~TypeScript.ModuleFlags.ShouldEmitModuleDecl; + } + } + this.inImportTypeCheck = prevInImportTC; + return importDecl; + }; + TypeFlow.prototype.typeCheckModule = function (moduleDecl) { + if(!moduleDecl.mod) { + return moduleDecl; + } + if(this.currentScript) { + this.currentScript.requiresGlobal = true; + } + var mod = moduleDecl.mod; + var sym = null; + var prevScope = this.scope; + var prevThisType = this.thisType; + var prevCurrentModDecl = this.checker.currentModDecl; + this.checker.currentModDecl = moduleDecl; + this.thisType = null; + this.scope = mod.containedScope; + this.typeCheck(moduleDecl.members); + sym = mod.symbol; + this.checker.currentModDecl = prevCurrentModDecl; + this.thisType = prevThisType; + this.scope = prevScope; + moduleDecl.type = mod; + if(sym) { + sym.typeCheckStatus = TypeScript.TypeCheckStatus.Finished; + } + return moduleDecl; + }; + TypeFlow.prototype.typeCheckFor = function (forStmt) { + forStmt.init = this.typeCheck(forStmt.init); + this.nestingLevel++; + forStmt.cond = this.typeCheck(forStmt.cond); + this.typeCheckCondExpr(forStmt.cond); + forStmt.incr = this.typeCheck(forStmt.incr); + this.nestingLevel--; + forStmt.body = this.typeCheck(forStmt.body); + this.typeCheckCompoundStmtBlock(forStmt.body, "for statement"); + forStmt.type = this.voidType; + return forStmt; + }; + TypeFlow.prototype.typeCheckWith = function (withStmt) { + if(this.checker.errorsOnWith) { + this.checker.errorReporter.simpleError(withStmt.expr, "All symbols within a 'with' block will be typed as 'any'"); + } + withStmt.expr = this.typeCheck(withStmt.expr); + this.checker.inWith = true; + withStmt.body = this.typeCheck(withStmt.body); + this.typeCheckCompoundStmtBlock(withStmt.body, "with statement"); + this.checker.inWith = false; + return withStmt; + }; + TypeFlow.prototype.typeCheckForIn = function (forInStmt) { + forInStmt.obj = this.typeCheck(forInStmt.obj); + forInStmt.lval = this.cast(this.typeCheck(forInStmt.lval), this.checker.stringType); + if(forInStmt.lval.nodeType == TypeScript.NodeType.VarDecl) { + var varDecl = forInStmt.lval; + if(varDecl.typeExpr) { + this.checker.errorReporter.simpleError(varDecl, "Variable declarations for for/in expressions may not contain a type annotation"); + } + if(varDecl.sym) { + varDecl.sym.setType(this.checker.stringType); + } + } + forInStmt.body = this.typeCheck(forInStmt.body); + this.typeCheckCompoundStmtBlock(forInStmt.body, "for in statement"); + return forInStmt; + }; + TypeFlow.prototype.typeCheckWhile = function (whileStmt) { + whileStmt.cond = this.typeCheck(whileStmt.cond); + this.typeCheckCondExpr(whileStmt.cond); + whileStmt.body = this.typeCheck(whileStmt.body); + this.typeCheckCompoundStmtBlock(whileStmt.body, "while statement"); + whileStmt.type = this.voidType; + return whileStmt; + }; + TypeFlow.prototype.typeCheckDoWhile = function (doWhileStmt) { + doWhileStmt.cond = this.typeCheck(doWhileStmt.cond); + this.typeCheckCondExpr(doWhileStmt.cond); + doWhileStmt.body = this.typeCheck(doWhileStmt.body); + this.typeCheckCompoundStmtBlock(doWhileStmt.body, "do while statement"); + doWhileStmt.type = this.voidType; + return doWhileStmt; + }; + TypeFlow.prototype.typeCheckCondExpr = function (cond) { + if(this.checker.styleSettings.assignmentInCond) { + if((cond !== null) && (cond.nodeType >= TypeScript.NodeType.Asg) && (cond.nodeType <= TypeScript.NodeType.LastAsg)) { + this.checker.errorReporter.simpleError(cond, "top-level assignment statement in conditional expression"); + } + } + }; + TypeFlow.prototype.typeCheckCompoundStmtBlock = function (stmts, stmtType) { + if(this.checker.styleSettings.blockInCompoundStmt && stmts) { + if(stmts.nodeType != TypeScript.NodeType.Block) { + this.checker.errorReporter.styleError(stmts, stmtType + " requires a block"); + } + } + }; + TypeFlow.prototype.typeCheckIf = function (ifStmt) { + ifStmt.cond = this.typeCheck(ifStmt.cond); + this.typeCheckCondExpr(ifStmt.cond); + ifStmt.thenBod = this.typeCheck(ifStmt.thenBod); + ifStmt.elseBod = this.typeCheck(ifStmt.elseBod); + this.typeCheckCompoundStmtBlock(ifStmt.thenBod, "if statement"); + this.typeCheckCompoundStmtBlock(ifStmt.elseBod, "if statement"); + ifStmt.type = this.voidType; + return ifStmt; + }; + TypeFlow.prototype.typeFromAccessorFuncDecl = function (funcDecl) { + if(!funcDecl.isAccessor()) { + return null; + } + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { + return funcDecl.type.call.signatures[0].returnType.type; + } else { + return funcDecl.type.call.signatures[0].parameters[0].getType(); + } + }; + TypeFlow.prototype.typeCheckObjectLit = function (objectLit) { + var resultType = new TypeScript.Type(); + resultType.symbol = new TypeScript.TypeSymbol(this.checker.anon, objectLit.minChar, objectLit.limChar - objectLit.minChar, this.checker.locationInfo.unitIndex, resultType); + resultType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + resultType.memberScope = new TypeScript.SymbolTableScope(resultType.members, null, null, null, null); + var aggScope = new TypeScript.SymbolAggregateScope(resultType.symbol); + aggScope.addParentScope(resultType.memberScope); + aggScope.addParentScope(this.scope); + resultType.containedScope = aggScope; + var memberDecls = objectLit.operand; + var prevThisType = this.thisType; + var acceptTargetType = false; + var targetType = null; + if(this.checker.hasTargetType()) { + targetType = this.checker.getTargetTypeContext().contextualType; + if(targetType && targetType.symbol && !this.checker.typeStatusIsFinished(targetType.symbol.typeCheckStatus)) { + if(targetType.symbol.declAST) { + this.typeCheck(targetType.symbol.declAST); + } + } + acceptTargetType = true; + } + if(memberDecls) { + for(var i = 0, len = memberDecls.members.length; i < len; i++) { + var binex = memberDecls.members[i]; + var id = binex.operand1; + var text; + var targetMember = null; + var fieldSymbol = null; + if(id.nodeType == TypeScript.NodeType.Name) { + text = (id).text; + } else { + if(id.nodeType == TypeScript.NodeType.QString) { + var idText = (id).text; + text = idText.substring(1, idText.length - 1); + } else { + this.checker.errorReporter.simpleError(objectLit, "malformed object literal"); + resultType = this.anyType; + break; + } + } + if(acceptTargetType && targetType.memberScope) { + targetMember = targetType.memberScope.find(text, false, false); + } + if(binex.operand2.nodeType == TypeScript.NodeType.FuncDecl && (binex.operand2).isAccessor()) { + var funcDecl = binex.operand2; + var accessorSym = resultType.members.publicMembers.lookup(text); + accessorSym = this.checker.createAccessorSymbol(funcDecl, accessorSym, resultType, true, false, resultType.memberScope, null); + funcDecl.accessorSymbol = accessorSym; + fieldSymbol = accessorSym; + if(id.nodeType == TypeScript.NodeType.Name) { + (id).sym = accessorSym; + } + } + this.checker.typeCheckWithContextualType(acceptTargetType && targetMember ? targetMember.getType() : null, false, acceptTargetType, binex.operand2); + if(acceptTargetType && targetMember) { + if((binex.operand2.type == this.anyType || this.checker.sourceIsAssignableToTarget(binex.operand2.type, targetMember.getType())) || (binex.operand2.nodeType == TypeScript.NodeType.FuncDecl && (binex.operand2).isAccessor() && this.typeFromAccessorFuncDecl(binex.operand2) == targetMember.getType())) { + binex.operand1.type = targetMember.getType(); + } + } else { + binex.operand2.type = binex.operand2.type == this.checker.undefinedType ? this.anyType : binex.operand2.type; + } + if(fieldSymbol == null) { + var memberType = binex.operand2.type; + var field = new TypeScript.ValueLocation(); + fieldSymbol = new TypeScript.FieldSymbol(text, id.minChar, this.checker.locationInfo.unitIndex, true, field); + fieldSymbol.flags |= TypeScript.SymbolFlags.Property; + field.symbol = fieldSymbol; + fieldSymbol.typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); + field.typeLink = new TypeScript.TypeLink(); + field.typeLink.type = memberType; + resultType.members.publicMembers.add(text, fieldSymbol); + } + fieldSymbol.isObjectLitField = true; + } + } + this.thisType = prevThisType; + objectLit.type = resultType; + if(targetType) { + objectLit.targetType = targetType; + } + }; + TypeFlow.prototype.typeCheckArrayLit = function (arrayLit) { + var elements = arrayLit.operand; + var elementType = this.anyType; + var targetElementType = null; + var comparisonInfo = new TypeScript.TypeComparisonInfo(); + comparisonInfo.onlyCaptureFirstError = true; + if(this.checker.hasTargetType()) { + var targetType = this.checker.getTargetTypeContext().contextualType; + if(targetType.elementType) { + targetElementType = targetType.elementType; + } + } + if(elements) { + var prevInArrayElemTypeCheck = this.inArrayElementTypeCheck; + this.inArrayElementTypeCheck = true; + this.checker.typeCheckWithContextualType(targetElementType, this.checker.inProvisionalTypecheckMode(), targetElementType != null, elements); + this.inArrayElementTypeCheck = prevInArrayElemTypeCheck; + elementType = elements.members[0].type; + var collection = { + getLength: function () { + return elements.members.length; + }, + setTypeAtIndex: function (index, type) { + elements.members[index].type = type; + }, + getTypeAtIndex: function (index) { + return elements.members[index].type; + } + }; + elementType = this.checker.findBestCommonType(elementType, targetElementType, collection, false, comparisonInfo); + if(elementType == this.checker.undefinedType || (!prevInArrayElemTypeCheck && elementType == this.nullType)) { + elementType = this.anyType; + } + } + if(!elementType) { + var emsg = "Incompatible types in array literal expression"; + if(!comparisonInfo.message) { + this.checker.errorReporter.simpleError(arrayLit, emsg); + } else { + this.checker.errorReporter.simpleError(arrayLit, emsg + ": " + comparisonInfo.message); + } + elementType = this.anyType; + } else { + if(targetElementType) { + if(this.checker.sourceIsAssignableToTarget(elementType, targetElementType)) { + elementType = targetElementType; + } + } + } + arrayLit.type = this.checker.makeArrayType(elementType); + }; + TypeFlow.prototype.checkForVoidConstructor = function (type, ast) { + if(type && type.construct && type.construct.signatures.length > 0) { + for(var i = 0; i < type.construct.signatures.length; i++) { + if(type.construct.signatures[i].returnType.type == this.checker.voidType) { + this.checker.errorReporter.simpleError(ast, "Constructors may not have a return type of 'void'"); + break; + } + } + } + }; + TypeFlow.prototype.typeCheckReturn = function (returnStmt) { + if(this.thisFnc) { + var targetType = null; + if(this.checker.hasTargetType()) { + var tcContext = this.checker.getTargetTypeContext(); + var accessorType = tcContext.targetAccessorType; + if(accessorType) { + targetType = accessorType; + } else { + var targetSig = this.checker.getTargetTypeContext().targetSig; + if(targetSig && targetSig.returnType.type != this.voidType) { + targetType = targetSig.returnType.type; + } + } + } + if(returnStmt.returnExpression) { + this.thisFnc.fncFlags |= TypeScript.FncFlags.HasReturnExpression; + if(targetType == null && this.thisFnc.returnTypeAnnotation && this.thisFnc.returnTypeAnnotation.type && this.thisFnc.returnTypeAnnotation.type != this.voidType) { + targetType = this.thisFnc.returnTypeAnnotation.type; + } + this.checker.typeCheckWithContextualType(targetType, this.checker.inProvisionalTypecheckMode(), targetType != null, returnStmt.returnExpression); + var expectedReturnType = (this.thisFnc.returnTypeAnnotation && this.thisFnc.returnTypeAnnotation.type) ? this.thisFnc.returnTypeAnnotation.type : targetType; + if(expectedReturnType) { + if(expectedReturnType == this.voidType && returnStmt.returnExpression.type != this.voidType) { + this.checker.errorReporter.simpleError(returnStmt, "Return with value expression in void function"); + returnStmt.type = returnStmt.returnExpression.type; + } else { + returnStmt.returnExpression = this.cast(returnStmt.returnExpression, expectedReturnType); + returnStmt.type = expectedReturnType; + } + } else { + if(targetType) { + if(returnStmt.returnExpression.type != this.voidType) { + returnStmt.returnExpression = this.cast(returnStmt.returnExpression, targetType); + } else { + returnStmt.returnExpression.type = targetType; + } + } + returnStmt.type = returnStmt.returnExpression.type; + } + this.thisFnc.returnStatementsWithExpressions[this.thisFnc.returnStatementsWithExpressions.length] = returnStmt; + } else { + returnStmt.type = targetType == null ? this.checker.voidType : targetType; + } + } + return returnStmt; + }; + TypeFlow.prototype.typeCheckInstOf = function (ast) { + var binex = ast; + binex.operand1 = this.typeCheck(binex.operand1); + binex.operand2 = this.typeCheck(binex.operand2); + if(!((binex.operand1.type == this.checker.anyType || this.checker.sourceIsSubtypeOfTarget(binex.operand1.type, this.objectInterfaceType)) && (binex.operand2.type == this.anyType || this.checker.sourceIsSubtypeOfTarget(binex.operand2.type, this.functionInterfaceType)))) { + this.checker.errorReporter.simpleError(ast, "The instanceof operator requires the left operand to be of type Any or an object type, and the right operand to be of type Any or a subtype of the Function interface type"); + } + binex.type = this.booleanType; + return binex; + }; + TypeFlow.prototype.typeCheckCommaOperator = function (ast) { + var binex = ast; + binex.operand1 = this.typeCheck(binex.operand1); + binex.operand2 = this.typeCheck(binex.operand2); + binex.type = binex.operand2.type; + return binex; + }; + TypeFlow.prototype.typeCheckLogOr = function (binex) { + binex.operand1 = this.typeCheck(binex.operand1); + binex.operand2 = this.typeCheck(binex.operand2); + var leftType = binex.operand1.type; + var rightType = binex.operand2.type; + if(leftType == this.checker.anyType || rightType == this.checker.anyType) { + binex.type = this.checker.anyType; + } else { + if(leftType == this.checker.booleanType) { + if(rightType == this.checker.booleanType) { + binex.type = this.checker.booleanType; + } else { + binex.type = this.checker.anyType; + } + } else { + if(leftType == this.checker.numberType) { + if(rightType == this.checker.numberType) { + binex.type = this.checker.numberType; + } else { + binex.type = this.checker.anyType; + } + } else { + if(leftType == this.checker.stringType) { + if(rightType == this.checker.stringType) { + binex.type = this.checker.stringType; + } else { + binex.type = this.checker.anyType; + } + } else { + if(this.checker.sourceIsSubtypeOfTarget(leftType, rightType)) { + binex.type = rightType; + } else { + if(this.checker.sourceIsSubtypeOfTarget(rightType, leftType)) { + binex.type = leftType; + } else { + binex.type = this.checker.anyType; + } + } + } + } + } + } + return binex; + }; + TypeFlow.prototype.typeCheckLogAnd = function (binex) { + binex.operand1 = this.typeCheck(binex.operand1); + binex.operand2 = this.typeCheck(binex.operand2); + binex.type = binex.operand2.type; + return binex; + }; + TypeFlow.prototype.tryAddCandidates = function (signature, actuals, exactCandidates, conversionCandidates, comparisonInfo) { + var lowerBound = signature.nonOptionalParameterCount; + var upperBound = signature.parameters.length; + var formalLen = lowerBound; + var acceptable = false; + if((actuals.length >= lowerBound) && (signature.hasVariableArgList || actuals.length <= upperBound)) { + formalLen = (signature.hasVariableArgList ? signature.parameters.length : actuals.length); + acceptable = true; + } + var repeatType = null; + if(acceptable || signature.hasVariableArgList) { + if(signature.hasVariableArgList) { + formalLen -= 1; + repeatType = (signature.parameters[formalLen]).parameter.typeLink.type; + repeatType = repeatType.elementType; + acceptable = actuals.length >= formalLen; + } + var len = actuals.length; + var exact = acceptable; + var convert = acceptable; + for(var i = 0; i < len; i++) { + var typeA; + if(i < formalLen) { + typeA = (signature.parameters[i]).parameter.typeLink.type; + } else { + typeA = repeatType; + } + var typeB = actuals[i]; + if(!typeA || !typeB || !(this.checker.typesAreIdentical(typeA, typeB))) { + exact = false; + } + if(!this.checker.sourceIsAssignableToTarget(typeB, typeA, comparisonInfo)) { + convert = false; + } + if(!(exact || convert)) { + break; + } + } + if(exact) { + exactCandidates[exactCandidates.length] = signature; + } else { + if(convert && (exactCandidates.length == 0)) { + conversionCandidates[conversionCandidates.length] = signature; + } + } + } + }; + TypeFlow.prototype.resolveOverload = function (application, group) { + var rd = this.resolutionDataCache.getResolutionData(); + var actuals = rd.actuals; + var exactCandidates = rd.exactCandidates; + var conversionCandidates = rd.conversionCandidates; + var candidate = null; + var hasOverloads = group.signatures.length > 1; + var comparisonInfo = new TypeScript.TypeComparisonInfo(); + var args = null; + var target = null; + if(application.nodeType == TypeScript.NodeType.Call || application.nodeType == TypeScript.NodeType.New) { + var callEx = application; + args = callEx.arguments; + target = callEx.target; + if(callEx.arguments) { + var len = callEx.arguments.members.length; + for(var i = 0; i < len; i++) { + actuals[i] = callEx.arguments.members[i].type; + } + } + } else { + if(application.nodeType == TypeScript.NodeType.Index) { + var binExp = application; + target = binExp.operand1; + args = new TypeScript.ASTList(); + args.members[0] = binExp.operand2; + actuals[0] = binExp.operand2.type; + } + } + for(var j = 0, groupLen = group.signatures.length; j < groupLen; j++) { + var signature = group.signatures[j]; + if(hasOverloads && signature == group.definitionSignature && !this.checker.canCallDefinitionSignature) { + continue; + } + if(!signature.returnType.type && signature.declAST && (signature.typeCheckStatus != TypeScript.TypeCheckStatus.Finished)) { + this.typeCheckFunction(signature.declAST); + } + this.tryAddCandidates(signature, actuals, exactCandidates, conversionCandidates, comparisonInfo); + } + if(exactCandidates.length == 0) { + var applicableCandidates = this.checker.getApplicableSignatures(conversionCandidates, args, comparisonInfo); + if(applicableCandidates.length > 0) { + var candidateInfo = this.checker.findMostApplicableSignature(applicableCandidates, args); + if(candidateInfo.ambiguous) { + this.checker.errorReporter.simpleError(target, "Ambiguous call expression - could not choose overload"); + } + candidate = candidateInfo.sig; + } else { + var emsg = "Supplied parameters do not match any signature of call target"; + if(comparisonInfo.message) { + this.checker.errorReporter.simpleError(target, emsg + ":\n\t" + comparisonInfo.message); + } else { + this.checker.errorReporter.simpleError(target, emsg); + } + } + } else { + if(exactCandidates.length > 1) { + var applicableSigs = []; + for(var i = 0; i < exactCandidates.length; i++) { + applicableSigs[i] = { + signature: exactCandidates[i], + hadProvisionalErrors: false + }; + } + var candidateInfo = this.checker.findMostApplicableSignature(applicableSigs, args); + if(candidateInfo.ambiguous) { + this.checker.errorReporter.simpleError(target, "Ambiguous call expression - could not choose overload"); + } + candidate = candidateInfo.sig; + } else { + candidate = exactCandidates[0]; + } + } + this.resolutionDataCache.returnResolutionData(rd); + return candidate; + }; + TypeFlow.prototype.typeCheckNew = function (ast) { + var callEx = ast; + callEx.target = this.typeCheck(callEx.target); + var target = callEx.target; + if(target.type.construct || target.type.call) { + this.preTypeCheckCallArgs(callEx.arguments); + } else { + callEx.arguments = this.typeCheck(callEx.arguments); + } + if(target.type == this.anyType) { + callEx.type = this.anyType; + callEx.arguments = this.typeCheck(callEx.arguments); + } else { + if(target.type.construct) { + var signature = this.resolveOverload(callEx, target.type.construct); + if(signature == null) { + callEx.type = this.anyType; + } else { + if(signature.returnType.type == this.voidType) { + callEx.type = this.anyType; + callEx.signature = signature; + } else { + callEx.type = signature.returnType.type; + callEx.signature = signature; + } + } + } else { + if(target.type.call) { + var signature = this.resolveOverload(callEx, target.type.call); + if(signature == null) { + callEx.type = this.anyType; + } else { + if((signature.returnType.type == this.voidType) || (signature.returnType.type == this.anyType)) { + callEx.type = this.anyType; + callEx.signature = signature; + } else { + this.checker.errorReporter.simpleError(callEx.target, "new expression only valid on constructors"); + } + } + } else { + if(target.type.elementType) { + callEx.type = target.type; + } else { + this.checker.errorReporter.invalidCall(callEx, callEx.nodeType, this.scope); + callEx.type = this.anyType; + } + } + } + } + this.postTypeCheckCallArgs(callEx); + return callEx; + }; + TypeFlow.prototype.preTypeCheckCallArgs = function (args) { + if(!args) { + return; + } + for(var i = 0; i < args.members.length; i++) { + switch(args.members[i].nodeType) { + case TypeScript.NodeType.FuncDecl: + case TypeScript.NodeType.ObjectLit: + case TypeScript.NodeType.ArrayLit: { + continue; + + } + default: { + this.typeCheck(args.members[i]); + break; + + } + } + } + }; + TypeFlow.prototype.postTypeCheckCallArgs = function (callEx) { + var acceptedTargetType = false; + var i = 0; + if(callEx.target && callEx.target.type && callEx.signature && callEx.arguments) { + var sig = callEx.signature; + if(sig && callEx.arguments.members.length >= sig.nonOptionalParameterCount) { + acceptedTargetType = true; + var targetType = null; + var nonVarArgFormalParamLength = sig.hasVariableArgList ? sig.parameters.length - 1 : sig.parameters.length; + var nonVarArgActualParamLength = callEx.arguments.members.length < nonVarArgFormalParamLength ? callEx.arguments.members.length : nonVarArgFormalParamLength; + for(i = 0; i < nonVarArgActualParamLength; i++) { + targetType = sig.parameters[i].getType(); + switch(callEx.arguments.members[i].nodeType) { + case TypeScript.NodeType.FuncDecl: + case TypeScript.NodeType.ObjectLit: + case TypeScript.NodeType.ArrayLit: { + this.checker.typeCheckWithContextualType(targetType, this.checker.inProvisionalTypecheckMode(), !sig.parameters[i].declAST.isParenthesized, callEx.arguments.members[i]); + break; + + } + } + } + if(sig.hasVariableArgList) { + var varArgParamIndex = sig.nonOptionalParameterCount - 1; + targetType = sig.parameters[varArgParamIndex].getType(); + if(targetType) { + targetType = targetType.elementType; + } + var isParenthesized = !sig.parameters[varArgParamIndex].declAST.isParenthesized; + for(i = nonVarArgActualParamLength; i < callEx.arguments.members.length; i++) { + switch(callEx.arguments.members[i].nodeType) { + case TypeScript.NodeType.FuncDecl: + case TypeScript.NodeType.ObjectLit: + case TypeScript.NodeType.ArrayLit: { + this.checker.typeCheckWithContextualType(targetType, this.checker.inProvisionalTypecheckMode(), isParenthesized, callEx.arguments.members[i]); + break; + + } + } + } + } + } + } + if(!acceptedTargetType && callEx.arguments) { + this.checker.killCurrentContextualType(); + for(i = 0; i < callEx.arguments.members.length; i++) { + switch(callEx.arguments.members[i].nodeType) { + case TypeScript.NodeType.FuncDecl: + case TypeScript.NodeType.ObjectLit: + case TypeScript.NodeType.ArrayLit: { + this.typeCheck(callEx.arguments.members[i]); + break; + + } + default: { + continue; + + } + } + } + } + }; + TypeFlow.prototype.typeCheckCall = function (ast) { + var callEx = ast; + if(this.checker.styleSettings.newMustBeUsed && (ast.nodeType == TypeScript.NodeType.New)) { + if(TypeScript.hasFlag(ast.flags, TypeScript.ASTFlags.IsStatement)) { + this.checker.errorReporter.styleError(ast, "use of new expression as a statement"); + } + } else { + if((!this.checker.styleSettings.evalOK) && (ast.nodeType == TypeScript.NodeType.Call)) { + if((callEx.target.nodeType == TypeScript.NodeType.Name) && ((callEx.target).text == "eval")) { + this.checker.errorReporter.styleError(callEx, "eval not permitted"); + } + } + } + if(callEx.target.nodeType == TypeScript.NodeType.FuncDecl) { + (callEx.target).isInlineCallLiteral = true; + } + var prevInSuperCall = this.inSuperCall; + if(callEx.target.nodeType == TypeScript.NodeType.Super) { + this.inSuperCall = true; + } + callEx.target = this.typeCheck(callEx.target); + this.preTypeCheckCallArgs(callEx.arguments); + var target = callEx.target; + if((target.type == null) || (target.type == this.anyType) || (this.functionInterfaceType && target.type == this.functionInterfaceType)) { + callEx.type = this.anyType; + } else { + var fnType = target.type; + if(fnType.call) { + var signature = this.resolveOverload(callEx, fnType.call); + if(signature == null) { + callEx.type = this.anyType; + } else { + callEx.type = signature.returnType.type; + callEx.signature = signature; + } + } else { + if(callEx.target.nodeType == TypeScript.NodeType.Super && this.thisFnc && this.thisFnc.isConstructor && TypeScript.hasFlag(this.thisFnc.fncFlags, TypeScript.FncFlags.ClassMethod)) { + var signature = fnType.symbol.type.construct ? this.resolveOverload(callEx, fnType.symbol.type.construct) : null; + if(signature == null) { + callEx.type = this.anyType; + } else { + callEx.flags |= TypeScript.ASTFlags.ClassBaseConstructorCall; + callEx.type = signature.returnType.type; + callEx.signature = signature; + } + } else { + callEx.type = this.anyType; + this.checker.errorReporter.invalidCall(callEx, callEx.nodeType, this.scope); + } + } + } + this.postTypeCheckCallArgs(callEx); + this.inSuperCall = prevInSuperCall; + return callEx; + }; + TypeFlow.prototype.assignScopes = function (ast) { + var script = ast; + this.checker.locationInfo = script.locationInfo; + var globalChain = new ScopeChain(this.checker.gloMod, null, this.globalScope); + var context = new TypeScript.AssignScopeContext(globalChain, this, [ + this.checker.currentModDecl + ]); + TypeScript.getAstWalkerFactory().walk(ast, TypeScript.preAssignScopes, TypeScript.postAssignScopes, null, context); + }; + TypeFlow.prototype.findMemberScope = function (enclosingScopeContext, matchFlag) { + var enclosingScope = enclosingScopeContext.getScope(); + var pos = enclosingScopeContext.pos - enclosingScopeContext.getScriptFragmentPosition(); + var scriptFragment = enclosingScopeContext.getScriptFragment(); + var memContext = new TypeScript.MemberScopeContext(this, pos, matchFlag); + memContext.scope = enclosingScope; + if(scriptFragment.nodeType == TypeScript.NodeType.Name) { + return scriptFragment.type.getMemberScope(this); + } else { + TypeScript.getAstWalkerFactory().walk(scriptFragment, TypeScript.preFindMemberScope, null, null, memContext); + if(memContext.ast && enclosingScopeContext.enclosingClassDecl && memContext.ast.type == enclosingScopeContext.enclosingClassDecl.type.instanceType) { + enclosingScopeContext.publicsOnly = false; + } + if(memContext.type) { + return memContext.type.getMemberScope(this); + } else { + return null; + } + } + }; + TypeFlow.prototype.findMemberScopeAt = function (enclosingScopeContext) { + return this.findMemberScope(enclosingScopeContext, TypeScript.ASTFlags.DotLHS); + }; + TypeFlow.prototype.findMemberScopeAtFullAst = function (enclosingScopeContext) { + var matchFlag = TypeScript.ASTFlags.DotLHS; + var pos = enclosingScopeContext.pos; + var astResult = null; + var preFindMemberScopeFullAst = function (ast, parent, walker) { + if(TypeScript.isValidAstNode(ast)) { + if(TypeScript.hasFlag(ast.flags, matchFlag) && (pos == ast.limChar || (pos - 1) == ast.limChar)) { + astResult = ast; + walker.options.stopWalk(); + } + walker.options.goChildren = (ast.minChar <= pos) && (pos <= ast.limChar); + } + return ast; + }; + var preFindMemberScopeFullAstFuzy = function (ast, parent, walker) { + if(TypeScript.isValidAstNode(ast)) { + if(TypeScript.hasFlag(ast.flags, matchFlag) && ((ast.minChar < pos) && (pos <= ast.limChar))) { + astResult = ast; + } + walker.options.goChildren = (ast.minChar <= pos) && (pos <= ast.limChar); + } + return ast; + }; + TypeScript.getAstWalkerFactory().walk(enclosingScopeContext.script, preFindMemberScopeFullAst); + if(astResult == null) { + TypeScript.getAstWalkerFactory().walk(enclosingScopeContext.script, preFindMemberScopeFullAstFuzy); + } + if(astResult && enclosingScopeContext.enclosingClassDecl && astResult.type == enclosingScopeContext.enclosingClassDecl.type.instanceType) { + enclosingScopeContext.publicsOnly = false; + } + if(astResult && astResult.type) { + return astResult.type.getMemberScope(this); + } else { + return null; + } + }; + return TypeFlow; + })(); + TypeScript.TypeFlow = TypeFlow; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Primitive) { + Primitive._map = []; + Primitive.None = 0; + Primitive.Void = 1; + Primitive.Double = 2; + Primitive.String = 4; + Primitive.Boolean = 8; + Primitive.Any = 16; + Primitive.Null = 32; + Primitive.Undefined = 64; + })(TypeScript.Primitive || (TypeScript.Primitive = {})); + var Primitive = TypeScript.Primitive; + var MemberName = (function () { + function MemberName() { + this.prefix = ""; + this.suffix = ""; + } + MemberName.prototype.isString = function () { + return false; + }; + MemberName.prototype.isArray = function () { + return false; + }; + MemberName.prototype.toString = function () { + return MemberName.memberNameToString(this); + }; + MemberName.memberNameToString = function memberNameToString(memberName) { + var result = memberName.prefix; + if(memberName.isString()) { + result += (memberName).text; + } else { + var ar = memberName; + for(var index = 0; index < ar.entries.length; index++) { + result += MemberName.memberNameToString(ar.entries[index]); + result += ar.delim; + } + } + result += memberName.suffix; + return result; + } + MemberName.create = function create(arg1, arg2, arg3) { + if(typeof arg1 == "string") { + return new MemberNameString(arg1); + } else { + var result = new MemberNameArray(); + if(arg2) { + result.prefix = arg2; + } + if(arg3) { + result.suffix = arg3; + } + result.entries.push(arg1); + return result; + } + } + return MemberName; + })(); + TypeScript.MemberName = MemberName; + var MemberNameString = (function (_super) { + __extends(MemberNameString, _super); + function MemberNameString(text) { + _super.call(this); + this.text = text; + } + MemberNameString.prototype.isString = function () { + return true; + }; + return MemberNameString; + })(MemberName); + TypeScript.MemberNameString = MemberNameString; + var MemberNameArray = (function (_super) { + __extends(MemberNameArray, _super); + function MemberNameArray() { + _super.apply(this, arguments); + + this.delim = ""; + this.entries = []; + } + MemberNameArray.prototype.isArray = function () { + return true; + }; + MemberNameArray.prototype.add = function (entry) { + this.entries.push(entry); + }; + MemberNameArray.prototype.addAll = function (entries) { + for(var i = 0; i < entries.length; i++) { + this.entries.push(entries[i]); + } + }; + return MemberNameArray; + })(MemberName); + TypeScript.MemberNameArray = MemberNameArray; + var currentTypeID = -1; + var Type = (function () { + function Type() { + this.typeID = currentTypeID++; + this.construct = null; + this.call = null; + this.index = null; + this.passTypeCreated = TypeScript.CompilerDiagnostics.analysisPass; + this.primitiveTypeClass = Primitive.None; + this.typeFlags = TypeScript.TypeFlags.None; + } + Type.prototype.baseClass = function () { + if(this.extendsList && (this.extendsList.length > 0)) { + return this.extendsList[0]; + } else { + return null; + } + }; + Type.prototype.getArrayBase = function (arrInstType, checker) { + return this.arrayCache.specialize(arrInstType, checker); + }; + Type.prototype.isClass = function () { + return this.instanceType != null; + }; + Type.prototype.isArray = function () { + return this.elementType != null; + }; + Type.prototype.isClassInstance = function () { + return this.symbol && !this.elementType && (this.symbol).type.isClass(); + }; + Type.prototype.getInstanceType = function () { + if(this.isClass()) { + return this.instanceType; + } else { + return this; + } + }; + Type.prototype.hasImplementation = function () { + return TypeScript.hasFlag(this.typeFlags, TypeScript.TypeFlags.HasImplementation); + }; + Type.prototype.setHasImplementation = function () { + this.typeFlags |= TypeScript.TypeFlags.HasImplementation; + }; + Type.prototype.isDouble = function () { + return TypeScript.hasFlag(this.primitiveTypeClass, Primitive.Double); + }; + Type.prototype.isString = function () { + return TypeScript.hasFlag(this.primitiveTypeClass, Primitive.String); + }; + Type.prototype.isBoolean = function () { + return TypeScript.hasFlag(this.primitiveTypeClass, Primitive.Boolean); + }; + Type.prototype.isNull = function () { + return TypeScript.hasFlag(this.primitiveTypeClass, Primitive.Null); + }; + Type.prototype.getTypeName = function () { + return this.getMemberTypeName("", true, false, null); + }; + Type.prototype.getScopedTypeName = function (scope) { + return this.getMemberTypeName("", true, false, scope); + }; + Type.prototype.getScopedTypeNameEx = function (scope) { + return this.getMemberTypeNameEx("", true, false, scope); + }; + Type.prototype.callCount = function () { + var total = 0; + if(this.call) { + total += this.call.signatures.length; + } + if(this.construct) { + total += this.construct.signatures.length; + } + if(this.index) { + total += this.index.signatures.length; + } + return total; + }; + Type.prototype.getMemberTypeName = function (prefix, topLevel, isElementType, scope) { + var memberName = this.getMemberTypeNameEx(prefix, topLevel, isElementType, scope); + return memberName.toString(); + }; + Type.prototype.getMemberTypeNameEx = function (prefix, topLevel, isElementType, scope) { + if(this.elementType) { + return MemberName.create(this.elementType.getMemberTypeNameEx(prefix, false, true, scope), "", "[]"); + } else { + if(this.symbol && this.symbol.name && this.symbol.name != "_anonymous" && (((this.call == null) && (this.construct == null) && (this.index == null)) || (TypeScript.hasFlag(this.typeFlags, TypeScript.TypeFlags.BuildingName)) || (this.members && (!this.isClass())))) { + var tn = this.symbol.scopeRelativeName(scope); + return MemberName.create(tn == "null" ? "any" : tn); + } else { + if(this.members || this.call || this.construct) { + if(TypeScript.hasFlag(this.typeFlags, TypeScript.TypeFlags.BuildingName)) { + return MemberName.create("this"); + } + this.typeFlags |= TypeScript.TypeFlags.BuildingName; + var builder = ""; + var allMemberNames = new MemberNameArray(); + var curlies = isElementType || this.index != null; + var memCount = 0; + var delim = "; "; + if(this.members) { + this.members.allMembers.map(function (key, s, unused) { + var sym = s; + if(!TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.BuiltIn)) { + var typeNameMember = sym.getTypeNameEx(scope); + if(typeNameMember.isArray() && (typeNameMember).delim == delim) { + allMemberNames.addAll((typeNameMember).entries); + } else { + allMemberNames.add(typeNameMember); + } + memCount++; + curlies = true; + } + }, null); + } + var signatureCount = this.callCount(); + var j; + var len = 0; + var shortform = !curlies && signatureCount == 1 && topLevel; + if(this.call) { + allMemberNames.addAll(this.call.toStrings(prefix, shortform, scope)); + } + if(this.construct) { + allMemberNames.addAll(this.construct.toStrings("new", shortform, scope)); + } + if(this.index) { + allMemberNames.addAll(this.index.toStrings("", shortform, scope)); + } + if((curlies) || ((signatureCount > 1) && topLevel)) { + allMemberNames.prefix = "{ "; + allMemberNames.suffix = "}"; + allMemberNames.delim = delim; + } else { + if(allMemberNames.entries.length > 1) { + allMemberNames.delim = delim; + } + } + this.typeFlags &= (~TypeScript.TypeFlags.BuildingName); + if((signatureCount == 0) && (memCount == 0)) { + return MemberName.create("{}"); + } else { + return allMemberNames; + } + } else { + return MemberName.create("{}"); + } + } + } + }; + Type.prototype.checkDecl = function (checker) { + if(this.isClassInstance() || this.isClass()) { + if(this.symbol.declAST) { + checker.typeFlow.inScopeTypeCheckDecl(this.symbol.declAST); + } + } + }; + Type.prototype.getMemberScope = function (flow) { + if(this == flow.anyType) { + return null; + } else { + if(this.isDouble()) { + if(flow.numberInterfaceType) { + return flow.numberInterfaceType.memberScope; + } else { + return null; + } + } else { + if(this.isBoolean()) { + if(flow.booleanInterfaceType) { + return flow.booleanInterfaceType.memberScope; + } else { + return null; + } + } else { + if(this == flow.stringType) { + if(flow.stringInterfaceType) { + return flow.stringInterfaceType.memberScope; + } else { + return null; + } + } else { + if(this.elementType) { + if(flow.arrayInterfaceType) { + var arrInstType = this.elementType.getArrayBase(flow.arrayInterfaceType, flow.checker); + return arrInstType.memberScope; + } else { + return null; + } + } else { + return this.memberScope; + } + } + } + } + } + }; + Type.prototype.isReferenceType = function () { + return this.members || this.extendsList || this.construct || this.call || this.index || this.elementType; + }; + Type.prototype.specializeType = function (pattern, replacement, checker, membersOnly) { + if(pattern == this) { + return replacement; + } + var result = this; + if(membersOnly) { + if(this.isReferenceType()) { + result = new Type(); + if(this.members) { + result.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + this.members.publicMembers.map(function (key, s, unused) { + var sym = s; + var bSym = sym.specializeType(pattern, replacement, checker); + result.members.addPublicMember(bSym.name, bSym); + }, null); + this.members.privateMembers.map(function (key, s, unused) { + var sym = s; + var bSym = sym.specializeType(pattern, replacement, checker); + result.members.addPrivateMember(bSym.name, bSym); + }, null); + } + if(this.ambientMembers) { + result.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + this.ambientMembers.publicMembers.map(function (key, s, unused) { + var sym = s; + var bSym = sym.specializeType(pattern, replacement, checker); + result.ambientMembers.addPublicMember(bSym.name, bSym); + }, null); + this.ambientMembers.privateMembers.map(function (key, s, unused) { + var sym = s; + var bSym = sym.specializeType(pattern, replacement, checker); + result.ambientMembers.addPrivateMember(bSym.name, bSym); + }, null); + } + result.containedScope = checker.scopeOf(result); + result.memberScope = result.containedScope; + } + } else { + if(this.elementType) { + if(this.elementType == pattern) { + result = checker.makeArrayType(replacement); + } else { + if(this.elementType.elementType == pattern) { + result = checker.makeArrayType(checker.makeArrayType(replacement)); + } + } + } else { + if(this.call) { + result = new Type(); + result.call = this.call.specializeType(pattern, replacement, checker); + } + } + } + return result; + }; + Type.prototype.hasBase = function (baseType) { + if(baseType == this) { + return true; + } else { + if(this.extendsList) { + for(var i = 0, len = this.extendsList.length; i < len; i++) { + if(this.extendsList[i].hasBase(baseType)) { + return true; + } + } + } + } + return false; + }; + Type.prototype.mergeOrdered = function (b, checker, acceptVoid, comparisonInfo) { + if((this == checker.anyType) || (b == checker.anyType)) { + return checker.anyType; + } else { + if(this == b) { + return this; + } else { + if((b == checker.nullType) && this != checker.nullType) { + return this; + } else { + if((this == checker.nullType) && (b != checker.nullType)) { + return b; + } else { + if(acceptVoid && (b == checker.voidType) && this != checker.voidType) { + return this; + } else { + if(acceptVoid && (this == checker.voidType) && (b != checker.voidType)) { + return b; + } else { + if((b == checker.undefinedType) && this != checker.undefinedType) { + return this; + } else { + if((this == checker.undefinedType) && (b != checker.undefinedType)) { + return b; + } else { + if(this.elementType && b.elementType) { + if(this.elementType == b.elementType) { + return this; + } else { + var mergedET = this.elementType.mergeOrdered(b.elementType, checker, acceptVoid, comparisonInfo); + if(mergedET == null) { + return checker.makeArrayType(checker.anyType); + } else { + return checker.makeArrayType(mergedET); + } + } + } else { + if(checker.sourceIsSubtypeOfTarget(this, b, comparisonInfo)) { + return b; + } else { + if(checker.sourceIsSubtypeOfTarget(b, this, comparisonInfo)) { + return this; + } else { + return null; + } + } + } + } + } + } + } + } + } + } + } + }; + Type.prototype.isModuleType = function () { + return false; + }; + Type.prototype.hasMembers = function () { + return this.members != null; + }; + Type.prototype.getAllEnclosedTypes = function () { + return null; + }; + Type.prototype.getAllAmbientEnclosedTypes = function () { + return null; + }; + Type.prototype.getPublicEnclosedTypes = function () { + return null; + }; + Type.prototype.getpublicAmbientEnclosedTypes = function () { + return null; + }; + Type.prototype.getDocComments = function () { + if(this.elementType || !this.symbol) { + return []; + } + if(this.isClassInstance() || this.isClass()) { + if(this.symbol.declAST.nodeType == TypeScript.NodeType.FuncDecl) { + return (this.symbol.declAST).classDecl.getDocComments(); + } else { + return this.symbol.getDocComments(); + } + } + if(this.symbol.name && this.symbol.name != "_anonymous" && (((this.call == null) && (this.construct == null) && (this.index == null)) || this.members)) { + return this.symbol.getDocComments(); + } + return []; + }; + return Type; + })(); + TypeScript.Type = Type; + var ModuleType = (function (_super) { + __extends(ModuleType, _super); + function ModuleType(enclosedTypes, ambientEnclosedTypes) { + _super.call(this); + this.enclosedTypes = enclosedTypes; + this.ambientEnclosedTypes = ambientEnclosedTypes; + this.importedModules = []; + } + ModuleType.prototype.isModuleType = function () { + return true; + }; + ModuleType.prototype.hasMembers = function () { + return this.members != null || this.enclosedTypes != null; + }; + ModuleType.prototype.getAllEnclosedTypes = function () { + return this.enclosedTypes; + }; + ModuleType.prototype.getAllAmbientEnclosedTypes = function () { + return this.ambientEnclosedTypes; + }; + ModuleType.prototype.getPublicEnclosedTypes = function () { + return null; + }; + ModuleType.prototype.getpublicAmbientEnclosedTypes = function () { + return null; + }; + ModuleType.findDynamicModuleNameInHashTable = function findDynamicModuleNameInHashTable(moduleType, members) { + var moduleName = null; + members.map(function (key, s, c) { + if(moduleName == null && !TypeScript.isQuoted(key)) { + var symbol = s; + var type = symbol.getType(); + if(type == moduleType) { + moduleName = { + name: key, + symbol: symbol + }; + } + } + }, null); + return moduleName; + } + ModuleType.prototype.findDynamicModuleName = function (moduleType) { + var moduleName = null; + moduleName = ModuleType.findDynamicModuleNameInHashTable(moduleType, this.members.allMembers); + if(moduleName == null) { + moduleName = ModuleType.findDynamicModuleNameInHashTable(moduleType, this.ambientMembers.allMembers); + } + return moduleName; + }; + return ModuleType; + })(Type); + TypeScript.ModuleType = ModuleType; + var TypeLink = (function () { + function TypeLink() { + this.type = null; + this.ast = null; + } + return TypeLink; + })(); + TypeScript.TypeLink = TypeLink; + function getTypeLink(ast, checker, autoVar) { + var result = new TypeLink(); + result.ast = ast; + if((ast == null) && (autoVar)) { + result.type = checker.anyType; + } else { + result.type = null; + } + return result; + } + TypeScript.getTypeLink = getTypeLink; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + function stripQuotes(str) { + return str.replace("\"", "").replace("'", "").replace("'", "").replace("\"", ""); + } + TypeScript.stripQuotes = stripQuotes; + function isQuoted(str) { + return str.indexOf("\"") != -1 || str.indexOf("'") != -1 || str.indexOf("'") != -1 || str.indexOf("\"") != -1; + } + TypeScript.isQuoted = isQuoted; + function quoteStr(str) { + return "\"" + str + "\""; + } + TypeScript.quoteStr = quoteStr; + function swapQuotes(str) { + if(str.indexOf("\"") != -1) { + str = str.replace("\"", "'"); + str = str.replace("\"", "'"); + } else { + str = str.replace("'", "\""); + str = str.replace("'", "\""); + } + return str; + } + TypeScript.swapQuotes = swapQuotes; + function switchToForwardSlashes(path) { + return path.replace(/\\/g, "/"); + } + TypeScript.switchToForwardSlashes = switchToForwardSlashes; + function trimModName(modName) { + if(modName.length > 6 && modName.substring(modName.length - 6, modName.length) == ".d.str") { + return modName.substring(0, modName.length - 6); + } + if(modName.length > 4 && modName.substring(modName.length - 4, modName.length) == ".str") { + return modName.substring(0, modName.length - 4); + } + if(modName.length > 5 && modName.substring(modName.length - 5, modName.length) == ".d.ts") { + return modName.substring(0, modName.length - 5); + } + if(modName.length > 3 && modName.substring(modName.length - 3, modName.length) == ".ts") { + return modName.substring(0, modName.length - 3); + } + if(modName.length > 3 && modName.substring(modName.length - 3, modName.length) == ".js") { + return modName.substring(0, modName.length - 3); + } + return modName; + } + TypeScript.trimModName = trimModName; + function getDeclareFilePath(fname) { + return isSTRFile(fname) ? changePathToDSTR(fname) : isTSFile(fname) ? changePathToDTS(fname) : changePathToDTS(fname); + } + TypeScript.getDeclareFilePath = getDeclareFilePath; + function isFileOfExtension(fname, ext) { + var invariantFname = fname.toLocaleUpperCase(); + var invariantExt = ext.toLocaleUpperCase(); + var extLength = invariantExt.length; + return invariantFname.length > extLength && invariantFname.substring(invariantFname.length - extLength, invariantFname.length) == invariantExt; + } + function isJSFile(fname) { + return isFileOfExtension(fname, ".js"); + } + TypeScript.isJSFile = isJSFile; + function isSTRFile(fname) { + return isFileOfExtension(fname, ".str"); + } + TypeScript.isSTRFile = isSTRFile; + function isTSFile(fname) { + return isFileOfExtension(fname, ".ts"); + } + TypeScript.isTSFile = isTSFile; + function isDSTRFile(fname) { + return isFileOfExtension(fname, ".d.str"); + } + TypeScript.isDSTRFile = isDSTRFile; + function isDTSFile(fname) { + return isFileOfExtension(fname, ".d.ts"); + } + TypeScript.isDTSFile = isDTSFile; + function getPrettyName(modPath, quote, treatAsFileName) { + if (typeof quote === "undefined") { quote = true; } + if (typeof treatAsFileName === "undefined") { treatAsFileName = false; } + var modName = treatAsFileName ? switchToForwardSlashes(modPath) : trimModName(stripQuotes(modPath)); + var components = this.getPathComponents(modName); + return components.length ? (quote ? quoteStr(components[components.length - 1]) : components[components.length - 1]) : modPath; + } + TypeScript.getPrettyName = getPrettyName; + function getPathComponents(path) { + return path.split("/"); + } + TypeScript.getPathComponents = getPathComponents; + function getRelativePathToFixedPath(fixedModFilePath, absoluteModPath) { + absoluteModPath = switchToForwardSlashes(absoluteModPath); + var modComponents = this.getPathComponents(absoluteModPath); + var fixedModComponents = this.getPathComponents(fixedModFilePath); + var joinStartIndex = 0; + for(; joinStartIndex < modComponents.length && joinStartIndex < fixedModComponents.length; joinStartIndex++) { + if(fixedModComponents[joinStartIndex] != modComponents[joinStartIndex]) { + break; + } + } + if(joinStartIndex != 0) { + var relativePath = ""; + var relativePathComponents = modComponents.slice(joinStartIndex, modComponents.length); + for(; joinStartIndex < fixedModComponents.length; joinStartIndex++) { + if(fixedModComponents[joinStartIndex] != "") { + relativePath = relativePath + "../"; + } + } + return relativePath + relativePathComponents.join("/"); + } + return absoluteModPath; + } + TypeScript.getRelativePathToFixedPath = getRelativePathToFixedPath; + function quoteBaseName(modPath) { + var modName = trimModName(stripQuotes(modPath)); + var path = getRootFilePath(modName); + if(path == "") { + return modPath; + } else { + var components = modName.split(path); + var fileIndex = components.length > 1 ? 1 : 0; + return quoteStr(components[fileIndex]); + } + } + TypeScript.quoteBaseName = quoteBaseName; + function changePathToSTR(modPath) { + return trimModName(stripQuotes(modPath)) + ".str"; + } + TypeScript.changePathToSTR = changePathToSTR; + function changePathToDSTR(modPath) { + return trimModName(stripQuotes(modPath)) + ".d.str"; + } + TypeScript.changePathToDSTR = changePathToDSTR; + function changePathToTS(modPath) { + return trimModName(stripQuotes(modPath)) + ".ts"; + } + TypeScript.changePathToTS = changePathToTS; + function changePathToDTS(modPath) { + return trimModName(stripQuotes(modPath)) + ".d.ts"; + } + TypeScript.changePathToDTS = changePathToDTS; + function isRelative(path) { + return path.charAt(0) == "."; + } + TypeScript.isRelative = isRelative; + function isRooted(path) { + return path.charAt(0) == "\\" || path.charAt(0) == "/" || (path.indexOf(":\\") != -1) || (path.indexOf(":/") != -1); + } + TypeScript.isRooted = isRooted; + function getRootFilePath(outFname) { + if(outFname == "") { + return outFname; + } else { + var isPath = outFname.indexOf("/") != -1; + return isPath ? filePath(outFname) : ""; + } + } + TypeScript.getRootFilePath = getRootFilePath; + function filePathComponents(fullPath) { + fullPath = switchToForwardSlashes(fullPath); + var components = getPathComponents(fullPath); + return components.slice(0, components.length - 1); + } + TypeScript.filePathComponents = filePathComponents; + function filePath(fullPath) { + var path = filePathComponents(fullPath); + return path.join("/") + "/"; + } + TypeScript.filePath = filePath; + function normalizeURL(url) { + var hostDomainAndPortRegex = /^(https?:\/\/[\-\w\.]+(:\d+)?\/)(.*)$/i; + var matches = hostDomainAndPortRegex.exec(url); + if(matches) { + var hostDomainAndPort = matches[1]; + var actualPath = matches[3]; + return hostDomainAndPort + normalizePath(actualPath); + } + return normalizePath(url); + } + TypeScript.normalizeURL = normalizeURL; + TypeScript.pathNormalizeRegExp = /\//g; + function normalizePath(path) { + path = switchToForwardSlashes(path); + var startedWithSep = path.charAt(0) === "/"; + var parts = this.getPathComponents(path); + for(var i = 0; i < parts.length; i++) { + if(parts[i] === "." || parts[i] === "") { + parts.splice(i, 1); + i--; + } + if(i > 0 && parts[i] === ".." && parts[i - 1] !== "..") { + parts.splice(i - 1, 2); + i -= 2; + } + } + return (startedWithSep ? "/" : "") + parts.join("/"); + } + TypeScript.normalizePath = normalizePath; + function normalizeImportPath(path) { + return normalizePath(path); + } + TypeScript.normalizeImportPath = normalizeImportPath; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SourceUnit = (function () { + function SourceUnit(path, content) { + this.path = path; + this.content = content; + this.referencedFiles = null; + } + SourceUnit.prototype.getText = function (start, end) { + return this.content.substring(start, end); + }; + SourceUnit.prototype.getLength = function () { + return this.content.length; + }; + return SourceUnit; + })(); + TypeScript.SourceUnit = SourceUnit; + var CompilationEnvironment = (function () { + function CompilationEnvironment(compilationSettings, ioHost) { + this.compilationSettings = compilationSettings; + this.ioHost = ioHost; + this.residentCode = []; + this.code = []; + } + return CompilationEnvironment; + })(); + TypeScript.CompilationEnvironment = CompilationEnvironment; + var CodeResolver = (function () { + function CodeResolver(environment) { + this.environment = environment; + this.visited = { + }; + } + CodeResolver.prototype.resolveCode = function (referencePath, parentPath, performSearch, resolutionDispatcher) { + var resolvedFile = { + content: "", + path: referencePath + }; + var ioHost = this.environment.ioHost; + var isRelativePath = TypeScript.isRelative(referencePath); + var isRootedPath = isRelativePath ? false : TypeScript.isRooted(referencePath); + var normalizedPath = isRelativePath ? ioHost.resolvePath(parentPath + "/" + referencePath) : (isRootedPath || !parentPath || performSearch ? referencePath : parentPath + "/" + referencePath); + if(!TypeScript.isSTRFile(normalizedPath) && !TypeScript.isTSFile(normalizedPath)) { + normalizedPath += ".ts"; + } + normalizedPath = TypeScript.switchToForwardSlashes(TypeScript.stripQuotes(normalizedPath)); + var absoluteModuleID = this.environment.compilationSettings.useCaseSensitiveFileResolution ? normalizedPath : normalizedPath.toLocaleUpperCase(); + if(!this.visited[absoluteModuleID]) { + if(isRelativePath || isRootedPath || !performSearch) { + try { + TypeScript.CompilerDiagnostics.debugPrint(" Reading code from " + normalizedPath); + try { + resolvedFile.content = ioHost.readFile(normalizedPath); + } catch (err) { + try { + if(TypeScript.isSTRFile(normalizedPath)) { + normalizedPath = TypeScript.changePathToTS(normalizedPath); + } else { + if(TypeScript.isTSFile(normalizedPath)) { + normalizedPath = TypeScript.changePathToSTR(normalizedPath); + } + } + TypeScript.CompilerDiagnostics.debugPrint(" Reading code from " + normalizedPath); + resolvedFile.content = ioHost.readFile(normalizedPath); + } catch (err) { + normalizedPath = TypeScript.changePathToDSTR(normalizedPath); + TypeScript.CompilerDiagnostics.debugPrint(" Reading code from " + normalizedPath); + try { + resolvedFile.content = ioHost.readFile(normalizedPath); + } catch (err) { + normalizedPath = TypeScript.changePathToDTS(normalizedPath); + TypeScript.CompilerDiagnostics.debugPrint(" Reading code from " + normalizedPath); + resolvedFile.content = ioHost.readFile(normalizedPath); + } + } + } + TypeScript.CompilerDiagnostics.debugPrint(" Found code at " + normalizedPath); + resolvedFile.path = normalizedPath; + this.visited[absoluteModuleID] = true; + } catch (err) { + TypeScript.CompilerDiagnostics.debugPrint(" Did not find code for " + referencePath); + } + } else { + resolvedFile = ioHost.findFile(parentPath, normalizedPath); + if(!resolvedFile) { + if(TypeScript.isSTRFile(normalizedPath)) { + normalizedPath = TypeScript.changePathToTS(normalizedPath); + } else { + if(TypeScript.isTSFile(normalizedPath)) { + normalizedPath = TypeScript.changePathToSTR(normalizedPath); + } + } + resolvedFile = ioHost.findFile(parentPath, normalizedPath); + } + if(!resolvedFile) { + normalizedPath = TypeScript.changePathToDTS(normalizedPath); + resolvedFile = ioHost.findFile(parentPath, normalizedPath); + if(!resolvedFile) { + normalizedPath = TypeScript.changePathToDSTR(normalizedPath); + resolvedFile = ioHost.findFile(parentPath, normalizedPath); + } + } + if(resolvedFile) { + resolvedFile.path = TypeScript.switchToForwardSlashes(TypeScript.stripQuotes(resolvedFile.path)); + TypeScript.CompilerDiagnostics.debugPrint(referencePath + " resolved to: " + resolvedFile.path); + resolvedFile.content = resolvedFile.content; + this.visited[absoluteModuleID] = true; + } else { + TypeScript.CompilerDiagnostics.debugPrint("Could not find " + referencePath); + } + } + if(resolvedFile && resolvedFile.content) { + var rootDir = ioHost.dirName(resolvedFile.path); + var sourceUnit = new SourceUnit(resolvedFile.path, resolvedFile.content); + var preProcessedFileInfo = TypeScript.preProcessFile(sourceUnit, this.environment.compilationSettings); + sourceUnit.referencedFiles = preProcessedFileInfo.referencedFiles; + for(var i = 0; i < preProcessedFileInfo.referencedFiles.length; i++) { + var referencedFile = preProcessedFileInfo.referencedFiles[i]; + var normalizedPath = TypeScript.isRooted(referencedFile.path) ? referencedFile.path : rootDir + "/" + referencedFile.path; + normalizedPath = ioHost.resolvePath(normalizedPath); + if(referencePath == normalizedPath) { + resolutionDispatcher.postResolutionError(normalizedPath, "File contains reference to itself", null); + continue; + } + this.resolveCode(referencedFile.path, rootDir, false, resolutionDispatcher); + } + for(var i = 0; i < preProcessedFileInfo.importedFiles.length; i++) { + this.resolveCode(preProcessedFileInfo.importedFiles[i].path, rootDir, true, resolutionDispatcher); + } + resolutionDispatcher.postResolution(sourceUnit.path, sourceUnit); + } + } + }; + return CodeResolver; + })(); + TypeScript.CodeResolver = CodeResolver; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var StyleSettings = (function () { + function StyleSettings() { + this.bitwise = false; + this.blockInCompoundStmt = false; + this.eqeqeq = false; + this.forin = false; + this.emptyBlocks = true; + this.newMustBeUsed = false; + this.requireSemi = false; + this.assignmentInCond = false; + this.eqnull = false; + this.evalOK = true; + this.innerScopeDeclEscape = true; + this.funcInLoop = true; + this.reDeclareLocal = true; + this.literalSubscript = true; + this.implicitAny = false; + } + StyleSettings.prototype.setOption = function (opt, val) { + var optExists = this[opt]; + if(optExists !== undefined) { + this[opt] = val; + return true; + } else { + return false; + } + }; + StyleSettings.prototype.parseOptions = function (str) { + var opts = str.split(";"); + for(var i = 0, len = opts.length; i < len; i++) { + var opt = opts[i]; + var val = true; + var colonIndex = opt.lastIndexOf(":"); + if(colonIndex >= 0) { + var valStr = opt.substring(colonIndex + 1); + opt = opt.substring(0, colonIndex); + if(valStr == "off") { + val = false; + } + } + if(!this.setOption(opt, val)) { + return false; + } + } + return true; + }; + return StyleSettings; + })(); + TypeScript.StyleSettings = StyleSettings; + var CompilationSettings = (function () { + function CompilationSettings() { + this.styleSettings = new StyleSettings(); + this.propagateConstants = false; + this.minWhitespace = false; + this.parseOnly = false; + this.errorRecovery = false; + this.emitComments = false; + this.watch = false; + this.exec = false; + this.resolve = true; + this.controlFlow = false; + this.printControlFlow = false; + this.controlFlowUseDef = false; + this.errorOnWith = true; + this.preprocess = true; + this.canCallDefinitionSignature = false; + this.inferPropertiesFromThisAssignment = false; + this.useDefaultLib = true; + this.codeGenTarget = TypeScript.CodeGenTarget.ES3; + this.moduleGenTarget = TypeScript.ModuleGenTarget.Synchronous; + this.outputOption = ""; + this.mapSourceFiles = false; + this.generateDeclarationFiles = false; + this.useCaseSensitiveFileResolution = false; + } + CompilationSettings.prototype.setStyleOptions = function (str) { + this.styleSettings.parseOptions(str); + }; + return CompilationSettings; + })(); + TypeScript.CompilationSettings = CompilationSettings; + function getFileReferenceFromReferencePath(comment) { + var referencesRegEx = /^(\/\/\/\s*/igm; + var match = referencesRegEx.exec(comment); + if(match) { + var path = TypeScript.normalizePath(match[3]); + var adjustedPath = TypeScript.normalizePath(path); + var isResident = match.length >= 7 && match[6] == "true"; + if(isResident) { + TypeScript.CompilerDiagnostics.debugPrint(path + " is resident"); + } + return { + minChar: 0, + limChar: 0, + path: TypeScript.switchToForwardSlashes(adjustedPath), + isResident: isResident + }; + } else { + return null; + } + } + function getAdditionalDependencyPath(comment) { + var amdDependencyRegEx = /^(\/\/\/\s*/igm; + var match = amdDependencyRegEx.exec(comment); + if(match) { + var path = match[3]; + return path; + } else { + return null; + } + } + TypeScript.getAdditionalDependencyPath = getAdditionalDependencyPath; + function getImplicitImport(comment) { + var implicitImportRegEx = /^(\/\/\/\s*/igm; + var match = implicitImportRegEx.exec(comment); + if(match) { + return true; + } + return false; + } + TypeScript.getImplicitImport = getImplicitImport; + function getStyleSettings(comment, styleSettings) { + var styleRegEx = /^(\/\/\/\s*/igm; + var settings = styleRegEx.exec(comment); + if(settings) { + var settingsRegEx = /^([a-zA-Z]+=['"]on['|"])/igm; + settings = settingsRegEx.exec(settings[2]); + if(settings) { + for(var i = 0; i < settings.length; i++) { + var setting = (settings[i]).split("="); + var on = "\"on\""; + switch(setting[0]) { + case "blockInCompoundStmt": { + styleSettings.blockInCompoundStmt = setting[1] == on; + break; + + } + case "eqeqeq": { + styleSettings.eqeqeq = setting[1] == on; + break; + + } + case "forin": { + styleSettings.forin = setting[1] == on; + break; + + } + case "emptyBlocks": { + styleSettings.emptyBlocks = setting[1] == on; + break; + + } + case "newMustBeUsed": { + styleSettings.newMustBeUsed = setting[1] == on; + break; + + } + case "requireSemi": { + styleSettings.requireSemi = setting[1] == on; + break; + + } + case "assignmentInCond": { + styleSettings.assignmentInCond = setting[1] == on; + break; + + } + case "eqnull": { + styleSettings.eqnull = setting[1] == on; + break; + + } + case "evalOK": { + styleSettings.evalOK = setting[1] == on; + break; + + } + case "innerScopeDeclEscape": { + styleSettings.innerScopeDeclEscape = setting[1] == on; + break; + + } + case "funcInLoop": { + styleSettings.funcInLoop = setting[1] == on; + break; + + } + case "reDeclareLocal": { + styleSettings.reDeclareLocal = setting[1] == on; + break; + + } + case "literalSubscript": { + styleSettings.literalSubscript = setting[1] == on; + break; + + } + case "implicitAny": { + styleSettings.implicitAny = setting[1] == on; + break; + + } + } + } + } + } + } + TypeScript.getStyleSettings = getStyleSettings; + function getReferencedFiles(sourceText) { + var preProcessInfo = preProcessFile(sourceText, null, false); + return preProcessInfo.referencedFiles; + } + TypeScript.getReferencedFiles = getReferencedFiles; + function preProcessFile(sourceText, options, readImportFiles) { + if (typeof options === "undefined") { options = new CompilationSettings(); } + if (typeof readImportFiles === "undefined") { readImportFiles = true; } + var scanner = new TypeScript.Scanner(); + scanner.resetComments(); + scanner.setSourceText(sourceText, TypeScript.LexMode.File); + var tok = scanner.scan(); + var comments = []; + var comment = null; + var leftCurlies = []; + var settings = options; + var referencedFiles = []; + var importedFiles = []; + var isLibFile = false; + while(tok.tokenId != TypeScript.TokenID.EndOfFile) { + if(readImportFiles && tok.tokenId == TypeScript.TokenID.Import) { + tok = scanner.scan(); + if(tok.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToID(tok, false)) { + tok = scanner.scan(); + if(tok.tokenId == TypeScript.TokenID.Equals) { + tok = scanner.scan(); + if(tok.tokenId == TypeScript.TokenID.Module) { + tok = scanner.scan(); + if(tok.tokenId == TypeScript.TokenID.OpenParen) { + tok = scanner.scan(); + if(tok.tokenId == TypeScript.TokenID.StringLiteral) { + var ref = { + minChar: scanner.startPos, + limChar: scanner.pos, + path: TypeScript.stripQuotes(TypeScript.switchToForwardSlashes(tok.getText())), + isResident: false + }; + importedFiles.push(ref); + } + } + } + } + } + } + if(tok.tokenId == TypeScript.TokenID.OpenBrace) { + leftCurlies.push(tok); + } + if(tok.tokenId == TypeScript.TokenID.CloseBrace) { + leftCurlies.pop(); + } + tok = scanner.scan(); + } + comments = scanner.getComments(); + for(var iComment = 0; iComment < comments.length; iComment++) { + comment = comments[iComment]; + if(!comment.isBlock) { + var referencedCode = getFileReferenceFromReferencePath(comment.getText()); + if(referencedCode) { + referencedCode.minChar = comment.startPos; + referencedCode.limChar = referencedCode.minChar + comment.value.length; + referencedFiles.push(referencedCode); + } + if(settings) { + getStyleSettings(comment.getText(), settings.styleSettings); + var isNoLibRegex = /^(\/\/\/\s*/igm; + var isNoLibMatch = isNoLibRegex.exec(comment.getText()); + if(isNoLibMatch) { + isLibFile = (isNoLibMatch[3] == "true"); + } + } + } + } + return { + settings: settings, + referencedFiles: referencedFiles, + importedFiles: importedFiles, + isLibFile: isLibFile + }; + } + TypeScript.preProcessFile = preProcessFile; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var IncrementalParser = (function () { + function IncrementalParser(logger) { + this.logger = logger; + this.astLogger = new TypeScript.AstLogger(this.logger); + } + IncrementalParser.prototype.getEnclosingScopeContextIfSingleScopeEdit = function (previousScript, scriptId, newSourceText, editRange) { + this.logger.log("checkEditsInsideSingleScope(\"" + scriptId + "\")"); + if(editRange === null) { + throw new Error("editRange should be valid"); + } + if(editRange.isUnknown()) { + this.logger.log(" Bailing out because edit range is unknown"); + return null; + } + var scope1 = TypeScript.findEnclosingScopeAt(this.logger, previousScript, newSourceText, editRange.minChar, false); + var scope2 = TypeScript.findEnclosingScopeAt(this.logger, previousScript, newSourceText, editRange.limChar, false); + if(scope1 == null || scope2 == null) { + this.logger.log(" Bailing out because containing scopes cannot be determined"); + return null; + } + if(scope1.scopeStartAST !== scope2.scopeStartAST) { + this.logger.log(" Bailing out because edit overlaps 2 disctint scopes"); + return null; + } + var newScopeLength = scope1.scopeStartAST.limChar - scope1.scopeStartAST.minChar + editRange.delta; + if(newScopeLength <= 0) { + this.logger.log(" Bailing out because scope has been entirely removed from new source text"); + return null; + } + return scope1; + }; + IncrementalParser.prototype.attemptIncrementalUpdateUnit = function (previousScript, scriptId, newSourceText, editRange) { + this.logger.log("attemptIncrementalUpdateUnit(\"" + scriptId + "\")"); + if(editRange === null) { + throw new Error("editRange should be valid"); + } + var scope1 = this.getEnclosingScopeContextIfSingleScopeEdit(previousScript, scriptId, newSourceText, editRange); + if(scope1 === null) { + return null; + } + var newScopeLength = scope1.scopeStartAST.limChar - scope1.scopeStartAST.minChar + editRange.delta; + if(newScopeLength >= newSourceText.getLength() / 2) { + this.logger.log(" Bailing out because range of scope to reparse (" + newScopeLength + " characters) is greater than half the size of the source text"); + return null; + } + var parseErrors = []; + var errorCapture = function (minChar, charLen, message, unitIndex) { + parseErrors.push(new TypeScript.ErrorEntry(unitIndex, minChar, minChar + charLen, message)); + }; + var quickParseResult = TypeScript.quickParse(this.logger, scope1.scopeStartAST, newSourceText, scope1.scopeStartAST.minChar, scope1.scopeStartAST.minChar + newScopeLength, errorCapture); + if(quickParseResult.endLexState != TypeScript.LexState.Start) { + this.logger.log(" Bailing out because scope contains unterminated comment"); + return null; + } + var scriptFragment = quickParseResult.Script; + if(scriptFragment.vars.members.length !== 0) { + this.logger.log(" Bailing out because new source text defines variables"); + return null; + } + if(scriptFragment.bod.members.length !== 1) { + this.logger.log(" Bailing out because new source text defines more than one scope (or none)"); + return null; + } + var oldScope = scope1.scopeStartAST; + var newScope = scriptFragment.bod.members[0]; + if(oldScope.nodeType != newScope.nodeType) { + this.logger.log(" Bailing out because new source text does not define the same scope type as the existing scope"); + return null; + } + if(!(oldScope).leftCurlyCount || !(oldScope).rightCurlyCount) { + this.logger.log(" Bailing out because sopce doesn't have left/right curly count"); + return null; + } + if((oldScope).leftCurlyCount !== (newScope).leftCurlyCount) { + this.logger.log(" Bailing out because new source text contains more (or fewer) left curly braces"); + return null; + } + if((oldScope).rightCurlyCount !== (newScope).rightCurlyCount) { + this.logger.log(" Bailing out because new source text contains more (or fewer) right curly braces"); + return null; + } + if(newScope.minChar !== 0) { + this.logger.log(" Bailing out because new function declaration does not start at position 0"); + return null; + } + if(newScope.limChar !== newScopeLength) { + this.logger.log(" Bailing out because new function declaration does not end at the new end position"); + return null; + } + return TypeScript.UpdateUnitResult.singleScopeEdits(previousScript, scriptFragment, oldScope, newScope, editRange, parseErrors); + }; + IncrementalParser.prototype.mergeTrees = function (updateResult) { + var _this = this; + TypeScript.timeFunction(this.logger, "mergeTrees()", function () { + var editRange = new TypeScript.ScriptEditRange(updateResult.scope1.minChar, updateResult.scope1.limChar, updateResult.editRange.delta); + _this.applyDeltaPosition(updateResult.script1, editRange.limChar, editRange.delta); + _this.applyDeltaPosition(updateResult.script2, 0, editRange.minChar); + _this.mergeLocationInfo(updateResult.script1, updateResult.script2, editRange); + _this.replaceAST(updateResult.script1, updateResult.scope1, updateResult.scope2); + }); + }; + IncrementalParser.prototype.replaceAST = function (script, oldAst, newAst) { + var _this = this; + var pre = function (cur, parent, walker) { + if(cur === oldAst) { + newAst.preComments = cur.preComments; + newAst.postComments = cur.postComments; + _this.logger.log("replaced old AST node with new one in script AST"); + walker.options.stopWalk(); + return newAst; + } + if(TypeScript.isValidAstNode(cur)) { + if(cur.limChar < oldAst.minChar || cur.minChar > oldAst.limChar) { + walker.options.goChildren = false; + } + } + return cur; + }; + TypeScript.getAstWalkerFactory().walk(script, pre); + }; + IncrementalParser.prototype.mergeLocationInfo = function (script, partial, editRange) { + var lineMap1 = script.locationInfo.lineMap; + var lineMap2 = partial.locationInfo.lineMap; + if(this.logger.information()) { + this.logger.log("lineMap1 (before):"); + this.astLogger.logLinemap(lineMap1); + this.logger.log("lineMap2 (quick parse):"); + this.astLogger.logLinemap(lineMap2); + this.logger.log("EditRange=" + editRange); + } + var i1 = 2; + var i2 = 2; + var len1 = lineMap1.length; + var len2 = lineMap2.length; + while(i1 < len1) { + if(lineMap1[i1] <= editRange.minChar) { + i1++; + } else { + if(lineMap1[i1] >= editRange.limChar) { + lineMap1[i1] += editRange.delta; + i1++; + } else { + if(i2 < len2) { + lineMap1.splice(i1, 0, lineMap2[i2] + editRange.minChar); + i1++; + len1++; + i2++; + } else { + lineMap1.splice(i1, 1); + len1--; + } + } + } + } + if(i2 < len2) { + if(lineMap1[len1 - 1] >= (lineMap2[i2] + editRange.minChar)) { + i1 = 2; + while(i1 < len1 && i2 < len2) { + if(lineMap1[i1] < (lineMap2[i2] + editRange.minChar)) { + i1++; + } else { + lineMap1.splice(i1, 0, lineMap2[i2] + editRange.minChar); + i1++; + len1++; + i2++; + } + } + } + for(; i2 < len2; i2++) { + lineMap1.push(lineMap2[i2] + editRange.minChar); + } + } + if(this.logger.information()) { + this.logger.log("lineMap1 (after merge):"); + this.astLogger.logLinemap(lineMap1); + } + }; + IncrementalParser.prototype.applyDeltaPosition = function (ast, start, delta) { + var applyDelta = function (ast) { + if(ast.minChar !== -1 && ast.minChar >= start) { + ast.minChar += delta; + } + if(ast.limChar !== -1 && ast.limChar >= start) { + ast.limChar += delta; + } + }; + var applyDeltaToComments = function (comments) { + if(comments && comments.length > 0) { + for(var i = 0; i < comments.length; i++) { + applyDelta(comments[i]); + } + } + }; + var pre = function (cur, parent, walker) { + if(cur.limChar !== -1 && cur.limChar < start) { + walker.options.goChildren = false; + } + applyDelta(cur); + applyDeltaToComments(cur.preComments); + applyDeltaToComments(cur.postComments); + return cur; + }; + TypeScript.getAstWalkerFactory().walk(ast, pre); + }; + return IncrementalParser; + })(); + TypeScript.IncrementalParser = IncrementalParser; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var DeclFileWriter = (function () { + function DeclFileWriter(declFile) { + this.declFile = declFile; + this.onNewLine = true; + } + DeclFileWriter.prototype.Write = function (s) { + this.declFile.Write(s); + this.onNewLine = false; + }; + DeclFileWriter.prototype.WriteLine = function (s) { + this.declFile.WriteLine(s); + this.onNewLine = true; + }; + DeclFileWriter.prototype.Close = function () { + this.declFile.Close(); + }; + return DeclFileWriter; + })(); + TypeScript.DeclFileWriter = DeclFileWriter; + var DeclarationEmitter = (function () { + function DeclarationEmitter(checker, emitOptions, errorReporter) { + this.checker = checker; + this.emitOptions = emitOptions; + this.errorReporter = errorReporter; + this.declFile = null; + this.indenter = new TypeScript.Indenter(); + this.declarationContainerStack = []; + this.isDottedModuleName = []; + this.ignoreCallbackAst = null; + this.singleDeclFile = null; + this.varListCount = 0; + } + DeclarationEmitter.prototype.getAstDeclarationContainer = function () { + return this.declarationContainerStack[this.declarationContainerStack.length - 1]; + }; + DeclarationEmitter.prototype.emitDottedModuleName = function () { + return (this.isDottedModuleName.length == 0) ? false : this.isDottedModuleName[this.isDottedModuleName.length - 1]; + }; + DeclarationEmitter.prototype.setDeclarationFile = function (file) { + this.declFile = new DeclFileWriter(file); + }; + DeclarationEmitter.prototype.Close = function () { + try { + this.declFile.Close(); + } catch (ex) { + this.errorReporter.emitterError(null, ex.message); + } + }; + DeclarationEmitter.prototype.emitDeclarations = function (script) { + TypeScript.AstWalkerWithDetailCallback.walk(script, this); + }; + DeclarationEmitter.prototype.getIndentString = function (declIndent) { + if (typeof declIndent === "undefined") { declIndent = false; } + if(this.emitOptions.minWhitespace) { + return ""; + } else { + return this.indenter.getIndent(); + } + }; + DeclarationEmitter.prototype.emitIndent = function () { + this.declFile.Write(this.getIndentString()); + }; + DeclarationEmitter.prototype.canEmitSignature = function (declFlags, canEmitGlobalAmbientDecl, useDeclarationContainerTop) { + if (typeof canEmitGlobalAmbientDecl === "undefined") { canEmitGlobalAmbientDecl = true; } + if (typeof useDeclarationContainerTop === "undefined") { useDeclarationContainerTop = true; } + var container; + if(useDeclarationContainerTop) { + container = this.getAstDeclarationContainer(); + } else { + container = this.declarationContainerStack[this.declarationContainerStack.length - 2]; + } + if(container.nodeType == TypeScript.NodeType.ModuleDeclaration && !TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Exported)) { + return false; + } + if(!canEmitGlobalAmbientDecl && container.nodeType == TypeScript.NodeType.Script && TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Ambient)) { + return false; + } + return true; + }; + DeclarationEmitter.prototype.canEmitPrePostAstSignature = function (declFlags, astWithPrePostCallback, preCallback) { + if(this.ignoreCallbackAst) { + TypeScript.CompilerDiagnostics.assert(this.ignoreCallbackAst != astWithPrePostCallback, "Ignore Callback AST mismatch"); + this.ignoreCallbackAst = null; + return false; + } else { + if(preCallback && !this.canEmitSignature(declFlags, true, preCallback)) { + this.ignoreCallbackAst = astWithPrePostCallback; + return false; + } + } + return true; + }; + DeclarationEmitter.prototype.getDeclFlagsString = function (declFlags, typeString) { + var result = this.getIndentString(); + var accessorString = ""; + if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.GetAccessor)) { + accessorString = "get "; + } else { + if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.SetAccessor)) { + accessorString = "set "; + } + } + var container = this.getAstDeclarationContainer(); + if(container.nodeType == TypeScript.NodeType.ModuleDeclaration && TypeScript.hasFlag((container).modFlags, TypeScript.ModuleFlags.IsWholeFile) && TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Exported)) { + result += "export "; + } + if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.LocalStatic) || TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Static)) { + result += "static " + accessorString; + } else { + if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Private)) { + result += "private " + accessorString; + } else { + if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Public)) { + result += "public " + accessorString; + } else { + if(accessorString == "") { + result += typeString + " "; + } else { + result += accessorString; + } + } + } + } + return result; + }; + DeclarationEmitter.prototype.emitDeclFlags = function (declFlags, typeString) { + this.declFile.Write(this.getDeclFlagsString(declFlags, typeString)); + }; + DeclarationEmitter.prototype.canEmitTypeAnnotationSignature = function (declFlag) { + if (typeof declFlag === "undefined") { declFlag = TypeScript.DeclFlags.None; } + return !TypeScript.hasFlag(declFlag, TypeScript.DeclFlags.Private); + }; + DeclarationEmitter.prototype.pushDeclarationContainer = function (ast) { + this.declarationContainerStack.push(ast); + }; + DeclarationEmitter.prototype.popDeclarationContainer = function (ast) { + TypeScript.CompilerDiagnostics.assert(ast != this.getAstDeclarationContainer(), 'Declaration container mismatch'); + this.declarationContainerStack.pop(); + }; + DeclarationEmitter.prototype.emitTypeNamesMember = function (memberName, emitIndent) { + if (typeof emitIndent === "undefined") { emitIndent = false; } + if(memberName.prefix == "{ ") { + if(emitIndent) { + this.emitIndent(); + } + this.declFile.WriteLine("{"); + this.indenter.increaseIndent(); + emitIndent = true; + } else { + if(memberName.prefix != "") { + if(emitIndent) { + this.emitIndent(); + } + this.declFile.Write(memberName.prefix); + emitIndent = false; + } + } + if(memberName.isString()) { + if(emitIndent) { + this.emitIndent(); + } + this.declFile.Write((memberName).text); + } else { + var ar = memberName; + for(var index = 0; index < ar.entries.length; index++) { + this.emitTypeNamesMember(ar.entries[index], emitIndent); + if(ar.delim == "; ") { + this.declFile.WriteLine(";"); + } + } + } + if(memberName.suffix == "}") { + this.indenter.decreaseIndent(); + this.emitIndent(); + this.declFile.Write(memberName.suffix); + } else { + this.declFile.Write(memberName.suffix); + } + }; + DeclarationEmitter.prototype.emitTypeSignature = function (type) { + var containingScope = null; + var declarationContainerAst = this.getAstDeclarationContainer(); + switch(declarationContainerAst.nodeType) { + case TypeScript.NodeType.ModuleDeclaration: + case TypeScript.NodeType.InterfaceDeclaration: + case TypeScript.NodeType.FuncDecl: { + if(declarationContainerAst.type) { + containingScope = declarationContainerAst.type.containedScope; + } + break; + + } + case TypeScript.NodeType.Script: { + var script = declarationContainerAst; + if(script.bod) { + containingScope = script.bod.enclosingScope; + } + break; + + } + case TypeScript.NodeType.ClassDeclaration: { + if(declarationContainerAst.type) { + containingScope = declarationContainerAst.type.instanceType.containedScope; + } + break; + + } + default: { + TypeScript.CompilerDiagnostics.debugPrint("Unknown containing scope"); + + } + } + var typeNameMembers = type.getScopedTypeNameEx(containingScope); + this.emitTypeNamesMember(typeNameMembers); + }; + DeclarationEmitter.prototype.emitComment = function (comment) { + var text = comment.getText(); + if(this.declFile.onNewLine) { + this.emitIndent(); + } else { + if(!comment.isBlockComment) { + this.declFile.WriteLine(""); + this.emitIndent(); + } + } + this.declFile.Write(text[0]); + for(var i = 1; i < text.length; i++) { + this.declFile.WriteLine(""); + this.emitIndent(); + this.declFile.Write(text[i]); + } + if(comment.endsLine || !comment.isBlockComment) { + this.declFile.WriteLine(""); + } else { + this.declFile.Write(" "); + } + }; + DeclarationEmitter.prototype.emitDeclarationComments = function (astOrSymbol, endLine) { + if (typeof endLine === "undefined") { endLine = true; } + if(!this.emitOptions.emitComments) { + return; + } + var declComments = astOrSymbol.getDocComments(); + if(declComments.length > 0) { + for(var i = 0; i < declComments.length; i++) { + this.emitComment(declComments[i]); + } + if(endLine) { + if(!this.declFile.onNewLine) { + this.declFile.WriteLine(""); + } + } else { + if(this.declFile.onNewLine) { + this.emitIndent(); + } + } + } + }; + DeclarationEmitter.prototype.VarDeclCallback = function (pre, varDecl) { + if(pre && this.canEmitSignature(TypeScript.ToDeclFlags(varDecl.varFlags), false)) { + var interfaceMember = (this.getAstDeclarationContainer().nodeType == TypeScript.NodeType.InterfaceDeclaration); + this.emitDeclarationComments(varDecl); + if(!interfaceMember) { + if(this.varListCount >= 0) { + this.emitDeclFlags(TypeScript.ToDeclFlags(varDecl.varFlags), "var"); + this.varListCount = -this.varListCount; + } + this.declFile.Write(varDecl.id.text); + } else { + this.emitIndent(); + this.declFile.Write(varDecl.id.text); + if(TypeScript.hasFlag(varDecl.id.flags, TypeScript.ASTFlags.OptionalName)) { + this.declFile.Write("?"); + } + } + var type = null; + if(varDecl.typeExpr && varDecl.typeExpr.type) { + type = varDecl.typeExpr.type; + } else { + if(varDecl.sym) { + type = (varDecl.sym).getType(); + if(type == this.checker.anyType) { + type = null; + } + } + } + if(type && this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(varDecl.varFlags))) { + this.declFile.Write(": "); + this.emitTypeSignature(type); + } + if(this.varListCount > 0) { + this.varListCount--; + } else { + if(this.varListCount < 0) { + this.varListCount++; + } + } + if(this.varListCount < 0) { + this.declFile.Write(", "); + } else { + this.declFile.WriteLine(";"); + } + } + return false; + }; + DeclarationEmitter.prototype.BlockCallback = function (pre, block) { + if(!block.isStatementBlock) { + if(pre) { + this.varListCount = block.statements.members.length; + } else { + this.varListCount = 0; + } + return true; + } + return false; + }; + DeclarationEmitter.prototype.emitArgDecl = function (argDecl, funcDecl) { + this.emitDeclarationComments(argDecl, false); + this.declFile.Write(argDecl.id.text); + if(argDecl.isOptionalArg()) { + this.declFile.Write("?"); + } + if((argDecl.typeExpr || argDecl.type != this.checker.anyType) && this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(funcDecl.fncFlags))) { + this.declFile.Write(": "); + this.emitTypeSignature(argDecl.type); + } + }; + DeclarationEmitter.prototype.FuncDeclCallback = function (pre, funcDecl) { + if(!pre) { + return false; + } + if(funcDecl.isAccessor()) { + return this.emitPropertyAccessorSignature(funcDecl); + } + var isInterfaceMember = (this.getAstDeclarationContainer().nodeType == TypeScript.NodeType.InterfaceDeclaration); + if(funcDecl.bod) { + if(funcDecl.isConstructor) { + if(funcDecl.type.construct && funcDecl.type.construct.signatures.length > 1) { + return false; + } + } else { + if(funcDecl.type.call && funcDecl.type.call.signatures.length > 1) { + return false; + } + } + } else { + if(!isInterfaceMember && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Private) && funcDecl.type.call && funcDecl.type.call.signatures.length > 1) { + var signatures = funcDecl.type.call.signatures; + var firstSignature = signatures[0].declAST; + if(firstSignature.bod) { + firstSignature = signatures[1].declAST; + } + if(firstSignature != funcDecl) { + return false; + } + } + } + if(!this.canEmitSignature(TypeScript.ToDeclFlags(funcDecl.fncFlags), false)) { + return false; + } + this.emitDeclarationComments(funcDecl); + if(funcDecl.isConstructor) { + this.emitIndent(); + this.declFile.Write("constructor"); + } else { + var id = funcDecl.getNameText(); + if(!isInterfaceMember) { + this.emitDeclFlags(TypeScript.ToDeclFlags(funcDecl.fncFlags), "function"); + this.declFile.Write(id); + } else { + this.emitIndent(); + if(funcDecl.isConstructMember()) { + this.declFile.Write("new"); + } else { + if(!funcDecl.isCallMember() && !funcDecl.isIndexerMember()) { + this.declFile.Write(id); + if(TypeScript.hasFlag(funcDecl.name.flags, TypeScript.ASTFlags.OptionalName)) { + this.declFile.Write("? "); + } + } + } + } + } + if(!funcDecl.isIndexerMember()) { + this.declFile.Write("("); + } else { + this.declFile.Write("["); + } + this.indenter.increaseIndent(); + if(funcDecl.arguments) { + var argsLen = funcDecl.arguments.members.length; + if(funcDecl.variableArgList) { + argsLen--; + } + for(var i = 0; i < argsLen; i++) { + var argDecl = funcDecl.arguments.members[i]; + this.emitArgDecl(argDecl, funcDecl); + if(i < (argsLen - 1)) { + this.declFile.Write(", "); + } + } + } + if(funcDecl.variableArgList) { + var lastArg = funcDecl.arguments.members[funcDecl.arguments.members.length - 1]; + if(funcDecl.arguments.members.length > 1) { + this.declFile.Write(", ..."); + } else { + this.declFile.Write("..."); + } + this.emitArgDecl(lastArg, funcDecl); + } + this.indenter.decreaseIndent(); + if(!funcDecl.isIndexerMember()) { + this.declFile.Write(")"); + } else { + this.declFile.Write("]"); + } + if(!funcDecl.isConstructor && (funcDecl.returnTypeAnnotation || funcDecl.signature.returnType.type != this.checker.anyType) && this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(funcDecl.fncFlags))) { + this.declFile.Write(": "); + this.emitTypeSignature(funcDecl.signature.returnType.type); + } + this.declFile.WriteLine(";"); + return false; + }; + DeclarationEmitter.prototype.emitBaseList = function (bases, qual) { + if(bases && (bases.members.length > 0)) { + this.declFile.Write(" " + qual + " "); + var basesLen = bases.members.length; + for(var i = 0; i < basesLen; i++) { + var baseExpr = bases.members[i]; + var baseSymbol = baseExpr.type.symbol; + var baseType = baseExpr.type; + if(i > 0) { + this.declFile.Write(", "); + } + this.emitTypeSignature(baseType); + } + } + }; + DeclarationEmitter.prototype.emitPropertyAccessorSignature = function (funcDecl) { + var accessorSymbol = funcDecl.accessorSymbol; + if(accessorSymbol.getter && accessorSymbol.getter.declAST != funcDecl) { + return false; + } + this.emitDeclarationComments(accessorSymbol); + this.emitDeclFlags(TypeScript.ToDeclFlags(accessorSymbol.flags), "var"); + this.declFile.Write(funcDecl.name.text); + var propertyType = accessorSymbol.getType(); + if(this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(accessorSymbol.flags))) { + this.declFile.Write(" : "); + this.emitTypeSignature(propertyType); + } + this.declFile.WriteLine(";"); + return false; + }; + DeclarationEmitter.prototype.emitClassMembersFromConstructorDefinition = function (funcDecl) { + if(funcDecl.arguments) { + var argsLen = funcDecl.arguments.members.length; + if(funcDecl.variableArgList) { + argsLen--; + } + for(var i = 0; i < argsLen; i++) { + var argDecl = funcDecl.arguments.members[i]; + if(TypeScript.hasFlag(argDecl.varFlags, TypeScript.VarFlags.Property)) { + this.emitDeclarationComments(argDecl); + this.emitDeclFlags(TypeScript.ToDeclFlags(argDecl.varFlags), "var"); + this.declFile.Write(argDecl.id.text); + if(argDecl.typeExpr && this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(argDecl.varFlags))) { + this.declFile.Write(": "); + this.emitTypeSignature(argDecl.type); + } + this.declFile.WriteLine(";"); + } + } + } + }; + DeclarationEmitter.prototype.ClassDeclarationCallback = function (pre, classDecl) { + if(!this.canEmitPrePostAstSignature(TypeScript.ToDeclFlags(classDecl.varFlags), classDecl, pre)) { + return false; + } + if(pre) { + var className = classDecl.name.text; + this.emitDeclarationComments(classDecl); + this.emitDeclFlags(TypeScript.ToDeclFlags(classDecl.varFlags), "class"); + this.declFile.Write(className); + this.emitBaseList(classDecl.extendsList, "extends"); + this.emitBaseList(classDecl.implementsList, "implements"); + this.declFile.WriteLine(" {"); + this.pushDeclarationContainer(classDecl); + this.indenter.increaseIndent(); + if(classDecl.constructorDecl) { + this.emitClassMembersFromConstructorDefinition(classDecl.constructorDecl); + } + } else { + this.indenter.decreaseIndent(); + this.popDeclarationContainer(classDecl); + this.emitIndent(); + this.declFile.WriteLine("}"); + } + return true; + }; + DeclarationEmitter.prototype.InterfaceDeclarationCallback = function (pre, interfaceDecl) { + if(!this.canEmitPrePostAstSignature(TypeScript.ToDeclFlags(interfaceDecl.varFlags), interfaceDecl, pre)) { + return false; + } + if(pre) { + var interfaceName = interfaceDecl.name.text; + this.emitDeclarationComments(interfaceDecl); + this.emitDeclFlags(TypeScript.ToDeclFlags(interfaceDecl.varFlags), "interface"); + this.declFile.Write(interfaceName); + this.emitBaseList(interfaceDecl.extendsList, "extends"); + this.declFile.WriteLine(" {"); + this.indenter.increaseIndent(); + this.pushDeclarationContainer(interfaceDecl); + } else { + this.indenter.decreaseIndent(); + this.popDeclarationContainer(interfaceDecl); + this.emitIndent(); + this.declFile.WriteLine("}"); + } + return true; + }; + DeclarationEmitter.prototype.ImportDeclarationCallback = function (pre, importDecl) { + if(pre) { + if((this.declarationContainerStack[0]).isExternallyVisibleSymbol(importDecl.id.sym)) { + this.emitDeclarationComments(importDecl); + this.emitIndent(); + this.declFile.Write("import "); + this.declFile.Write(importDecl.id.text + " = "); + if(importDecl.isDynamicImport) { + this.declFile.WriteLine("module (" + importDecl.getAliasName() + ");"); + } else { + this.declFile.WriteLine(importDecl.getAliasName() + ";"); + } + } + } + return false; + }; + DeclarationEmitter.prototype.emitEnumSignature = function (moduleDecl) { + if(!this.canEmitSignature(TypeScript.ToDeclFlags(moduleDecl.modFlags))) { + return false; + } + this.emitDeclarationComments(moduleDecl); + this.emitDeclFlags(TypeScript.ToDeclFlags(moduleDecl.modFlags), "enum"); + this.declFile.WriteLine(moduleDecl.name.text + " {"); + this.indenter.increaseIndent(); + var membersLen = moduleDecl.members.members.length; + for(var j = 1; j < membersLen; j++) { + var memberDecl = moduleDecl.members.members[j]; + if(memberDecl.nodeType == TypeScript.NodeType.VarDecl) { + this.emitDeclarationComments(memberDecl); + this.emitIndent(); + this.declFile.WriteLine((memberDecl).id.text + ","); + } else { + TypeScript.CompilerDiagnostics.assert(memberDecl.nodeType != TypeScript.NodeType.Asg, "We want to catch this"); + } + } + this.indenter.decreaseIndent(); + this.emitIndent(); + this.declFile.WriteLine("}"); + return false; + }; + DeclarationEmitter.prototype.ModuleDeclarationCallback = function (pre, moduleDecl) { + if(TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsWholeFile)) { + if(TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsDynamic)) { + if(pre) { + if(!this.emitOptions.outputMany) { + this.singleDeclFile = this.declFile; + TypeScript.CompilerDiagnostics.assert(this.indenter.indentAmt == 0, "Indent has to be 0 when outputing new file"); + var declareFileName = this.emitOptions.mapOutputFileName(TypeScript.stripQuotes(moduleDecl.name.sym.name), TypeScript.TypeScriptCompiler.mapToDTSFileName); + var useUTF8InOutputfile = moduleDecl.containsUnicodeChar || (this.emitOptions.emitComments && moduleDecl.containsUnicodeCharInComment); + try { + this.declFile = new DeclFileWriter(this.emitOptions.ioHost.createFile(declareFileName, useUTF8InOutputfile)); + } catch (ex) { + this.errorReporter.emitterError(null, ex.message); + } + } + this.pushDeclarationContainer(moduleDecl); + } else { + if(!this.emitOptions.outputMany) { + TypeScript.CompilerDiagnostics.assert(this.singleDeclFile != this.declFile, "singleDeclFile cannot be null as we are going to revert back to it"); + TypeScript.CompilerDiagnostics.assert(this.indenter.indentAmt == 0, "Indent has to be 0 when outputing new file"); + try { + this.declFile.Close(); + } catch (ex) { + this.errorReporter.emitterError(null, ex.message); + } + this.declFile = this.singleDeclFile; + } + this.popDeclarationContainer(moduleDecl); + } + } + return true; + } + if(moduleDecl.isEnum()) { + if(pre) { + this.emitEnumSignature(moduleDecl); + } + return false; + } + if(!this.canEmitPrePostAstSignature(TypeScript.ToDeclFlags(moduleDecl.modFlags), moduleDecl, pre)) { + return false; + } + if(pre) { + if(this.emitDottedModuleName()) { + this.dottedModuleEmit += "."; + } else { + this.dottedModuleEmit = this.getDeclFlagsString(TypeScript.ToDeclFlags(moduleDecl.modFlags), "module"); + } + this.dottedModuleEmit += moduleDecl.name.text; + var isCurrentModuleDotted = (moduleDecl.members.members.length == 1 && moduleDecl.members.members[0].nodeType == TypeScript.NodeType.ModuleDeclaration && !(moduleDecl.members.members[0]).isEnum() && TypeScript.hasFlag((moduleDecl.members.members[0]).modFlags, TypeScript.ModuleFlags.Exported)); + var moduleDeclComments = moduleDecl.getDocComments(); + isCurrentModuleDotted = isCurrentModuleDotted && (moduleDeclComments == null || moduleDeclComments.length == 0); + this.isDottedModuleName.push(isCurrentModuleDotted); + this.pushDeclarationContainer(moduleDecl); + if(!isCurrentModuleDotted) { + this.emitDeclarationComments(moduleDecl); + this.declFile.Write(this.dottedModuleEmit); + this.declFile.WriteLine(" {"); + this.indenter.increaseIndent(); + } + } else { + if(!this.emitDottedModuleName()) { + this.indenter.decreaseIndent(); + this.emitIndent(); + this.declFile.WriteLine("}"); + } + this.popDeclarationContainer(moduleDecl); + this.isDottedModuleName.pop(); + } + return true; + }; + DeclarationEmitter.prototype.ScriptCallback = function (pre, script) { + if(pre) { + if(this.emitOptions.outputMany) { + for(var i = 0; i < script.referencedFiles.length; i++) { + var referencePath = script.referencedFiles[i].path; + var declareFileName; + if(TypeScript.isRooted(referencePath)) { + declareFileName = this.emitOptions.mapOutputFileName(referencePath, TypeScript.TypeScriptCompiler.mapToDTSFileName); + } else { + declareFileName = TypeScript.getDeclareFilePath(script.referencedFiles[i].path); + } + this.declFile.WriteLine('/// '); + } + } + this.pushDeclarationContainer(script); + } else { + this.popDeclarationContainer(script); + } + return true; + }; + DeclarationEmitter.prototype.DefaultCallback = function (pre, ast) { + return !TypeScript.hasFlag(ast.flags, TypeScript.ASTFlags.IsStatement); + }; + return DeclarationEmitter; + })(); + TypeScript.DeclarationEmitter = DeclarationEmitter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (UpdateUnitKind) { + UpdateUnitKind._map = []; + UpdateUnitKind._map[0] = "Unknown"; + UpdateUnitKind.Unknown = 0; + UpdateUnitKind._map[1] = "NoEdits"; + UpdateUnitKind.NoEdits = 1; + UpdateUnitKind._map[2] = "EditsInsideSingleScope"; + UpdateUnitKind.EditsInsideSingleScope = 2; + })(TypeScript.UpdateUnitKind || (TypeScript.UpdateUnitKind = {})); + var UpdateUnitKind = TypeScript.UpdateUnitKind; + var ScriptEditRange = (function () { + function ScriptEditRange(minChar, limChar, delta) { + this.minChar = minChar; + this.limChar = limChar; + this.delta = delta; + } + ScriptEditRange.unknown = function unknown() { + return new ScriptEditRange(-1, -1, -1); + } + ScriptEditRange.prototype.isUnknown = function () { + return this.minChar === -1 && this.limChar === -1 && this.delta === -1; + }; + ScriptEditRange.prototype.containsPosition = function (pos) { + return (this.minChar <= pos && pos < this.limChar) || (this.minChar <= pos && pos < this.limChar + this.delta); + }; + ScriptEditRange.prototype.toString = function () { + return "editRange(minChar=" + this.minChar + ", limChar=" + this.limChar + ", delta=" + this.delta + ")"; + }; + return ScriptEditRange; + })(); + TypeScript.ScriptEditRange = ScriptEditRange; + var UpdateUnitResult = (function () { + function UpdateUnitResult(kind, unitIndex, script1, script2) { + this.kind = kind; + this.unitIndex = unitIndex; + this.script1 = script1; + this.script2 = script2; + this.scope1 = null; + this.scope2 = null; + this.editRange = null; + this.parseErrors = []; + } + UpdateUnitResult.noEdits = function noEdits(unitIndex) { + return new UpdateUnitResult(UpdateUnitKind.NoEdits, unitIndex, null, null); + } + UpdateUnitResult.unknownEdits = function unknownEdits(script1, script2, parseErrors) { + var result = new UpdateUnitResult(UpdateUnitKind.Unknown, script1.locationInfo.unitIndex, script1, script2); + result.parseErrors = parseErrors; + return result; + } + UpdateUnitResult.singleScopeEdits = function singleScopeEdits(script1, script2, scope1, scope2, editRange, parseErrors) { + var result = new UpdateUnitResult(UpdateUnitKind.EditsInsideSingleScope, script1.locationInfo.unitIndex, script1, script2); + result.scope1 = scope1; + result.scope2 = scope2; + result.editRange = editRange; + result.parseErrors = parseErrors; + return result; + } + return UpdateUnitResult; + })(); + TypeScript.UpdateUnitResult = UpdateUnitResult; + var ErrorEntry = (function () { + function ErrorEntry(unitIndex, minChar, limChar, message) { + this.unitIndex = unitIndex; + this.minChar = minChar; + this.limChar = limChar; + this.message = message; + } + return ErrorEntry; + })(); + TypeScript.ErrorEntry = ErrorEntry; + TypeScript.defaultSettings = new TypeScript.CompilationSettings(); + var TypeScriptCompiler = (function () { + function TypeScriptCompiler(errorOutput, logger, settings) { + if (typeof logger === "undefined") { logger = new TypeScript.NullLogger(); } + if (typeof settings === "undefined") { settings = TypeScript.defaultSettings; } + this.errorOutput = errorOutput; + this.logger = logger; + this.settings = settings; + this.parser = new TypeScript.Parser(); + this.typeFlow = null; + this.scripts = new TypeScript.ASTList(); + this.units = new Array(); + this.errorReporter = new TypeScript.ErrorReporter(this.errorOutput); + this.persistentTypeState = new TypeScript.PersistentGlobalTypeState(this.errorReporter); + this.errorReporter.parser = this.parser; + this.initTypeChecker(this.errorOutput); + this.parser.style_requireSemi = this.settings.styleSettings.requireSemi; + this.parser.style_funcInLoop = this.settings.styleSettings.funcInLoop; + this.parser.inferPropertiesFromThisAssignment = this.settings.inferPropertiesFromThisAssignment; + this.emitSettings = new TypeScript.EmitOptions(this.settings); + TypeScript.codeGenTarget = settings.codeGenTarget; + } + TypeScriptCompiler.prototype.timeFunction = function (funcDescription, func) { + return TypeScript.timeFunction(this.logger, funcDescription, func); + }; + TypeScriptCompiler.prototype.initTypeChecker = function (errorOutput) { + this.persistentTypeState.refreshPersistentState(); + this.typeChecker = new TypeScript.TypeChecker(this.persistentTypeState); + this.typeChecker.errorReporter = this.errorReporter; + this.typeChecker.checkControlFlow = this.settings.controlFlow; + this.typeChecker.checkControlFlowUseDef = this.settings.controlFlowUseDef; + this.typeChecker.printControlFlowGraph = this.settings.printControlFlow; + this.typeChecker.errorsOnWith = this.settings.errorOnWith; + this.typeChecker.styleSettings = this.settings.styleSettings; + this.typeChecker.canCallDefinitionSignature = this.settings.canCallDefinitionSignature; + this.errorReporter.checker = this.typeChecker; + this.setErrorOutput(this.errorOutput); + }; + TypeScriptCompiler.prototype.setErrorOutput = function (outerr) { + this.errorOutput = outerr; + this.errorReporter.setErrOut(outerr); + this.parser.outfile = outerr; + }; + TypeScriptCompiler.prototype.emitCommentsToOutput = function () { + this.emitSettings = new TypeScript.EmitOptions(this.settings); + }; + TypeScriptCompiler.prototype.setErrorCallback = function (fn) { + this.parser.errorCallback = fn; + }; + TypeScriptCompiler.prototype.updateUnit = function (prog, filename, setRecovery) { + return this.updateSourceUnit(new TypeScript.StringSourceText(prog), filename, setRecovery); + }; + TypeScriptCompiler.prototype.updateSourceUnit = function (sourceText, filename, setRecovery) { + var _this = this; + return this.timeFunction("updateSourceUnit(" + filename + ")", function () { + var updateResult = _this.partialUpdateUnit(sourceText, filename, setRecovery); + return _this.applyUpdateResult(updateResult); + }); + }; + TypeScriptCompiler.prototype.applyUpdateResult = function (updateResult) { + switch(updateResult.kind) { + case UpdateUnitKind.NoEdits: { + return false; + + } + case UpdateUnitKind.Unknown: { + this.scripts.members[updateResult.unitIndex] = updateResult.script2; + this.units[updateResult.unitIndex] = updateResult.script2.locationInfo; + for(var i = 0, len = updateResult.parseErrors.length; i < len; i++) { + var e = updateResult.parseErrors[i]; + if(this.parser.errorCallback) { + this.parser.errorCallback(e.minChar, e.limChar - e.minChar, e.message, e.unitIndex); + } + } + return true; + + } + case UpdateUnitKind.EditsInsideSingleScope: { + new TypeScript.IncrementalParser(this.logger).mergeTrees(updateResult); + return true; + + } + } + }; + TypeScriptCompiler.prototype.partialUpdateUnit = function (sourceText, filename, setRecovery) { + var _this = this; + return this.timeFunction("partialUpdateUnit(" + filename + ")", function () { + for(var i = 0, len = _this.units.length; i < len; i++) { + if(_this.units[i].filename == filename) { + if((_this.scripts.members[i]).isResident) { + return UpdateUnitResult.noEdits(i); + } + if(setRecovery) { + _this.parser.setErrorRecovery(null); + } + var updateResult; + var parseErrors = []; + var errorCapture = function (minChar, charLen, message, unitIndex) { + parseErrors.push(new ErrorEntry(unitIndex, minChar, minChar + charLen, message)); + }; + var svErrorCallback = _this.parser.errorCallback; + if(svErrorCallback) { + _this.parser.errorCallback = errorCapture; + } + var oldScript = _this.scripts.members[i]; + var newScript = _this.parser.parse(sourceText, filename, i); + if(svErrorCallback) { + _this.parser.errorCallback = svErrorCallback; + } + updateResult = UpdateUnitResult.unknownEdits(oldScript, newScript, parseErrors); + return updateResult; + } + } + throw new Error("Unknown file \"" + filename + "\""); + }); + }; + TypeScriptCompiler.prototype.addUnit = function (prog, filename, keepResident, referencedFiles) { + if (typeof keepResident === "undefined") { keepResident = false; } + if (typeof referencedFiles === "undefined") { referencedFiles = []; } + return this.addSourceUnit(new TypeScript.StringSourceText(prog), filename, keepResident, referencedFiles); + }; + TypeScriptCompiler.prototype.addSourceUnit = function (sourceText, filename, keepResident, referencedFiles) { + if (typeof referencedFiles === "undefined") { referencedFiles = []; } + var _this = this; + return this.timeFunction("addSourceUnit(" + filename + ", " + keepResident + ")", function () { + var script = _this.parser.parse(sourceText, filename, _this.units.length, TypeScript.AllowedElements.Global); + script.referencedFiles = referencedFiles; + script.isResident = keepResident; + _this.persistentTypeState.setCollectionMode(keepResident ? TypeScript.TypeCheckCollectionMode.Resident : TypeScript.TypeCheckCollectionMode.Transient); + var index = _this.units.length; + _this.units[index] = script.locationInfo; + _this.typeChecker.collectTypes(script); + _this.scripts.append(script); + return script; + }); + }; + TypeScriptCompiler.prototype.parseUnit = function (prog, filename) { + return this.parseSourceUnit(new TypeScript.StringSourceText(prog), filename); + }; + TypeScriptCompiler.prototype.parseSourceUnit = function (sourceText, filename) { + this.parser.setErrorRecovery(this.errorOutput); + var script = this.parser.parse(sourceText, filename, 0); + var index = this.units.length; + this.units[index] = script.locationInfo; + this.typeChecker.collectTypes(script); + this.scripts.append(script); + }; + TypeScriptCompiler.prototype.typeCheck = function () { + var _this = this; + return this.timeFunction("typeCheck()", function () { + var binder = new TypeScript.Binder(_this.typeChecker); + _this.typeChecker.units = _this.units; + binder.bind(_this.typeChecker.globalScope, _this.typeChecker.globals); + binder.bind(_this.typeChecker.globalScope, _this.typeChecker.ambientGlobals); + binder.bind(_this.typeChecker.globalScope, _this.typeChecker.globalTypes); + binder.bind(_this.typeChecker.globalScope, _this.typeChecker.ambientGlobalTypes); + _this.typeFlow = new TypeScript.TypeFlow(_this.logger, _this.typeChecker.globalScope, _this.parser, _this.typeChecker); + var i = 0; + var script = null; + var len = _this.scripts.members.length; + _this.persistentTypeState.setCollectionMode(TypeScript.TypeCheckCollectionMode.Resident); + for(i = 0; i < len; i++) { + script = _this.scripts.members[i]; + if(!script.isResident || script.hasBeenTypeChecked) { + continue; + } + _this.typeFlow.assignScopes(script); + _this.typeFlow.initLibs(); + } + for(i = 0; i < len; i++) { + script = _this.scripts.members[i]; + if(!script.isResident || script.hasBeenTypeChecked) { + continue; + } + _this.typeFlow.typeCheck(script); + script.hasBeenTypeChecked = true; + } + _this.persistentTypeState.setCollectionMode(TypeScript.TypeCheckCollectionMode.Transient); + len = _this.scripts.members.length; + for(i = 0; i < len; i++) { + script = _this.scripts.members[i]; + if(script.isResident) { + continue; + } + _this.typeFlow.assignScopes(script); + _this.typeFlow.initLibs(); + } + for(i = 0; i < len; i++) { + script = _this.scripts.members[i]; + if(script.isResident) { + continue; + } + _this.typeFlow.typeCheck(script); + } + return null; + }); + }; + TypeScriptCompiler.prototype.cleanASTTypesForReTypeCheck = function (ast) { + function cleanASTType(ast, parent) { + ast.type = null; + if(ast.nodeType == TypeScript.NodeType.VarDecl) { + var vardecl = ast; + vardecl.sym = null; + } else { + if(ast.nodeType == TypeScript.NodeType.ArgDecl) { + var argdecl = ast; + argdecl.sym = null; + } else { + if(ast.nodeType == TypeScript.NodeType.Name) { + var name = ast; + name.sym = null; + } else { + if(ast.nodeType == TypeScript.NodeType.FuncDecl) { + var funcdecl = ast; + funcdecl.signature = null; + funcdecl.freeVariables = new Array(); + funcdecl.symbols = null; + funcdecl.accessorSymbol = null; + funcdecl.scopeType = null; + } else { + if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { + var modDecl = ast; + modDecl.mod = null; + } else { + if(ast.nodeType == TypeScript.NodeType.With) { + (ast).withSym = null; + } else { + if(ast.nodeType == TypeScript.NodeType.Catch) { + (ast).containedScope = null; + } + } + } + } + } + } + } + return ast; + } + TypeScript.getAstWalkerFactory().walk(ast, cleanASTType); + }; + TypeScriptCompiler.prototype.cleanTypesForReTypeCheck = function () { + var _this = this; + return this.timeFunction("cleanTypesForReTypeCheck()", function () { + for(var i = 0, len = _this.scripts.members.length; i < len; i++) { + var script = _this.scripts.members[i]; + if((script).isResident) { + continue; + } + _this.cleanASTTypesForReTypeCheck(script); + _this.typeChecker.collectTypes(script); + } + return null; + }); + }; + TypeScriptCompiler.prototype.attemptIncrementalTypeCheck = function (updateResult) { + return this.timeFunction("attemptIncrementalTypeCheck()", function () { + return false; + }); + }; + TypeScriptCompiler.prototype.reTypeCheck = function () { + var _this = this; + return this.timeFunction("reTypeCheck()", function () { + TypeScript.CompilerDiagnostics.analysisPass++; + _this.initTypeChecker(_this.errorOutput); + _this.persistentTypeState.setCollectionMode(TypeScript.TypeCheckCollectionMode.Transient); + _this.cleanTypesForReTypeCheck(); + return _this.typeCheck(); + }); + }; + TypeScriptCompiler.prototype.isDynamicModuleCompilation = function () { + for(var i = 0, len = this.scripts.members.length; i < len; i++) { + var script = this.scripts.members[i]; + if(!script.isDeclareFile && script.topLevelMod != null) { + return true; + } + } + return false; + }; + TypeScriptCompiler.prototype.updateCommonDirectoryPath = function () { + var commonComponents = []; + var commonComponentsLength = -1; + for(var i = 0, len = this.scripts.members.length; i < len; i++) { + var script = this.scripts.members[i]; + if(script.emitRequired(this.emitSettings)) { + var fileName = script.locationInfo.filename; + var fileComponents = TypeScript.filePathComponents(fileName); + if(commonComponentsLength == -1) { + commonComponents = fileComponents; + commonComponentsLength = commonComponents.length; + } else { + var updatedPath = false; + for(var j = 0; j < commonComponentsLength && j < fileComponents.length; j++) { + if(commonComponents[j] != fileComponents[j]) { + commonComponentsLength = j; + updatedPath = true; + if(j == 0) { + this.errorReporter.emitterError(null, "Cannot find the common subdirectory path for the input files"); + return; + } + break; + } + } + if(!updatedPath && fileComponents.length < commonComponentsLength) { + commonComponentsLength = fileComponents.length; + } + } + } + } + this.emitSettings.commonDirectoryPath = commonComponents.slice(0, commonComponentsLength).join("/") + "/"; + if(this.emitSettings.outputOption.charAt(this.emitSettings.outputOption.length - 1) != "/") { + this.emitSettings.outputOption += "/"; + } + }; + TypeScriptCompiler.prototype.parseEmitOption = function (ioHost) { + this.emitSettings.ioHost = ioHost; + if(this.emitSettings.outputOption == "") { + this.emitSettings.outputMany = true; + this.emitSettings.commonDirectoryPath = ""; + return; + } + this.emitSettings.outputOption = TypeScript.switchToForwardSlashes(this.emitSettings.ioHost.resolvePath(this.emitSettings.outputOption)); + if(this.emitSettings.ioHost.directoryExists(this.emitSettings.outputOption)) { + this.emitSettings.outputMany = true; + } else { + if(this.emitSettings.ioHost.fileExists(this.emitSettings.outputOption)) { + this.emitSettings.outputMany = false; + } else { + this.emitSettings.outputMany = !TypeScript.isJSFile(this.emitSettings.outputOption); + } + } + if(this.isDynamicModuleCompilation() && !this.emitSettings.outputMany) { + this.errorReporter.emitterError(null, "Cannot compile dynamic modules when emitting into single file"); + } + if(this.emitSettings.outputMany) { + this.updateCommonDirectoryPath(); + } + }; + TypeScriptCompiler.prototype.useUTF8ForFile = function (script) { + if(this.emitSettings.outputMany) { + return this.outputScriptToUTF8(script); + } else { + return this.outputScriptsToUTF8((this.scripts.members)); + } + }; + TypeScriptCompiler.mapToDTSFileName = function mapToDTSFileName(fileName, wholeFileNameReplaced) { + return TypeScript.getDeclareFilePath(fileName); + } + TypeScriptCompiler.prototype.canEmitDeclarations = function (script) { + if(!this.settings.generateDeclarationFiles) { + return false; + } + if(!!script && (script.isDeclareFile || script.isResident || script.bod == null)) { + return false; + } + return true; + }; + TypeScriptCompiler.prototype.emitDeclarationsUnit = function (script, reuseEmitter, declarationEmitter) { + if(!this.canEmitDeclarations(script)) { + return null; + } + if(!declarationEmitter) { + var declareFileName = this.emitSettings.mapOutputFileName(script.locationInfo.filename, TypeScriptCompiler.mapToDTSFileName); + var declareFile = this.createFile(declareFileName, this.useUTF8ForFile(script)); + declarationEmitter = new TypeScript.DeclarationEmitter(this.typeChecker, this.emitSettings, this.errorReporter); + declarationEmitter.setDeclarationFile(declareFile); + } + declarationEmitter.emitDeclarations(script); + if(!reuseEmitter) { + declarationEmitter.Close(); + return null; + } else { + return declarationEmitter; + } + }; + TypeScriptCompiler.prototype.emitDeclarations = function () { + if(!this.canEmitDeclarations()) { + return; + } + if(this.errorReporter.hasErrors) { + return; + } + if(this.scripts.members.length == 0) { + return; + } + var declarationEmitter = null; + for(var i = 0, len = this.scripts.members.length; i < len; i++) { + var script = this.scripts.members[i]; + if(this.emitSettings.outputMany || declarationEmitter == null) { + declarationEmitter = this.emitDeclarationsUnit(script, !this.emitSettings.outputMany); + } else { + this.emitDeclarationsUnit(script, true, declarationEmitter); + } + } + if(declarationEmitter) { + declarationEmitter.Close(); + } + }; + TypeScriptCompiler.mapToFileNameExtension = function mapToFileNameExtension(extension, fileName, wholeFileNameReplaced) { + if(wholeFileNameReplaced) { + return fileName; + } else { + var splitFname = fileName.split("."); + splitFname.pop(); + return splitFname.join(".") + extension; + } + } + TypeScriptCompiler.mapToJSFileName = function mapToJSFileName(fileName, wholeFileNameReplaced) { + return TypeScriptCompiler.mapToFileNameExtension(".js", fileName, wholeFileNameReplaced); + } + TypeScriptCompiler.prototype.emitUnit = function (script, reuseEmitter, emitter) { + if(!script.emitRequired(this.emitSettings)) { + return null; + } + var fname = script.locationInfo.filename; + if(!emitter) { + var outFname = this.emitSettings.mapOutputFileName(fname, TypeScriptCompiler.mapToJSFileName); + var outFile = this.createFile(outFname, this.useUTF8ForFile(script)); + emitter = new TypeScript.Emitter(this.typeChecker, outFname, outFile, this.emitSettings, this.errorReporter); + if(this.settings.mapSourceFiles) { + emitter.setSourceMappings(new TypeScript.SourceMapper(fname, outFname, outFile, this.createFile(outFname + TypeScript.SourceMapper.MapFileExtension, false), this.errorReporter)); + } + } else { + if(this.settings.mapSourceFiles) { + emitter.setSourceMappings(new TypeScript.SourceMapper(fname, emitter.emittingFileName, emitter.outfile, emitter.sourceMapper.sourceMapOut, this.errorReporter)); + } + } + this.typeChecker.locationInfo = script.locationInfo; + emitter.emitJavascript(script, TypeScript.TokenID.Comma, false); + if(!reuseEmitter) { + emitter.Close(); + return null; + } else { + return emitter; + } + }; + TypeScriptCompiler.prototype.emit = function (ioHost) { + this.parseEmitOption(ioHost); + var emitter = null; + for(var i = 0, len = this.scripts.members.length; i < len; i++) { + var script = this.scripts.members[i]; + if(this.emitSettings.outputMany || emitter == null) { + emitter = this.emitUnit(script, !this.emitSettings.outputMany); + } else { + this.emitUnit(script, true, emitter); + } + } + if(emitter) { + emitter.Close(); + } + }; + TypeScriptCompiler.prototype.emitToOutfile = function (outputFile) { + if(this.settings.mapSourceFiles) { + throw Error("Cannot generate source map"); + } + if(this.settings.generateDeclarationFiles) { + throw Error("Cannot generate declaration files"); + } + if(this.settings.outputOption != "") { + throw Error("Cannot parse output option"); + } + var emitter = emitter = new TypeScript.Emitter(this.typeChecker, "stdout", outputFile, this.emitSettings, this.errorReporter); + ; ; + for(var i = 0, len = this.scripts.members.length; i < len; i++) { + var script = this.scripts.members[i]; + this.typeChecker.locationInfo = script.locationInfo; + emitter.emitJavascript(script, TypeScript.TokenID.Comma, false); + } + }; + TypeScriptCompiler.prototype.emitAST = function (ioHost) { + this.parseEmitOption(ioHost); + var outFile = null; + var context = null; + for(var i = 0, len = this.scripts.members.length; i < len; i++) { + var script = this.scripts.members[i]; + if(this.emitSettings.outputMany || context == null) { + var fname = this.units[i].filename; + var mapToTxtFileName = function (fileName, wholeFileNameReplaced) { + return TypeScriptCompiler.mapToFileNameExtension(".txt", fileName, wholeFileNameReplaced); + }; + var outFname = this.emitSettings.mapOutputFileName(fname, mapToTxtFileName); + outFile = this.createFile(outFname, this.useUTF8ForFile(script)); + context = new TypeScript.PrintContext(outFile, this.parser); + } + TypeScript.getAstWalkerFactory().walk(script, TypeScript.prePrintAST, TypeScript.postPrintAST, null, context); + if(this.emitSettings.outputMany) { + try { + outFile.Close(); + } catch (e) { + this.errorReporter.emitterError(null, e.message); + } + } + } + if(!this.emitSettings.outputMany) { + try { + outFile.Close(); + } catch (e) { + this.errorReporter.emitterError(null, e.message); + } + } + }; + TypeScriptCompiler.prototype.outputScriptToUTF8 = function (script) { + return script.containsUnicodeChar || (this.emitSettings.emitComments && script.containsUnicodeCharInComment); + }; + TypeScriptCompiler.prototype.outputScriptsToUTF8 = function (scripts) { + for(var i = 0, len = scripts.length; i < len; i++) { + var script = scripts[i]; + if(this.outputScriptToUTF8(script)) { + return true; + } + } + return false; + }; + TypeScriptCompiler.prototype.createFile = function (fileName, useUTF8) { + try { + return this.emitSettings.ioHost.createFile(fileName, useUTF8); + } catch (ex) { + this.errorReporter.emitterError(null, ex.message); + } + }; + return TypeScriptCompiler; + })(); + TypeScript.TypeScriptCompiler = TypeScriptCompiler; + var ScopeEntry = (function () { + function ScopeEntry(name, type, sym) { + this.name = name; + this.type = type; + this.sym = sym; + } + return ScopeEntry; + })(); + TypeScript.ScopeEntry = ScopeEntry; + var ScopeTraversal = (function () { + function ScopeTraversal(compiler) { + this.compiler = compiler; + } + ScopeTraversal.prototype.getScope = function (enclosingScopeContext) { + if(enclosingScopeContext.enclosingObjectLit && enclosingScopeContext.isMemberCompletion) { + return enclosingScopeContext.getObjectLiteralScope(); + } else { + if(enclosingScopeContext.isMemberCompletion) { + if(enclosingScopeContext.useFullAst) { + return this.compiler.typeFlow.findMemberScopeAtFullAst(enclosingScopeContext); + } else { + return this.compiler.typeFlow.findMemberScopeAt(enclosingScopeContext); + } + } else { + return enclosingScopeContext.getScope(); + } + } + }; + ScopeTraversal.prototype.getScopeEntries = function (enclosingScopeContext) { + var scope = this.getScope(enclosingScopeContext); + if(scope == null) { + return []; + } + var inScopeNames = new TypeScript.StringHashTable(); + var allSymbolNames = scope.getAllSymbolNames(enclosingScopeContext.isMemberCompletion); + for(var i = 0; i < allSymbolNames.length; i++) { + var name = allSymbolNames[i]; + if(name == TypeScript.globalId || name == "_Core" || name == "_element") { + continue; + } + inScopeNames.add(name, ""); + } + var svModuleDecl = this.compiler.typeChecker.currentModDecl; + this.compiler.typeChecker.currentModDecl = enclosingScopeContext.deepestModuleDecl; + var result = this.getTypeNamesForNames(enclosingScopeContext, inScopeNames.getAllKeys(), scope); + this.compiler.typeChecker.currentModDecl = svModuleDecl; + return result; + }; + ScopeTraversal.prototype.getTypeNamesForNames = function (enclosingScopeContext, allNames, scope) { + var result = []; + var enclosingScope = enclosingScopeContext.getScope(); + for(var i = 0; i < allNames.length; i++) { + var name = allNames[i]; + var publicsOnly = enclosingScopeContext.publicsOnly && enclosingScopeContext.isMemberCompletion; + var symbol = scope.find(name, publicsOnly, false); + if(symbol == null) { + symbol = scope.find(name, publicsOnly, true); + } + var displayThisMember = symbol && symbol.flags & TypeScript.SymbolFlags.Private ? symbol.container == scope.container : true; + if(symbol) { + if(displayThisMember && !TypeScript.isQuoted(symbol.name) && !TypeScript.isRelative(symbol.name)) { + var typeName = symbol.getType().getScopedTypeName(enclosingScope); + result.push(new ScopeEntry(name, typeName, symbol)); + } + } else { + if(name == "true" || name == "false") { + result.push(new ScopeEntry(name, "bool", this.compiler.typeChecker.booleanType.symbol)); + } + } + } + return result; + }; + return ScopeTraversal; + })(); + TypeScript.ScopeTraversal = ScopeTraversal; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (CompilerDiagnostics) { + CompilerDiagnostics.debug = false; + CompilerDiagnostics.diagnosticWriter = null; + CompilerDiagnostics.analysisPass = 0; + function Alert(output) { + if(CompilerDiagnostics.diagnosticWriter) { + CompilerDiagnostics.diagnosticWriter.Alert(output); + } + } + CompilerDiagnostics.Alert = Alert; + function debugPrint(s) { + if(CompilerDiagnostics.debug) { + Alert(s); + } + } + CompilerDiagnostics.debugPrint = debugPrint; + function assert(condition, s) { + if(CompilerDiagnostics.debug) { + if(!condition) { + Alert(s); + } + } + } + CompilerDiagnostics.assert = assert; + })(TypeScript.CompilerDiagnostics || (TypeScript.CompilerDiagnostics = {})); + var CompilerDiagnostics = TypeScript.CompilerDiagnostics; + var NullLogger = (function () { + function NullLogger() { } + NullLogger.prototype.information = function () { + return false; + }; + NullLogger.prototype.debug = function () { + return false; + }; + NullLogger.prototype.warning = function () { + return false; + }; + NullLogger.prototype.error = function () { + return false; + }; + NullLogger.prototype.fatal = function () { + return false; + }; + NullLogger.prototype.log = function (s) { + }; + return NullLogger; + })(); + TypeScript.NullLogger = NullLogger; + var LoggerAdapter = (function () { + function LoggerAdapter(logger) { + this.logger = logger; + this._information = this.logger.information(); + this._debug = this.logger.debug(); + this._warning = this.logger.warning(); + this._error = this.logger.error(); + this._fatal = this.logger.fatal(); + } + LoggerAdapter.prototype.information = function () { + return this._information; + }; + LoggerAdapter.prototype.debug = function () { + return this._debug; + }; + LoggerAdapter.prototype.warning = function () { + return this._warning; + }; + LoggerAdapter.prototype.error = function () { + return this._error; + }; + LoggerAdapter.prototype.fatal = function () { + return this._fatal; + }; + LoggerAdapter.prototype.log = function (s) { + this.logger.log(s); + }; + return LoggerAdapter; + })(); + TypeScript.LoggerAdapter = LoggerAdapter; + var BufferedLogger = (function () { + function BufferedLogger() { + this.logContents = []; + } + BufferedLogger.prototype.information = function () { + return false; + }; + BufferedLogger.prototype.debug = function () { + return false; + }; + BufferedLogger.prototype.warning = function () { + return false; + }; + BufferedLogger.prototype.error = function () { + return false; + }; + BufferedLogger.prototype.fatal = function () { + return false; + }; + BufferedLogger.prototype.log = function (s) { + this.logContents.push(s); + }; + return BufferedLogger; + })(); + TypeScript.BufferedLogger = BufferedLogger; + function timeFunction(logger, funcDescription, func) { + var start = +new Date(); + var result = func(); + var end = +new Date(); + logger.log(funcDescription + " completed in " + (end - start) + " msec"); + return result; + } + TypeScript.timeFunction = timeFunction; + function stringToLiteral(value, length) { + var result = ""; + var addChar = function (index) { + var ch = value.charCodeAt(index); + switch(ch) { + case 9: { + result += "\\t"; + break; + + } + case 10: { + result += "\\n"; + break; + + } + case 11: { + result += "\\v"; + break; + + } + case 12: { + result += "\\f"; + break; + + } + case 13: { + result += "\\r"; + break; + + } + case 34: { + result += "\\\""; + break; + + } + case 39: { + result += "\\\'"; + break; + + } + case 92: { + result += "\\"; + break; + + } + default: { + result += value.charAt(index); + + } + } + }; + var tooLong = (value.length > length); + if(tooLong) { + var mid = length >> 1; + for(var i = 0; i < mid; i++) { + addChar(i); + } + result += "(...)"; + for(var i = value.length - mid; i < value.length; i++) { + addChar(i); + } + } else { + length = value.length; + for(var i = 0; i < length; i++) { + addChar(i); + } + } + return result; + } + TypeScript.stringToLiteral = stringToLiteral; +})(TypeScript || (TypeScript = {})); +var IOUtils; +(function (IOUtils) { + function createDirectoryStructure(ioHost, dirName) { + if(ioHost.directoryExists(dirName)) { + return; + } + var parentDirectory = ioHost.dirName(dirName); + if(parentDirectory != "") { + createDirectoryStructure(ioHost, parentDirectory); + } + ioHost.createDirectory(dirName); + } + function createFileAndFolderStructure(ioHost, fileName, useUTF8) { + var path = ioHost.resolvePath(fileName); + var dirName = ioHost.dirName(path); + createDirectoryStructure(ioHost, dirName); + return ioHost.createFile(path, useUTF8); + } + IOUtils.createFileAndFolderStructure = createFileAndFolderStructure; + function throwIOError(message, error) { + var errorMessage = message; + if(error && error.message) { + errorMessage += (" " + error.message); + } + throw new Error(errorMessage); + } + IOUtils.throwIOError = throwIOError; +})(IOUtils || (IOUtils = {})); + +var IO = (function () { + function getWindowsScriptHostIO() { + var fso = new ActiveXObject("Scripting.FileSystemObject"); + var streamObjectPool = []; + function getStreamObject() { + if(streamObjectPool.length > 0) { + return streamObjectPool.pop(); + } else { + return new ActiveXObject("ADODB.Stream"); + } + } + function releaseStreamObject(obj) { + streamObjectPool.push(obj); + } + var args = []; + for(var i = 0; i < WScript.Arguments.length; i++) { + args[i] = WScript.Arguments.Item(i); + } + return { + readFile: function (path) { + try { + var streamObj = getStreamObject(); + streamObj.Open(); + streamObj.Type = 2; + streamObj.Charset = 'x-ansi'; + streamObj.LoadFromFile(path); + var bomChar = streamObj.ReadText(2); + streamObj.Position = 0; + if((bomChar.charCodeAt(0) == 254 && bomChar.charCodeAt(1) == 255) || (bomChar.charCodeAt(0) == 255 && bomChar.charCodeAt(1) == 254)) { + streamObj.Charset = 'unicode'; + } else { + if(bomChar.charCodeAt(0) == 239 && bomChar.charCodeAt(1) == 187) { + streamObj.Charset = 'utf-8'; + } + } + var str = streamObj.ReadText(-1); + streamObj.Close(); + releaseStreamObject(streamObj); + return str; + } catch (err) { + IOUtils.throwIOError("Error reading file \"" + path + "\".", err); + } + }, + writeFile: function (path, contents) { + var file = this.createFile(path); + file.Write(contents); + file.Close(); + }, + fileExists: function (path) { + return fso.FileExists(path); + }, + resolvePath: function (path) { + return fso.GetAbsolutePathName(path); + }, + dirName: function (path) { + return fso.GetParentFolderName(path); + }, + findFile: function (rootPath, partialFilePath) { + var path = fso.GetAbsolutePathName(rootPath) + "/" + partialFilePath; + while(true) { + if(fso.FileExists(path)) { + try { + var content = this.readFile(path); + return { + content: content, + path: path + }; + } catch (err) { + } + } else { + rootPath = fso.GetParentFolderName(fso.GetAbsolutePathName(rootPath)); + if(rootPath == "") { + return null; + } else { + path = fso.BuildPath(rootPath, partialFilePath); + } + } + } + }, + deleteFile: function (path) { + try { + if(fso.FileExists(path)) { + fso.DeleteFile(path, true); + } + } catch (e) { + IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); + } + }, + createFile: function (path, useUTF8) { + try { + var streamObj = getStreamObject(); + streamObj.Charset = useUTF8 ? 'utf-8' : 'x-ansi'; + streamObj.Open(); + return { + Write: function (str) { + streamObj.WriteText(str, 0); + }, + WriteLine: function (str) { + streamObj.WriteText(str, 1); + }, + Close: function () { + try { + streamObj.SaveToFile(path, 2); + } catch (saveError) { + IOUtils.throwIOError("Couldn't write to file '" + path + "'.", saveError); + }finally { + if(streamObj.State != 0) { + streamObj.Close(); + } + releaseStreamObject(streamObj); + } + } + }; + } catch (creationError) { + IOUtils.throwIOError("Couldn't write to file '" + path + "'.", creationError); + } + }, + directoryExists: function (path) { + return fso.FolderExists(path); + }, + createDirectory: function (path) { + try { + if(!this.directoryExists(path)) { + fso.CreateFolder(path); + } + } catch (e) { + IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e); + } + }, + dir: function (path, spec, options) { + options = options || { + }; + function filesInFolder(folder, root) { + var paths = []; + var fc; + if(options.recursive) { + fc = new Enumerator(folder.subfolders); + for(; !fc.atEnd(); fc.moveNext()) { + paths = paths.concat(filesInFolder(fc.item(), root + "/" + fc.item().Name)); + } + } + fc = new Enumerator(folder.files); + for(; !fc.atEnd(); fc.moveNext()) { + if(!spec || fc.item().Name.match(spec)) { + paths.push(root + "/" + fc.item().Name); + } + } + return paths; + } + var folder = fso.GetFolder(path); + var paths = []; + return filesInFolder(folder, path); + }, + print: function (str) { + WScript.StdOut.Write(str); + }, + printLine: function (str) { + WScript.Echo(str); + }, + arguments: args, + stderr: WScript.StdErr, + stdout: WScript.StdOut, + watchFile: null, + run: function (source, filename) { + try { + eval(source); + } catch (e) { + IOUtils.throwIOError("Error while executing file '" + filename + "'.", e); + } + }, + getExecutingFilePath: function () { + return WScript.ScriptFullName; + }, + quit: function (exitCode) { + if (typeof exitCode === "undefined") { exitCode = 0; } + try { + WScript.Quit(exitCode); + } catch (e) { + } + } + }; + } + ; ; + function getNodeIO() { + var _fs = require('fs'); + var _path = require('path'); + var _module = require('module'); + return { + readFile: function (file) { + try { + var buffer = _fs.readFileSync(file); + switch(buffer[0]) { + case 254: { + if(buffer[1] == 255) { + var i = 0; + while((i + 1) < buffer.length) { + var temp = buffer[i]; + buffer[i] = buffer[i + 1]; + buffer[i + 1] = temp; + i += 2; + } + return buffer.toString("ucs2", 2); + } + break; + + } + case 255: { + if(buffer[1] == 254) { + return buffer.toString("ucs2", 2); + } + break; + + } + case 239: { + if(buffer[1] == 187) { + return buffer.toString("utf8", 3); + } + + } + } + return buffer.toString(); + } catch (e) { + IOUtils.throwIOError("Error reading file \"" + file + "\".", e); + } + }, + writeFile: _fs.writeFileSync, + deleteFile: function (path) { + try { + _fs.unlinkSync(path); + } catch (e) { + IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); + } + }, + fileExists: function (path) { + return _fs.existsSync(path); + }, + createFile: function (path, useUTF8) { + function mkdirRecursiveSync(path) { + var stats = _fs.statSync(path); + if(stats.isFile()) { + IOUtils.throwIOError("\"" + path + "\" exists but isn't a directory.", null); + } else { + if(stats.isDirectory()) { + return; + } else { + mkdirRecursiveSync(_path.dirname(path)); + _fs.mkdirSync(path, 509); + } + } + } + mkdirRecursiveSync(_path.dirname(path)); + try { + var fd = _fs.openSync(path, 'w'); + } catch (e) { + IOUtils.throwIOError("Couldn't write to file '" + path + "'.", e); + } + return { + Write: function (str) { + _fs.writeSync(fd, str); + }, + WriteLine: function (str) { + _fs.writeSync(fd, str + '\r\n'); + }, + Close: function () { + _fs.closeSync(fd); + fd = null; + } + }; + }, + dir: function dir(path, spec, options) { + options = options || { + }; + function filesInFolder(folder) { + var paths = []; + var files = _fs.readdirSync(folder); + for(var i = 0; i < files.length; i++) { + var stat = _fs.statSync(folder + "/" + files[i]); + if(options.recursive && stat.isDirectory()) { + paths = paths.concat(filesInFolder(folder + "/" + files[i])); + } else { + if(stat.isFile() && (!spec || files[i].match(spec))) { + paths.push(folder + "/" + files[i]); + } + } + } + return paths; + } + return filesInFolder(path); + }, + createDirectory: function (path) { + try { + if(!this.directoryExists(path)) { + _fs.mkdirSync(path); + } + } catch (e) { + IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e); + } + }, + directoryExists: function (path) { + return _fs.existsSync(path) && _fs.lstatSync(path).isDirectory(); + }, + resolvePath: function (path) { + return _path.resolve(path); + }, + dirName: function (path) { + return _path.dirname(path); + }, + findFile: function (rootPath, partialFilePath) { + var path = rootPath + "/" + partialFilePath; + while(true) { + if(_fs.existsSync(path)) { + try { + var content = this.readFile(path); + return { + content: content, + path: path + }; + } catch (err) { + } + } else { + var parentPath = _path.resolve(rootPath, ".."); + if(rootPath === parentPath) { + return null; + } else { + rootPath = parentPath; + path = _path.resolve(rootPath, partialFilePath); + } + } + } + }, + print: function (str) { + process.stdout.write(str); + }, + printLine: function (str) { + process.stdout.write(str + '\n'); + }, + arguments: process.argv.slice(2), + stderr: { + Write: function (str) { + process.stderr.write(str); + }, + WriteLine: function (str) { + process.stderr.write(str + '\n'); + }, + Close: function () { + } + }, + stdout: { + Write: function (str) { + process.stdout.write(str); + }, + WriteLine: function (str) { + process.stdout.write(str + '\n'); + }, + Close: function () { + } + }, + watchFile: function (filename, callback) { + var firstRun = true; + var processingChange = false; + var fileChanged = function (curr, prev) { + if(!firstRun) { + if(curr.mtime < prev.mtime) { + return; + } + _fs.unwatchFile(filename, fileChanged); + if(!processingChange) { + processingChange = true; + callback(filename); + setTimeout(function () { + processingChange = false; + }, 100); + } + } + firstRun = false; + _fs.watchFile(filename, { + persistent: true, + interval: 500 + }, fileChanged); + }; + fileChanged(); + return { + filename: filename, + close: function () { + _fs.unwatchFile(filename, fileChanged); + } + }; + }, + run: function (source, filename) { + require.main.filename = filename; + require.main.paths = _module._nodeModulePaths(_path.dirname(_fs.realpathSync(filename))); + require.main._compile(source, filename); + }, + getExecutingFilePath: function () { + return process.mainModule.filename; + }, + quit: process.exit + }; + } + ; ; + if(typeof ActiveXObject === "function") { + return getWindowsScriptHostIO(); + } else { + if(typeof require === "function") { + return getNodeIO(); + } else { + return null; + } + } +})(); +var OptionsParser = (function () { + function OptionsParser(host) { + this.host = host; + this.DEFAULT_SHORT_FLAG = "-"; + this.DEFAULT_LONG_FLAG = "--"; + this.unnamed = []; + this.options = []; + } + OptionsParser.prototype.findOption = function (arg) { + for(var i = 0; i < this.options.length; i++) { + if(arg === this.options[i].short || arg === this.options[i].name) { + return this.options[i]; + } + } + return null; + }; + OptionsParser.prototype.printUsage = function () { + this.host.printLine("Syntax: tsc [options] [file ..]"); + this.host.printLine(""); + this.host.printLine("Examples: tsc hello.ts"); + this.host.printLine(" tsc --out foo.js foo.ts"); + this.host.printLine(" tsc @args.txt"); + this.host.printLine(""); + this.host.printLine("Options:"); + var output = []; + var maxLength = 0; + this.options = this.options.sort(function (a, b) { + var aName = a.name.toLowerCase(); + var bName = b.name.toLowerCase(); + if(aName > bName) { + return 1; + } else { + if(aName < bName) { + return -1; + } else { + return 0; + } + } + }); + for(var i = 0; i < this.options.length; i++) { + var option = this.options[i]; + if(option.experimental) { + continue; + } + if(!option.usage) { + break; + } + var usageString = " "; + var type = option.type ? " " + option.type.toUpperCase() : ""; + if(option.short) { + usageString += this.DEFAULT_SHORT_FLAG + option.short + type + ", "; + } + usageString += this.DEFAULT_LONG_FLAG + option.name + type; + output.push([ + usageString, + option.usage + ]); + if(usageString.length > maxLength) { + maxLength = usageString.length; + } + } + output.push([ + " @", + "Insert command line options and files from a file." + ]); + for(var i = 0; i < output.length; i++) { + this.host.printLine(output[i][0] + (new Array(maxLength - output[i][0].length + 3)).join(" ") + output[i][1]); + } + }; + OptionsParser.prototype.option = function (name, config, short) { + if(!config) { + config = short; + short = null; + } + config.name = name; + config.short = short; + config.flag = false; + this.options.push(config); + }; + OptionsParser.prototype.flag = function (name, config, short) { + if(!config) { + config = short; + short = null; + } + config.name = name; + config.short = short; + config.flag = true; + this.options.push(config); + }; + OptionsParser.prototype.parseString = function (argString) { + var position = 0; + var tokens = argString.match(/\s+|"|[^\s"]+/g); + function peek() { + return tokens[position]; + } + function consume() { + return tokens[position++]; + } + function consumeQuotedString() { + var value = ''; + consume(); + var token = peek(); + while(token && token !== '"') { + consume(); + value += token; + token = peek(); + } + consume(); + return value; + } + var args = []; + var currentArg = ''; + while(position < tokens.length) { + var token = peek(); + if(token === '"') { + currentArg += consumeQuotedString(); + } else { + if(token.match(/\s/)) { + if(currentArg.length > 0) { + args.push(currentArg); + currentArg = ''; + } + consume(); + } else { + consume(); + currentArg += token; + } + } + } + if(currentArg.length > 0) { + args.push(currentArg); + } + this.parse(args); + }; + OptionsParser.prototype.parse = function (args) { + var position = 0; + function consume() { + return args[position++]; + } + while(position < args.length) { + var current = consume(); + var match = current.match(/^(--?|@)(.*)/); + var value = null; + if(match) { + if(match[1] === '@') { + this.parseString(this.host.readFile(match[2])); + } else { + var arg = match[2]; + var option = this.findOption(arg); + if(option === null) { + this.host.printLine("Unknown option '" + arg + "'"); + this.host.printLine("Use the '--help' flag to see options"); + } else { + if(!option.flag) { + value = consume(); + } + option.set(value); + } + } + } else { + this.unnamed.push(current); + } + } + }; + return OptionsParser; +})(); +var CommandLineHost = (function () { + function CommandLineHost(compilationSettings) { + this.compilationSettings = compilationSettings; + this.pathMap = { + }; + this.resolvedPaths = { + }; + } + CommandLineHost.prototype.getPathIdentifier = function (path) { + return this.compilationSettings.useCaseSensitiveFileResolution ? path : path.toLocaleUpperCase(); + }; + CommandLineHost.prototype.isResolved = function (path) { + return this.resolvedPaths[this.getPathIdentifier(this.pathMap[path])] != undefined; + }; + CommandLineHost.prototype.resolveCompilationEnvironment = function (preEnv, resolver, traceDependencies) { + var _this = this; + var resolvedEnv = new TypeScript.CompilationEnvironment(preEnv.compilationSettings, preEnv.ioHost); + var nCode = preEnv.code.length; + var path = ""; + var postResolutionError = function (errorFile, errorMessage) { + TypeScript.CompilerDiagnostics.debugPrint("Could not resolve file '" + errorFile + "'" + (errorMessage == "" ? "" : ": " + errorMessage)); + }; + var resolutionDispatcher = { + postResolutionError: postResolutionError, + postResolution: function (path, code) { + var pathId = _this.getPathIdentifier(path); + if(!_this.resolvedPaths[pathId]) { + resolvedEnv.code.push(code); + _this.resolvedPaths[pathId] = true; + } + } + }; + for(var i = 0; i < nCode; i++) { + path = TypeScript.switchToForwardSlashes(preEnv.ioHost.resolvePath(preEnv.code[i].path)); + this.pathMap[preEnv.code[i].path] = path; + resolver.resolveCode(path, "", false, resolutionDispatcher); + } + return resolvedEnv; + }; + return CommandLineHost; +})(); +var BatchCompiler = (function () { + function BatchCompiler(ioHost) { + this.ioHost = ioHost; + this.resolvedEnvironment = null; + this.hasResolveErrors = false; + this.compilerVersion = "0.8.2.0"; + this.printedVersion = false; + this.compilationSettings = new TypeScript.CompilationSettings(); + this.compilationEnvironment = new TypeScript.CompilationEnvironment(this.compilationSettings, this.ioHost); + } + BatchCompiler.prototype.resolve = function () { + var resolver = new TypeScript.CodeResolver(this.compilationEnvironment); + var commandLineHost = new CommandLineHost(this.compilationSettings); + var ret = commandLineHost.resolveCompilationEnvironment(this.compilationEnvironment, resolver, true); + this.hasResolveErrors = false; + for(var i = 0; i < this.compilationEnvironment.code.length; i++) { + if(!commandLineHost.isResolved(this.compilationEnvironment.code[i].path)) { + this.hasResolveErrors = true; + var path = this.compilationEnvironment.code[i].path; + if(!TypeScript.isSTRFile(path) && !TypeScript.isDSTRFile(path) && !TypeScript.isTSFile(path) && !TypeScript.isDTSFile(path)) { + this.ioHost.stderr.WriteLine("Unknown extension for file: \"" + path + "\". Only .ts and .d.ts extensions are allowed."); + } else { + this.ioHost.stderr.WriteLine("Error reading file \"" + path + "\": File not found"); + } + } + } + return ret; + }; + BatchCompiler.prototype.compile = function () { + var _this = this; + var compiler; + compiler = new TypeScript.TypeScriptCompiler(this.ioHost.stderr, new TypeScript.NullLogger(), this.compilationSettings); + compiler.setErrorOutput(this.ioHost.stderr); + compiler.setErrorCallback(function (minChar, charLen, message, unitIndex) { + compiler.errorReporter.hasErrors = true; + var fname = _this.resolvedEnvironment.code[unitIndex].path; + var lineCol = { + line: -1, + col: -1 + }; + compiler.parser.getSourceLineCol(lineCol, minChar); + var msg = fname + " (" + lineCol.line + "," + (lineCol.col + 1) + "): " + message; + if(_this.compilationSettings.errorRecovery) { + _this.ioHost.stderr.WriteLine(msg); + } else { + throw new SyntaxError(msg); + } + }); + if(this.compilationSettings.emitComments) { + compiler.emitCommentsToOutput(); + } + var consumeUnit = function (code, addAsResident) { + try { + if(!_this.compilationSettings.resolve) { + code.content = _this.ioHost.readFile(code.path); + if(_this.compilationSettings.generateDeclarationFiles) { + TypeScript.CompilerDiagnostics.assert(code.referencedFiles == null, "With no resolve option, referenced files need to null"); + code.referencedFiles = TypeScript.getReferencedFiles(code); + } + } + if(code.content) { + if(_this.compilationSettings.parseOnly) { + compiler.parseUnit(code.content, code.path); + } else { + if(_this.compilationSettings.errorRecovery) { + compiler.parser.setErrorRecovery(_this.ioHost.stderr); + } + compiler.addUnit(code.content, code.path, addAsResident, code.referencedFiles); + } + } + } catch (err) { + compiler.errorReporter.hasErrors = true; + _this.ioHost.stderr.WriteLine(err.message); + } + }; + for(var iCode = 0; iCode < this.resolvedEnvironment.code.length; iCode++) { + if(!this.compilationSettings.parseOnly || (iCode > 0)) { + consumeUnit(this.resolvedEnvironment.code[iCode], false); + } + } + var emitterIOHost = { + createFile: function (fileName, useUTF8) { + return IOUtils.createFileAndFolderStructure(_this.ioHost, fileName, useUTF8); + }, + directoryExists: this.ioHost.directoryExists, + fileExists: this.ioHost.fileExists, + resolvePath: this.ioHost.resolvePath + }; + try { + if(!this.compilationSettings.parseOnly) { + compiler.typeCheck(); + compiler.emit(emitterIOHost); + compiler.emitDeclarations(); + } else { + compiler.emitAST(emitterIOHost); + } + } catch (err) { + compiler.errorReporter.hasErrors = true; + if(err.message != "EmitError") { + throw err; + } + } + return compiler.errorReporter.hasErrors; + }; + BatchCompiler.prototype.run = function () { + for(var i = 0; i < this.compilationEnvironment.code.length; i++) { + var unit = this.compilationEnvironment.code[i]; + var outputFileName = unit.path; + if(TypeScript.isTSFile(outputFileName)) { + outputFileName = outputFileName.replace(/\.ts$/, ".js"); + } else { + if(TypeScript.isSTRFile(outputFileName)) { + outputFileName = outputFileName.replace(/\.str$/, ".js"); + } + } + if(this.ioHost.fileExists(outputFileName)) { + var unitRes = this.ioHost.readFile(outputFileName); + this.ioHost.run(unitRes, outputFileName); + } + } + }; + BatchCompiler.prototype.batchCompile = function () { + var _this = this; + TypeScript.CompilerDiagnostics.diagnosticWriter = { + Alert: function (s) { + _this.ioHost.printLine(s); + } + }; + var code; + var opts = new OptionsParser(this.ioHost); + opts.option('out', { + usage: 'Concatenate and emit output to single file | Redirect output structure to the directory', + type: 'file|directory', + set: function (str) { + _this.compilationSettings.outputOption = str; + } + }); + opts.option('style', { + usage: 'Select style checking options (examples --style requireSemi:off or --style "eqeqeq;bitwise:off")', + experimental: true, + set: function (str) { + _this.compilationSettings.setStyleOptions(str); + } + }); + opts.flag('sourcemap', { + usage: 'Generates corresponding .map file', + set: function () { + _this.compilationSettings.mapSourceFiles = true; + } + }); + opts.flag('declaration', { + usage: 'Generates corresponding .d.ts file', + set: function () { + _this.compilationSettings.generateDeclarationFiles = true; + } + }); + if(this.ioHost.watchFile) { + opts.flag('watch', { + usage: 'Watch output files', + set: function () { + _this.compilationSettings.watch = true; + } + }, 'w'); + } + opts.flag('exec', { + usage: 'Execute the script after compilation', + set: function () { + _this.compilationSettings.exec = true; + } + }, 'e'); + opts.flag('parse', { + usage: 'Parse only', + experimental: true, + set: function () { + _this.compilationSettings.parseOnly = true; + } + }); + opts.flag('minw', { + usage: 'Minimize whitespace', + experimental: true, + set: function () { + _this.compilationSettings.minWhitespace = true; + } + }, 'mw'); + opts.flag('const', { + usage: 'Propagate constants to emitted code', + experimental: true, + set: function () { + _this.compilationSettings.propagateConstants = true; + } + }); + opts.flag('errorrecovery', { + usage: 'Enable error recovery', + experimental: true, + set: function () { + _this.compilationSettings.errorRecovery = true; + } + }, 'er'); + opts.flag('comments', { + usage: 'Emit comments to output', + set: function () { + _this.compilationSettings.emitComments = true; + } + }, 'c'); + opts.flag('cflow', { + usage: 'Control flow', + experimental: true, + set: function () { + _this.compilationSettings.controlFlow = true; + } + }); + opts.flag('cflowp', { + usage: 'Print control flow', + experimental: true, + set: function () { + _this.compilationSettings.controlFlow = true; + _this.compilationSettings.printControlFlow = true; + } + }); + opts.flag('cflowu', { + usage: 'Print Use Def control flow', + experimental: true, + set: function () { + _this.compilationSettings.controlFlow = true; + _this.compilationSettings.controlFlowUseDef = true; + } + }); + opts.flag('noerroronwith', { + usage: 'Allow with statements', + experimental: true, + set: function () { + _this.compilationSettings.errorOnWith = false; + } + }); + opts.flag('noresolve', { + usage: 'Skip resolution and preprocessing', + experimental: true, + set: function () { + _this.compilationSettings.resolve = false; + _this.compilationSettings.preprocess = false; + } + }); + opts.flag('debug', { + usage: 'Print debug output', + experimental: true, + set: function () { + TypeScript.CompilerDiagnostics.debug = true; + } + }); + opts.flag('canCallDefinitionSignature', { + usage: 'Allows you to call the definition signature of an overload group', + experimental: true, + set: function () { + _this.compilationSettings.canCallDefinitionSignature = true; + } + }); + opts.flag('nooptimizemodules', { + usage: 'Do not optimize module codegen', + experimental: true, + set: function () { + TypeScript.optimizeModuleCodeGen = false; + } + }); + opts.flag('nolib', { + usage: 'Do not include a default lib.d.ts with global declarations', + set: function () { + _this.compilationSettings.useDefaultLib = false; + } + }); + opts.flag('inferProperties', { + usage: 'Infer class properties from top-level assignments to \'this\'', + experimental: true, + set: function () { + _this.compilationSettings.inferPropertiesFromThisAssignment = true; + } + }); + opts.option('target', { + usage: 'Specify ECMAScript target version: "ES3" (default), or "ES5"', + type: 'VER', + set: function (type) { + type = type.toLowerCase(); + if(type === 'es3') { + _this.compilationSettings.codeGenTarget = TypeScript.CodeGenTarget.ES3; + } else { + if(type === 'es5') { + _this.compilationSettings.codeGenTarget = TypeScript.CodeGenTarget.ES5; + } else { + _this.ioHost.printLine("ECMAScript target version '" + type + "' not supported. Using default 'ES3' code generation"); + } + } + } + }); + opts.option('module', { + usage: 'Specify module code generation: "commonjs" (default) or "amd"', + type: 'kind', + set: function (type) { + type = type.toLowerCase(); + if(type === 'commonjs' || type === 'node') { + TypeScript.moduleGenTarget = TypeScript.ModuleGenTarget.Synchronous; + } else { + if(type === 'amd') { + TypeScript.moduleGenTarget = TypeScript.ModuleGenTarget.Asynchronous; + } else { + _this.ioHost.printLine("Module code generation '" + type + "' not supported. Using default 'commonjs' code generation"); + } + } + } + }); + var printedUsage = false; + opts.flag('help', { + usage: 'Print this message', + set: function () { + _this.printVersion(); + opts.printUsage(); + printedUsage = true; + } + }, 'h'); + opts.flag('useCaseSensitiveFileResolution', { + usage: 'Force file resolution to be case sensitive', + experimental: true, + set: function () { + _this.compilationSettings.useCaseSensitiveFileResolution = true; + } + }); + opts.flag('version', { + usage: 'Print the compiler\'s version: ' + this.compilerVersion, + set: function () { + _this.printVersion(); + } + }, 'v'); + opts.parse(this.ioHost.arguments); + if(this.compilationSettings.useDefaultLib) { + var compilerFilePath = this.ioHost.getExecutingFilePath(); + var binDirPath = this.ioHost.dirName(compilerFilePath); + var libStrPath = this.ioHost.resolvePath(binDirPath + "/lib.d.ts"); + code = new TypeScript.SourceUnit(libStrPath, null); + this.compilationEnvironment.code.push(code); + } + for(var i = 0; i < opts.unnamed.length; i++) { + code = new TypeScript.SourceUnit(opts.unnamed[i], null); + this.compilationEnvironment.code.push(code); + } + if(this.compilationEnvironment.code.length == (this.compilationSettings.useDefaultLib ? 1 : 0)) { + if(!printedUsage && !this.printedVersion) { + this.printVersion(); + opts.printUsage(); + this.ioHost.quit(1); + } + return; + } + var sourceFiles = []; + if(this.compilationSettings.watch) { + sourceFiles = this.compilationEnvironment.code.slice(0); + } + this.resolvedEnvironment = this.compilationSettings.resolve ? this.resolve() : this.compilationEnvironment; + var hasCompileErrors = this.compile(); + var hasErrors = hasCompileErrors || this.hasResolveErrors; + if(!hasErrors) { + if(this.compilationSettings.exec) { + this.run(); + } + } + if(this.compilationSettings.watch) { + this.watchFiles(sourceFiles); + } else { + this.ioHost.quit(hasErrors ? 1 : 0); + } + }; + BatchCompiler.prototype.printVersion = function () { + if(!this.printedVersion) { + this.ioHost.printLine("Version " + this.compilerVersion); + this.printedVersion = true; + } + }; + BatchCompiler.prototype.watchFiles = function (soruceFiles) { + var _this = this; + if(!this.ioHost.watchFile) { + this.ioHost.printLine("Error: Current host does not support -w[atch] option"); + return; + } + var resolvedFiles = []; + var watchers = { + }; + var addWatcher = function (filename) { + if(!watchers[filename]) { + var watcher = _this.ioHost.watchFile(filename, onWatchedFileChange); + watchers[filename] = watcher; + } else { + throw new Error("Cannot watch file, it is already watched."); + } + }; + var removeWatcher = function (filename) { + if(watchers[filename]) { + watchers[filename].close(); + delete watchers[filename]; + } else { + throw new Error("Cannot stop watching file, it is not being watched."); + } + }; + var onWatchedFileChange = function () { + _this.compilationEnvironment.code = soruceFiles; + _this.resolvedEnvironment = _this.compilationSettings.resolve ? _this.resolve() : _this.compilationEnvironment; + var oldFiles = resolvedFiles; + var newFiles = []; + _this.resolvedEnvironment.code.forEach(function (sf) { + return newFiles.push(sf.path); + }); + newFiles = newFiles.sort(); + var i = 0, j = 0; + while(i < oldFiles.length && j < newFiles.length) { + var compareResult = oldFiles[i].localeCompare(newFiles[j]); + if(compareResult == 0) { + i++; + j++; + } else { + if(compareResult < 0) { + removeWatcher(oldFiles[i]); + i++; + } else { + addWatcher(newFiles[j]); + j++; + } + } + } + for(var k = i; k < oldFiles.length; k++) { + removeWatcher(oldFiles[k]); + } + for(var k = j; k < newFiles.length; k++) { + addWatcher(newFiles[k]); + } + resolvedFiles = newFiles; + ; ; + _this.ioHost.printLine(""); + _this.ioHost.printLine("Recompiling (" + new Date() + "): "); + resolvedFiles.forEach(function (f) { + return _this.ioHost.printLine(" " + f); + }); + var hasCompileErrors = _this.compile(); + var hasErrors = hasCompileErrors || _this.hasResolveErrors; + if(!hasErrors) { + if(_this.compilationSettings.exec) { + _this.run(); + } + } + }; + this.ioHost.stderr = this.ioHost.stdout; + this.resolvedEnvironment.code.forEach(function (sf) { + resolvedFiles.push(sf.path); + addWatcher(sf.path); + }); + resolvedFiles.sort(); + }; + return BatchCompiler; +})(); +var batch = new BatchCompiler(IO); +batch.batchCompile(); diff --git a/_infrastructure/tests/typescript_0.8.2/typescript.js b/_infrastructure/tests/typescript_0.8.2/typescript.js new file mode 100644 index 0000000000..4a902f5b7b --- /dev/null +++ b/_infrastructure/tests/typescript_0.8.2/typescript.js @@ -0,0 +1,24654 @@ +/* ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + +var TypeScript; +(function (TypeScript) { + function hasFlag(val, flag) { + return (val & flag) != 0; + } + TypeScript.hasFlag = hasFlag; + (function (ErrorRecoverySet) { + ErrorRecoverySet._map = []; + ErrorRecoverySet.None = 0; + ErrorRecoverySet.Comma = 1; + ErrorRecoverySet.SColon = 1 << 1; + ErrorRecoverySet.Asg = 1 << 2; + ErrorRecoverySet.BinOp = 1 << 3; + ErrorRecoverySet.RBrack = 1 << 4; + ErrorRecoverySet.RCurly = 1 << 5; + ErrorRecoverySet.RParen = 1 << 6; + ErrorRecoverySet.Dot = 1 << 7; + ErrorRecoverySet.Colon = 1 << 8; + ErrorRecoverySet.PrimType = 1 << 9; + ErrorRecoverySet.AddOp = 1 << 10; + ErrorRecoverySet.LCurly = 1 << 11; + ErrorRecoverySet.PreOp = 1 << 12; + ErrorRecoverySet.RegExp = 1 << 13; + ErrorRecoverySet.LParen = 1 << 14; + ErrorRecoverySet.LBrack = 1 << 15; + ErrorRecoverySet.Scope = 1 << 16; + ErrorRecoverySet.In = 1 << 17; + ErrorRecoverySet.SCase = 1 << 18; + ErrorRecoverySet.Else = 1 << 19; + ErrorRecoverySet.Catch = 1 << 20; + ErrorRecoverySet.Var = 1 << 21; + ErrorRecoverySet.Stmt = 1 << 22; + ErrorRecoverySet.While = 1 << 23; + ErrorRecoverySet.ID = 1 << 24; + ErrorRecoverySet.Prefix = 1 << 25; + ErrorRecoverySet.Literal = 1 << 26; + ErrorRecoverySet.RLit = 1 << 27; + ErrorRecoverySet.Func = 1 << 28; + ErrorRecoverySet.EOF = 1 << 29; + ErrorRecoverySet.TypeScriptS = 1 << 30; + ErrorRecoverySet.ExprStart = ErrorRecoverySet.SColon | ErrorRecoverySet.AddOp | ErrorRecoverySet.LCurly | ErrorRecoverySet.PreOp | ErrorRecoverySet.RegExp | ErrorRecoverySet.LParen | ErrorRecoverySet.LBrack | ErrorRecoverySet.ID | ErrorRecoverySet.Prefix | ErrorRecoverySet.RLit | ErrorRecoverySet.Func | ErrorRecoverySet.Literal; + ErrorRecoverySet.StmtStart = ErrorRecoverySet.ExprStart | ErrorRecoverySet.SColon | ErrorRecoverySet.Var | ErrorRecoverySet.Stmt | ErrorRecoverySet.While | ErrorRecoverySet.TypeScriptS; + ErrorRecoverySet.Postfix = ErrorRecoverySet.Dot | ErrorRecoverySet.LParen | ErrorRecoverySet.LBrack; + })(TypeScript.ErrorRecoverySet || (TypeScript.ErrorRecoverySet = {})); + var ErrorRecoverySet = TypeScript.ErrorRecoverySet; + (function (AllowedElements) { + AllowedElements._map = []; + AllowedElements.None = 0; + AllowedElements.ModuleDeclarations = 1 << 2; + AllowedElements.ClassDeclarations = 1 << 3; + AllowedElements.InterfaceDeclarations = 1 << 4; + AllowedElements.AmbientDeclarations = 1 << 10; + AllowedElements.Properties = 1 << 11; + AllowedElements.Global = AllowedElements.ModuleDeclarations | AllowedElements.ClassDeclarations | AllowedElements.InterfaceDeclarations | AllowedElements.AmbientDeclarations; + AllowedElements.QuickParse = AllowedElements.Global | AllowedElements.Properties; + })(TypeScript.AllowedElements || (TypeScript.AllowedElements = {})); + var AllowedElements = TypeScript.AllowedElements; + (function (Modifiers) { + Modifiers._map = []; + Modifiers.None = 0; + Modifiers.Private = 1; + Modifiers.Public = 1 << 1; + Modifiers.Readonly = 1 << 2; + Modifiers.Ambient = 1 << 3; + Modifiers.Exported = 1 << 4; + Modifiers.Getter = 1 << 5; + Modifiers.Setter = 1 << 6; + Modifiers.Static = 1 << 7; + })(TypeScript.Modifiers || (TypeScript.Modifiers = {})); + var Modifiers = TypeScript.Modifiers; + (function (ASTFlags) { + ASTFlags._map = []; + ASTFlags.None = 0; + ASTFlags.ExplicitSemicolon = 1; + ASTFlags.AutomaticSemicolon = 1 << 1; + ASTFlags.Writeable = 1 << 2; + ASTFlags.Error = 1 << 3; + ASTFlags.DotLHSPartial = 1 << 4; + ASTFlags.DotLHS = 1 << 5; + ASTFlags.IsStatement = 1 << 6; + ASTFlags.StrictMode = 1 << 7; + ASTFlags.PossibleOptionalParameter = 1 << 8; + ASTFlags.ClassBaseConstructorCall = 1 << 9; + ASTFlags.OptionalName = 1 << 10; + ASTFlags.SkipNextRParen = 1 << 11; + })(TypeScript.ASTFlags || (TypeScript.ASTFlags = {})); + var ASTFlags = TypeScript.ASTFlags; + (function (DeclFlags) { + DeclFlags._map = []; + DeclFlags.None = 0; + DeclFlags.Exported = 1; + DeclFlags.Private = 1 << 1; + DeclFlags.Public = 1 << 2; + DeclFlags.Ambient = 1 << 3; + DeclFlags.Static = 1 << 4; + DeclFlags.LocalStatic = 1 << 5; + DeclFlags.GetAccessor = 1 << 6; + DeclFlags.SetAccessor = 1 << 7; + })(TypeScript.DeclFlags || (TypeScript.DeclFlags = {})); + var DeclFlags = TypeScript.DeclFlags; + (function (ModuleFlags) { + ModuleFlags._map = []; + ModuleFlags.None = 0; + ModuleFlags.Exported = 1; + ModuleFlags.Private = 1 << 1; + ModuleFlags.Public = 1 << 2; + ModuleFlags.Ambient = 1 << 3; + ModuleFlags.Static = 1 << 4; + ModuleFlags.LocalStatic = 1 << 5; + ModuleFlags.GetAccessor = 1 << 6; + ModuleFlags.SetAccessor = 1 << 7; + ModuleFlags.IsEnum = 1 << 8; + ModuleFlags.ShouldEmitModuleDecl = 1 << 9; + ModuleFlags.IsWholeFile = 1 << 10; + ModuleFlags.IsDynamic = 1 << 11; + ModuleFlags.MustCaptureThis = 1 << 12; + })(TypeScript.ModuleFlags || (TypeScript.ModuleFlags = {})); + var ModuleFlags = TypeScript.ModuleFlags; + (function (SymbolFlags) { + SymbolFlags._map = []; + SymbolFlags.None = 0; + SymbolFlags.Exported = 1; + SymbolFlags.Private = 1 << 1; + SymbolFlags.Public = 1 << 2; + SymbolFlags.Ambient = 1 << 3; + SymbolFlags.Static = 1 << 4; + SymbolFlags.LocalStatic = 1 << 5; + SymbolFlags.GetAccessor = 1 << 6; + SymbolFlags.SetAccessor = 1 << 7; + SymbolFlags.Property = 1 << 8; + SymbolFlags.Readonly = 1 << 9; + SymbolFlags.ModuleMember = 1 << 10; + SymbolFlags.InterfaceMember = 1 << 11; + SymbolFlags.ClassMember = 1 << 12; + SymbolFlags.BuiltIn = 1 << 13; + SymbolFlags.TypeSetDuringScopeAssignment = 1 << 14; + SymbolFlags.Constant = 1 << 15; + SymbolFlags.Optional = 1 << 16; + SymbolFlags.RecursivelyReferenced = 1 << 17; + SymbolFlags.Bound = 1 << 18; + SymbolFlags.CompilerGenerated = 1 << 19; + })(TypeScript.SymbolFlags || (TypeScript.SymbolFlags = {})); + var SymbolFlags = TypeScript.SymbolFlags; + (function (VarFlags) { + VarFlags._map = []; + VarFlags.None = 0; + VarFlags.Exported = 1; + VarFlags.Private = 1 << 1; + VarFlags.Public = 1 << 2; + VarFlags.Ambient = 1 << 3; + VarFlags.Static = 1 << 4; + VarFlags.LocalStatic = 1 << 5; + VarFlags.GetAccessor = 1 << 6; + VarFlags.SetAccessor = 1 << 7; + VarFlags.AutoInit = 1 << 8; + VarFlags.Property = 1 << 9; + VarFlags.Readonly = 1 << 10; + VarFlags.Class = 1 << 11; + VarFlags.ClassProperty = 1 << 12; + VarFlags.ClassBodyProperty = 1 << 13; + VarFlags.ClassConstructorProperty = 1 << 14; + VarFlags.ClassSuperMustBeFirstCallInConstructor = 1 << 15; + VarFlags.Constant = 1 << 16; + VarFlags.MustCaptureThis = 1 << 17; + })(TypeScript.VarFlags || (TypeScript.VarFlags = {})); + var VarFlags = TypeScript.VarFlags; + (function (FncFlags) { + FncFlags._map = []; + FncFlags.None = 0; + FncFlags.Exported = 1; + FncFlags.Private = 1 << 1; + FncFlags.Public = 1 << 2; + FncFlags.Ambient = 1 << 3; + FncFlags.Static = 1 << 4; + FncFlags.LocalStatic = 1 << 5; + FncFlags.GetAccessor = 1 << 6; + FncFlags.SetAccessor = 1 << 7; + FncFlags.Definition = 1 << 8; + FncFlags.Signature = 1 << 9; + FncFlags.Method = 1 << 10; + FncFlags.HasReturnExpression = 1 << 11; + FncFlags.CallMember = 1 << 12; + FncFlags.ConstructMember = 1 << 13; + FncFlags.HasSelfReference = 1 << 14; + FncFlags.IsFatArrowFunction = 1 << 15; + FncFlags.IndexerMember = 1 << 16; + FncFlags.IsFunctionExpression = 1 << 17; + FncFlags.ClassMethod = 1 << 18; + FncFlags.ClassPropertyMethodExported = 1 << 19; + FncFlags.HasSuperReferenceInFatArrowFunction = 1 << 20; + FncFlags.IsPropertyBound = 1 << 21; + })(TypeScript.FncFlags || (TypeScript.FncFlags = {})); + var FncFlags = TypeScript.FncFlags; + (function (SignatureFlags) { + SignatureFlags._map = []; + SignatureFlags.None = 0; + SignatureFlags.IsIndexer = 1; + SignatureFlags.IsStringIndexer = 1 << 1; + SignatureFlags.IsNumberIndexer = 1 << 2; + })(TypeScript.SignatureFlags || (TypeScript.SignatureFlags = {})); + var SignatureFlags = TypeScript.SignatureFlags; + function ToDeclFlags(fncOrVarOrSymbolOrModuleFlags) { + return fncOrVarOrSymbolOrModuleFlags; + } + TypeScript.ToDeclFlags = ToDeclFlags; + (function (TypeFlags) { + TypeFlags._map = []; + TypeFlags.None = 0; + TypeFlags.HasImplementation = 1; + TypeFlags.HasSelfReference = 1 << 1; + TypeFlags.MergeResult = 1 << 2; + TypeFlags.IsEnum = 1 << 3; + TypeFlags.BuildingName = 1 << 4; + TypeFlags.HasBaseType = 1 << 5; + TypeFlags.HasBaseTypeOfObject = 1 << 6; + TypeFlags.IsClass = 1 << 7; + })(TypeScript.TypeFlags || (TypeScript.TypeFlags = {})); + var TypeFlags = TypeScript.TypeFlags; + (function (TypeRelationshipFlags) { + TypeRelationshipFlags._map = []; + TypeRelationshipFlags.SuccessfulComparison = 0; + TypeRelationshipFlags.SourceIsNullTargetIsVoidOrUndefined = 1; + TypeRelationshipFlags.RequiredPropertyIsMissing = 1 << 1; + TypeRelationshipFlags.IncompatibleSignatures = 1 << 2; + TypeRelationshipFlags.SourceSignatureHasTooManyParameters = 3; + TypeRelationshipFlags.IncompatibleReturnTypes = 1 << 4; + TypeRelationshipFlags.IncompatiblePropertyTypes = 1 << 5; + TypeRelationshipFlags.IncompatibleParameterTypes = 1 << 6; + })(TypeScript.TypeRelationshipFlags || (TypeScript.TypeRelationshipFlags = {})); + var TypeRelationshipFlags = TypeScript.TypeRelationshipFlags; + (function (CodeGenTarget) { + CodeGenTarget._map = []; + CodeGenTarget.ES3 = 0; + CodeGenTarget.ES5 = 1; + })(TypeScript.CodeGenTarget || (TypeScript.CodeGenTarget = {})); + var CodeGenTarget = TypeScript.CodeGenTarget; + (function (ModuleGenTarget) { + ModuleGenTarget._map = []; + ModuleGenTarget.Synchronous = 0; + ModuleGenTarget.Asynchronous = 1; + ModuleGenTarget.Local = 1 << 1; + })(TypeScript.ModuleGenTarget || (TypeScript.ModuleGenTarget = {})); + var ModuleGenTarget = TypeScript.ModuleGenTarget; + TypeScript.codeGenTarget = CodeGenTarget.ES3; + TypeScript.moduleGenTarget = ModuleGenTarget.Synchronous; + TypeScript.optimizeModuleCodeGen = true; + function flagsToString(e, flags) { + var builder = ""; + for(var i = 1; i < (1 << 31); i = i << 1) { + if((flags & i) != 0) { + for(var k in e) { + if(e[k] == i) { + if(builder.length > 0) { + builder += "|"; + } + builder += k; + break; + } + } + } + } + return builder; + } + TypeScript.flagsToString = flagsToString; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (NodeType) { + NodeType._map = []; + NodeType._map[0] = "None"; + NodeType.None = 0; + NodeType._map[1] = "Empty"; + NodeType.Empty = 1; + NodeType._map[2] = "EmptyExpr"; + NodeType.EmptyExpr = 2; + NodeType._map[3] = "True"; + NodeType.True = 3; + NodeType._map[4] = "False"; + NodeType.False = 4; + NodeType._map[5] = "This"; + NodeType.This = 5; + NodeType._map[6] = "Super"; + NodeType.Super = 6; + NodeType._map[7] = "QString"; + NodeType.QString = 7; + NodeType._map[8] = "Regex"; + NodeType.Regex = 8; + NodeType._map[9] = "Null"; + NodeType.Null = 9; + NodeType._map[10] = "ArrayLit"; + NodeType.ArrayLit = 10; + NodeType._map[11] = "ObjectLit"; + NodeType.ObjectLit = 11; + NodeType._map[12] = "Void"; + NodeType.Void = 12; + NodeType._map[13] = "Comma"; + NodeType.Comma = 13; + NodeType._map[14] = "Pos"; + NodeType.Pos = 14; + NodeType._map[15] = "Neg"; + NodeType.Neg = 15; + NodeType._map[16] = "Delete"; + NodeType.Delete = 16; + NodeType._map[17] = "Await"; + NodeType.Await = 17; + NodeType._map[18] = "In"; + NodeType.In = 18; + NodeType._map[19] = "Dot"; + NodeType.Dot = 19; + NodeType._map[20] = "From"; + NodeType.From = 20; + NodeType._map[21] = "Is"; + NodeType.Is = 21; + NodeType._map[22] = "InstOf"; + NodeType.InstOf = 22; + NodeType._map[23] = "Typeof"; + NodeType.Typeof = 23; + NodeType._map[24] = "NumberLit"; + NodeType.NumberLit = 24; + NodeType._map[25] = "Name"; + NodeType.Name = 25; + NodeType._map[26] = "TypeRef"; + NodeType.TypeRef = 26; + NodeType._map[27] = "Index"; + NodeType.Index = 27; + NodeType._map[28] = "Call"; + NodeType.Call = 28; + NodeType._map[29] = "New"; + NodeType.New = 29; + NodeType._map[30] = "Asg"; + NodeType.Asg = 30; + NodeType._map[31] = "AsgAdd"; + NodeType.AsgAdd = 31; + NodeType._map[32] = "AsgSub"; + NodeType.AsgSub = 32; + NodeType._map[33] = "AsgDiv"; + NodeType.AsgDiv = 33; + NodeType._map[34] = "AsgMul"; + NodeType.AsgMul = 34; + NodeType._map[35] = "AsgMod"; + NodeType.AsgMod = 35; + NodeType._map[36] = "AsgAnd"; + NodeType.AsgAnd = 36; + NodeType._map[37] = "AsgXor"; + NodeType.AsgXor = 37; + NodeType._map[38] = "AsgOr"; + NodeType.AsgOr = 38; + NodeType._map[39] = "AsgLsh"; + NodeType.AsgLsh = 39; + NodeType._map[40] = "AsgRsh"; + NodeType.AsgRsh = 40; + NodeType._map[41] = "AsgRs2"; + NodeType.AsgRs2 = 41; + NodeType._map[42] = "ConditionalExpression"; + NodeType.ConditionalExpression = 42; + NodeType._map[43] = "LogOr"; + NodeType.LogOr = 43; + NodeType._map[44] = "LogAnd"; + NodeType.LogAnd = 44; + NodeType._map[45] = "Or"; + NodeType.Or = 45; + NodeType._map[46] = "Xor"; + NodeType.Xor = 46; + NodeType._map[47] = "And"; + NodeType.And = 47; + NodeType._map[48] = "Eq"; + NodeType.Eq = 48; + NodeType._map[49] = "Ne"; + NodeType.Ne = 49; + NodeType._map[50] = "Eqv"; + NodeType.Eqv = 50; + NodeType._map[51] = "NEqv"; + NodeType.NEqv = 51; + NodeType._map[52] = "Lt"; + NodeType.Lt = 52; + NodeType._map[53] = "Le"; + NodeType.Le = 53; + NodeType._map[54] = "Gt"; + NodeType.Gt = 54; + NodeType._map[55] = "Ge"; + NodeType.Ge = 55; + NodeType._map[56] = "Add"; + NodeType.Add = 56; + NodeType._map[57] = "Sub"; + NodeType.Sub = 57; + NodeType._map[58] = "Mul"; + NodeType.Mul = 58; + NodeType._map[59] = "Div"; + NodeType.Div = 59; + NodeType._map[60] = "Mod"; + NodeType.Mod = 60; + NodeType._map[61] = "Lsh"; + NodeType.Lsh = 61; + NodeType._map[62] = "Rsh"; + NodeType.Rsh = 62; + NodeType._map[63] = "Rs2"; + NodeType.Rs2 = 63; + NodeType._map[64] = "Not"; + NodeType.Not = 64; + NodeType._map[65] = "LogNot"; + NodeType.LogNot = 65; + NodeType._map[66] = "IncPre"; + NodeType.IncPre = 66; + NodeType._map[67] = "DecPre"; + NodeType.DecPre = 67; + NodeType._map[68] = "IncPost"; + NodeType.IncPost = 68; + NodeType._map[69] = "DecPost"; + NodeType.DecPost = 69; + NodeType._map[70] = "TypeAssertion"; + NodeType.TypeAssertion = 70; + NodeType._map[71] = "FuncDecl"; + NodeType.FuncDecl = 71; + NodeType._map[72] = "Member"; + NodeType.Member = 72; + NodeType._map[73] = "VarDecl"; + NodeType.VarDecl = 73; + NodeType._map[74] = "ArgDecl"; + NodeType.ArgDecl = 74; + NodeType._map[75] = "Return"; + NodeType.Return = 75; + NodeType._map[76] = "Break"; + NodeType.Break = 76; + NodeType._map[77] = "Continue"; + NodeType.Continue = 77; + NodeType._map[78] = "Throw"; + NodeType.Throw = 78; + NodeType._map[79] = "For"; + NodeType.For = 79; + NodeType._map[80] = "ForIn"; + NodeType.ForIn = 80; + NodeType._map[81] = "If"; + NodeType.If = 81; + NodeType._map[82] = "While"; + NodeType.While = 82; + NodeType._map[83] = "DoWhile"; + NodeType.DoWhile = 83; + NodeType._map[84] = "Block"; + NodeType.Block = 84; + NodeType._map[85] = "Case"; + NodeType.Case = 85; + NodeType._map[86] = "Switch"; + NodeType.Switch = 86; + NodeType._map[87] = "Try"; + NodeType.Try = 87; + NodeType._map[88] = "TryCatch"; + NodeType.TryCatch = 88; + NodeType._map[89] = "TryFinally"; + NodeType.TryFinally = 89; + NodeType._map[90] = "Finally"; + NodeType.Finally = 90; + NodeType._map[91] = "Catch"; + NodeType.Catch = 91; + NodeType._map[92] = "List"; + NodeType.List = 92; + NodeType._map[93] = "Script"; + NodeType.Script = 93; + NodeType._map[94] = "ClassDeclaration"; + NodeType.ClassDeclaration = 94; + NodeType._map[95] = "InterfaceDeclaration"; + NodeType.InterfaceDeclaration = 95; + NodeType._map[96] = "ModuleDeclaration"; + NodeType.ModuleDeclaration = 96; + NodeType._map[97] = "ImportDeclaration"; + NodeType.ImportDeclaration = 97; + NodeType._map[98] = "With"; + NodeType.With = 98; + NodeType._map[99] = "Label"; + NodeType.Label = 99; + NodeType._map[100] = "LabeledStatement"; + NodeType.LabeledStatement = 100; + NodeType._map[101] = "EBStart"; + NodeType.EBStart = 101; + NodeType._map[102] = "GotoEB"; + NodeType.GotoEB = 102; + NodeType._map[103] = "EndCode"; + NodeType.EndCode = 103; + NodeType._map[104] = "Error"; + NodeType.Error = 104; + NodeType._map[105] = "Comment"; + NodeType.Comment = 105; + NodeType._map[106] = "Debugger"; + NodeType.Debugger = 106; + NodeType.GeneralNode = NodeType.FuncDecl; + NodeType.LastAsg = NodeType.AsgRs2; + })(TypeScript.NodeType || (TypeScript.NodeType = {})); + var NodeType = TypeScript.NodeType; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var BlockIntrinsics = (function () { + function BlockIntrinsics() { + this.prototype = undefined; + this.toString = undefined; + this.toLocaleString = undefined; + this.valueOf = undefined; + this.hasOwnProperty = undefined; + this.propertyIsEnumerable = undefined; + this.isPrototypeOf = undefined; + this["constructor"] = undefined; + } + return BlockIntrinsics; + })(); + TypeScript.BlockIntrinsics = BlockIntrinsics; + var StringHashTable = (function () { + function StringHashTable() { + this.itemCount = 0; + this.table = (new BlockIntrinsics()); + } + StringHashTable.prototype.getAllKeys = function () { + var result = []; + for(var k in this.table) { + if(this.table[k] != undefined) { + result[result.length] = k; + } + } + return result; + }; + StringHashTable.prototype.add = function (key, data) { + if(this.table[key] != undefined) { + return false; + } + this.table[key] = data; + this.itemCount++; + return true; + }; + StringHashTable.prototype.addOrUpdate = function (key, data) { + if(this.table[key] != undefined) { + this.table[key] = data; + return false; + } + this.table[key] = data; + this.itemCount++; + return true; + }; + StringHashTable.prototype.map = function (fn, context) { + for(var k in this.table) { + var data = this.table[k]; + if(data != undefined) { + fn(k, this.table[k], context); + } + } + }; + StringHashTable.prototype.every = function (fn, context) { + for(var k in this.table) { + var data = this.table[k]; + if(data != undefined) { + if(!fn(k, this.table[k], context)) { + return false; + } + } + } + return true; + }; + StringHashTable.prototype.some = function (fn, context) { + for(var k in this.table) { + var data = this.table[k]; + if(data != undefined) { + if(fn(k, this.table[k], context)) { + return true; + } + } + } + return false; + }; + StringHashTable.prototype.count = function () { + return this.itemCount; + }; + StringHashTable.prototype.lookup = function (key) { + var data = this.table[key]; + if(data != undefined) { + return data; + } else { + return (null); + } + }; + return StringHashTable; + })(); + TypeScript.StringHashTable = StringHashTable; + var DualStringHashTable = (function () { + function DualStringHashTable(primaryTable, secondaryTable) { + this.primaryTable = primaryTable; + this.secondaryTable = secondaryTable; + this.insertPrimary = true; + } + DualStringHashTable.prototype.getAllKeys = function () { + return this.primaryTable.getAllKeys().concat(this.secondaryTable.getAllKeys()); + }; + DualStringHashTable.prototype.add = function (key, data) { + if(this.insertPrimary) { + return this.primaryTable.add(key, data); + } else { + return this.secondaryTable.add(key, data); + } + }; + DualStringHashTable.prototype.addOrUpdate = function (key, data) { + if(this.insertPrimary) { + return this.primaryTable.addOrUpdate(key, data); + } else { + return this.secondaryTable.addOrUpdate(key, data); + } + }; + DualStringHashTable.prototype.map = function (fn, context) { + this.primaryTable.map(fn, context); + this.secondaryTable.map(fn, context); + }; + DualStringHashTable.prototype.every = function (fn, context) { + return this.primaryTable.every(fn, context) && this.secondaryTable.every(fn, context); + }; + DualStringHashTable.prototype.some = function (fn, context) { + return this.primaryTable.some(fn, context) || this.secondaryTable.some(fn, context); + }; + DualStringHashTable.prototype.count = function () { + return this.primaryTable.count() + this.secondaryTable.count(); + }; + DualStringHashTable.prototype.lookup = function (key) { + var data = this.primaryTable.lookup(key); + if(data != undefined) { + return data; + } else { + return this.secondaryTable.lookup(key); + } + }; + return DualStringHashTable; + })(); + TypeScript.DualStringHashTable = DualStringHashTable; + function numberHashFn(key) { + var c2 = 668265261; + key = (key ^ 61) ^ (key >>> 16); + key = key + (key << 3); + key = key ^ (key >>> 4); + key = key * c2; + key = key ^ (key >>> 15); + return key; + } + TypeScript.numberHashFn = numberHashFn; + function combineHashes(key1, key2) { + return key2 ^ ((key1 >> 5) + key1); + } + TypeScript.combineHashes = combineHashes; + var HashEntry = (function () { + function HashEntry(key, data) { + this.key = key; + this.data = data; + } + return HashEntry; + })(); + TypeScript.HashEntry = HashEntry; + var HashTable = (function () { + function HashTable(size, hashFn, equalsFn) { + this.size = size; + this.hashFn = hashFn; + this.equalsFn = equalsFn; + this.itemCount = 0; + this.table = new Array(); + for(var i = 0; i < this.size; i++) { + this.table[i] = null; + } + } + HashTable.prototype.add = function (key, data) { + var current; + var entry = new HashEntry(key, data); + var val = this.hashFn(key); + val = val % this.size; + for(current = this.table[val]; current != null; current = current.next) { + if(this.equalsFn(key, current.key)) { + return false; + } + } + entry.next = this.table[val]; + this.table[val] = entry; + this.itemCount++; + return true; + }; + HashTable.prototype.remove = function (key) { + var current; + var val = this.hashFn(key); + val = val % this.size; + var result = null; + var prevEntry = null; + for(current = this.table[val]; current != null; current = current.next) { + if(this.equalsFn(key, current.key)) { + result = current.data; + this.itemCount--; + if(prevEntry) { + prevEntry.next = current.next; + } else { + this.table[val] = current.next; + } + break; + } + prevEntry = current; + } + return result; + }; + HashTable.prototype.count = function () { + return this.itemCount; + }; + HashTable.prototype.lookup = function (key) { + var current; + var val = this.hashFn(key); + val = val % this.size; + for(current = this.table[val]; current != null; current = current.next) { + if(this.equalsFn(key, current.key)) { + return (current.data); + } + } + return (null); + }; + return HashTable; + })(); + TypeScript.HashTable = HashTable; + var SimpleHashTable = (function () { + function SimpleHashTable() { + this.keys = []; + this.values = []; + } + SimpleHashTable.prototype.lookup = function (key, findValue) { + var searchArray = this.keys; + if(findValue) { + searchArray = this.values; + } + for(var i = 0; i < searchArray.length; i++) { + if(searchArray[i] == key) { + return { + key: this.keys[i], + data: this.values[i] + }; + } + } + return null; + }; + SimpleHashTable.prototype.add = function (key, data) { + var lookupData = this.lookup(key); + if(lookupData) { + return false; + } + this.keys[this.keys.length] = key; + this.values[this.values.length] = data; + return true; + }; + return SimpleHashTable; + })(); + TypeScript.SimpleHashTable = SimpleHashTable; +})(TypeScript || (TypeScript = {})); +var __extends = this.__extends || function (d, b) { + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var TypeScript; +(function (TypeScript) { + var ASTSpan = (function () { + function ASTSpan() { + this.minChar = -1; + this.limChar = -1; + } + return ASTSpan; + })(); + TypeScript.ASTSpan = ASTSpan; + var AST = (function (_super) { + __extends(AST, _super); + function AST(nodeType) { + _super.call(this); + this.nodeType = nodeType; + this.type = null; + this.flags = TypeScript.ASTFlags.Writeable; + this.passCreated = TypeScript.CompilerDiagnostics.analysisPass; + this.preComments = null; + this.postComments = null; + this.docComments = null; + this.isParenthesized = false; + } + AST.prototype.isExpression = function () { + return false; + }; + AST.prototype.isStatementOrExpression = function () { + return false; + }; + AST.prototype.isCompoundStatement = function () { + return false; + }; + AST.prototype.isLeaf = function () { + return this.isStatementOrExpression() && (!this.isCompoundStatement()); + }; + AST.prototype.isDeclaration = function () { + return false; + }; + AST.prototype.typeCheck = function (typeFlow) { + switch(this.nodeType) { + case TypeScript.NodeType.Error: + case TypeScript.NodeType.EmptyExpr: { + this.type = typeFlow.anyType; + break; + + } + case TypeScript.NodeType.This: { + return typeFlow.typeCheckThis(this); + + } + case TypeScript.NodeType.Null: { + this.type = typeFlow.nullType; + break; + + } + case TypeScript.NodeType.False: + case TypeScript.NodeType.True: { + this.type = typeFlow.booleanType; + break; + + } + case TypeScript.NodeType.Super: { + return typeFlow.typeCheckSuper(this); + + } + case TypeScript.NodeType.EndCode: + case TypeScript.NodeType.Empty: + case TypeScript.NodeType.Void: { + this.type = typeFlow.voidType; + break; + + } + default: { + throw new Error("please implement in derived class"); + + } + } + return this; + }; + AST.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + switch(this.nodeType) { + case TypeScript.NodeType.This: { + emitter.recordSourceMappingStart(this); + if(emitter.thisFnc && (TypeScript.hasFlag(emitter.thisFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction))) { + emitter.writeToOutput("_this"); + } else { + emitter.writeToOutput("this"); + } + emitter.recordSourceMappingEnd(this); + break; + + } + case TypeScript.NodeType.Null: { + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("null"); + emitter.recordSourceMappingEnd(this); + break; + + } + case TypeScript.NodeType.False: { + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("false"); + emitter.recordSourceMappingEnd(this); + break; + + } + case TypeScript.NodeType.True: { + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("true"); + emitter.recordSourceMappingEnd(this); + break; + + } + case TypeScript.NodeType.Super: { + emitter.recordSourceMappingStart(this); + emitter.emitSuperReference(); + emitter.recordSourceMappingEnd(this); + break; + + } + case TypeScript.NodeType.EndCode: + case TypeScript.NodeType.Error: + case TypeScript.NodeType.EmptyExpr: { + break; + + } + case TypeScript.NodeType.Empty: { + emitter.recordSourceMappingStart(this); + emitter.recordSourceMappingEnd(this); + break; + + } + case TypeScript.NodeType.Void: { + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("void "); + emitter.recordSourceMappingEnd(this); + break; + + } + default: { + throw new Error("please implement in derived class"); + + } + } + emitter.emitParensAndCommentsInPlace(this, false); + }; + AST.prototype.print = function (context) { + context.startLine(); + var lineCol = { + line: -1, + col: -1 + }; + var limLineCol = { + line: -1, + col: -1 + }; + if(context.parser !== null) { + context.parser.getSourceLineCol(lineCol, this.minChar); + context.parser.getSourceLineCol(limLineCol, this.limChar); + context.write("(" + lineCol.line + "," + lineCol.col + ")--" + "(" + limLineCol.line + "," + limLineCol.col + "): "); + } + var lab = this.printLabel(); + if(TypeScript.hasFlag(this.flags, TypeScript.ASTFlags.Error)) { + lab += " (Error)"; + } + context.writeLine(lab); + }; + AST.prototype.printLabel = function () { + if(TypeScript.nodeTypeTable[this.nodeType] !== undefined) { + return TypeScript.nodeTypeTable[this.nodeType]; + } else { + return (TypeScript.NodeType)._map[this.nodeType]; + } + }; + AST.prototype.addToControlFlow = function (context) { + context.walker.options.goChildren = false; + context.addContent(this); + }; + AST.prototype.netFreeUses = function (container, freeUses) { + }; + AST.prototype.treeViewLabel = function () { + return (TypeScript.NodeType)._map[this.nodeType]; + }; + AST.getResolvedIdentifierName = function getResolvedIdentifierName(name) { + if(!name) { + return ""; + } + var resolved = ""; + var start = 0; + var i = 0; + while(i <= name.length - 6) { + if(name.charAt(i) == '\\' && name.charAt(i + 1) == 'u') { + var charCode = parseInt(name.substr(i + 2, 4), 16); + resolved += name.substr(start, i - start); + resolved += String.fromCharCode(charCode); + i += 6; + start = i; + continue; + } + i++; + } + resolved += name.substring(start); + return resolved; + } + AST.prototype.getDocComments = function () { + if(!this.isDeclaration() || !this.preComments || this.preComments.length == 0) { + return []; + } + if(!this.docComments) { + var preCommentsLength = this.preComments.length; + var docComments = []; + for(var i = preCommentsLength - 1; i >= 0; i--) { + if(this.preComments[i].isDocComment()) { + var prevDocComment = docComments.length > 0 ? docComments[docComments.length - 1] : null; + if(prevDocComment == null || (this.preComments[i].limLine == prevDocComment.minLine || this.preComments[i].limLine + 1 == prevDocComment.minLine)) { + docComments.push(this.preComments[i]); + continue; + } + } + break; + } + this.docComments = docComments.reverse(); + } + return this.docComments; + }; + return AST; + })(ASTSpan); + TypeScript.AST = AST; + var IncompleteAST = (function (_super) { + __extends(IncompleteAST, _super); + function IncompleteAST(min, lim) { + _super.call(this, TypeScript.NodeType.Error); + this.minChar = min; + this.limChar = lim; + } + return IncompleteAST; + })(AST); + TypeScript.IncompleteAST = IncompleteAST; + var ASTList = (function (_super) { + __extends(ASTList, _super); + function ASTList() { + _super.call(this, TypeScript.NodeType.List); + this.enclosingScope = null; + this.members = new Array(); + } + ASTList.prototype.addToControlFlow = function (context) { + var len = this.members.length; + for(var i = 0; i < len; i++) { + if(context.noContinuation) { + context.addUnreachable(this.members[i]); + break; + } else { + this.members[i] = context.walk(this.members[i], this); + } + } + context.walker.options.goChildren = false; + }; + ASTList.prototype.append = function (ast) { + this.members[this.members.length] = ast; + return this; + }; + ASTList.prototype.appendAll = function (ast) { + if(ast.nodeType == TypeScript.NodeType.List) { + var list = ast; + for(var i = 0, len = list.members.length; i < len; i++) { + this.append(list.members[i]); + } + } else { + this.append(ast); + } + return this; + }; + ASTList.prototype.emit = function (emitter, tokenId, startLine) { + emitter.recordSourceMappingStart(this); + emitter.emitJavascriptList(this, null, TypeScript.TokenID.Semicolon, startLine, false, false); + emitter.recordSourceMappingEnd(this); + }; + ASTList.prototype.typeCheck = function (typeFlow) { + var len = this.members.length; + typeFlow.nestingLevel++; + for(var i = 0; i < len; i++) { + if(this.members[i]) { + this.members[i] = this.members[i].typeCheck(typeFlow); + } + } + typeFlow.nestingLevel--; + return this; + }; + return ASTList; + })(AST); + TypeScript.ASTList = ASTList; + var Identifier = (function (_super) { + __extends(Identifier, _super); + function Identifier(actualText, hasEscapeSequence) { + _super.call(this, TypeScript.NodeType.Name); + this.actualText = actualText; + this.hasEscapeSequence = hasEscapeSequence; + this.sym = null; + this.cloId = -1; + this.setText(actualText, hasEscapeSequence); + } + Identifier.prototype.setText = function (actualText, hasEscapeSequence) { + this.actualText = actualText; + if(hasEscapeSequence) { + this.text = AST.getResolvedIdentifierName(actualText); + } else { + this.text = actualText; + } + }; + Identifier.prototype.isMissing = function () { + return false; + }; + Identifier.prototype.isLeaf = function () { + return true; + }; + Identifier.prototype.treeViewLabel = function () { + return "id: " + this.actualText; + }; + Identifier.prototype.printLabel = function () { + if(this.actualText) { + return "id: " + this.actualText; + } else { + return "name node"; + } + }; + Identifier.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckName(this); + }; + Identifier.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitJavascriptName(this, true); + }; + Identifier.fromToken = function fromToken(token) { + return new Identifier(token.getText(), (token).hasEscapeSequence); + } + return Identifier; + })(AST); + TypeScript.Identifier = Identifier; + var MissingIdentifier = (function (_super) { + __extends(MissingIdentifier, _super); + function MissingIdentifier() { + _super.call(this, "__missing"); + } + MissingIdentifier.prototype.isMissing = function () { + return true; + }; + MissingIdentifier.prototype.emit = function (emitter, tokenId, startLine) { + }; + return MissingIdentifier; + })(Identifier); + TypeScript.MissingIdentifier = MissingIdentifier; + var Label = (function (_super) { + __extends(Label, _super); + function Label(id) { + _super.call(this, TypeScript.NodeType.Label); + this.id = id; + } + Label.prototype.printLabel = function () { + return this.id.actualText + ":"; + }; + Label.prototype.typeCheck = function (typeFlow) { + this.type = typeFlow.voidType; + return this; + }; + Label.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.recordSourceMappingStart(this.id); + emitter.writeToOutput(this.id.actualText); + emitter.recordSourceMappingEnd(this.id); + emitter.writeLineToOutput(":"); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return Label; + })(AST); + TypeScript.Label = Label; + var Expression = (function (_super) { + __extends(Expression, _super); + function Expression(nodeType) { + _super.call(this, nodeType); + } + Expression.prototype.isExpression = function () { + return true; + }; + Expression.prototype.isStatementOrExpression = function () { + return true; + }; + return Expression; + })(AST); + TypeScript.Expression = Expression; + var UnaryExpression = (function (_super) { + __extends(UnaryExpression, _super); + function UnaryExpression(nodeType, operand) { + _super.call(this, nodeType); + this.operand = operand; + this.targetType = null; + this.castTerm = null; + } + UnaryExpression.prototype.addToControlFlow = function (context) { + _super.prototype.addToControlFlow.call(this, context); + if(this.nodeType == TypeScript.NodeType.Throw) { + context.returnStmt(); + } + }; + UnaryExpression.prototype.typeCheck = function (typeFlow) { + switch(this.nodeType) { + case TypeScript.NodeType.Not: { + return typeFlow.typeCheckBitNot(this); + + } + case TypeScript.NodeType.LogNot: { + return typeFlow.typeCheckLogNot(this); + + } + case TypeScript.NodeType.Pos: + case TypeScript.NodeType.Neg: { + return typeFlow.typeCheckUnaryNumberOperator(this); + + } + case TypeScript.NodeType.IncPost: + case TypeScript.NodeType.IncPre: + case TypeScript.NodeType.DecPost: + case TypeScript.NodeType.DecPre: { + return typeFlow.typeCheckIncOrDec(this); + + } + case TypeScript.NodeType.ArrayLit: { + typeFlow.typeCheckArrayLit(this); + return this; + + } + case TypeScript.NodeType.ObjectLit: { + typeFlow.typeCheckObjectLit(this); + return this; + + } + case TypeScript.NodeType.Throw: { + this.operand = typeFlow.typeCheck(this.operand); + this.type = typeFlow.voidType; + return this; + + } + case TypeScript.NodeType.Typeof: { + this.operand = typeFlow.typeCheck(this.operand); + this.type = typeFlow.stringType; + return this; + + } + case TypeScript.NodeType.Delete: { + this.operand = typeFlow.typeCheck(this.operand); + this.type = typeFlow.booleanType; + break; + + } + case TypeScript.NodeType.TypeAssertion: { + this.castTerm = typeFlow.typeCheck(this.castTerm); + var applyTargetType = !this.operand.isParenthesized; + var targetType = applyTargetType ? this.castTerm.type : null; + typeFlow.checker.typeCheckWithContextualType(targetType, typeFlow.checker.inProvisionalTypecheckMode(), true, this.operand); + typeFlow.castWithCoercion(this.operand, this.castTerm.type, false, true); + this.type = this.castTerm.type; + return this; + + } + case TypeScript.NodeType.Void: { + this.operand = typeFlow.typeCheck(this.operand); + this.type = typeFlow.checker.undefinedType; + break; + + } + default: { + throw new Error("please implement in derived class"); + + } + } + return this; + }; + UnaryExpression.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + switch(this.nodeType) { + case TypeScript.NodeType.IncPost: { + emitter.emitJavascript(this.operand, TypeScript.TokenID.PlusPlus, false); + emitter.writeToOutput("++"); + break; + + } + case TypeScript.NodeType.LogNot: { + emitter.writeToOutput("!"); + emitter.emitJavascript(this.operand, TypeScript.TokenID.Exclamation, false); + break; + + } + case TypeScript.NodeType.DecPost: { + emitter.emitJavascript(this.operand, TypeScript.TokenID.MinusMinus, false); + emitter.writeToOutput("--"); + break; + + } + case TypeScript.NodeType.ObjectLit: { + emitter.emitObjectLiteral(this.operand); + break; + + } + case TypeScript.NodeType.ArrayLit: { + emitter.emitArrayLiteral(this.operand); + break; + + } + case TypeScript.NodeType.Not: { + emitter.writeToOutput("~"); + emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); + break; + + } + case TypeScript.NodeType.Neg: { + emitter.writeToOutput("-"); + if(this.operand.nodeType == TypeScript.NodeType.Neg) { + this.operand.isParenthesized = true; + } + emitter.emitJavascript(this.operand, TypeScript.TokenID.Minus, false); + break; + + } + case TypeScript.NodeType.Pos: { + emitter.writeToOutput("+"); + if(this.operand.nodeType == TypeScript.NodeType.Pos) { + this.operand.isParenthesized = true; + } + emitter.emitJavascript(this.operand, TypeScript.TokenID.Plus, false); + break; + + } + case TypeScript.NodeType.IncPre: { + emitter.writeToOutput("++"); + emitter.emitJavascript(this.operand, TypeScript.TokenID.PlusPlus, false); + break; + + } + case TypeScript.NodeType.DecPre: { + emitter.writeToOutput("--"); + emitter.emitJavascript(this.operand, TypeScript.TokenID.MinusMinus, false); + break; + + } + case TypeScript.NodeType.Throw: { + emitter.writeToOutput("throw "); + emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); + emitter.writeToOutput(";"); + break; + + } + case TypeScript.NodeType.Typeof: { + emitter.writeToOutput("typeof "); + emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); + break; + + } + case TypeScript.NodeType.Delete: { + emitter.writeToOutput("delete "); + emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); + break; + + } + case TypeScript.NodeType.Void: { + emitter.writeToOutput("void "); + emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); + break; + + } + case TypeScript.NodeType.TypeAssertion: { + emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); + break; + + } + default: { + throw new Error("please implement in derived class"); + + } + } + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return UnaryExpression; + })(Expression); + TypeScript.UnaryExpression = UnaryExpression; + var CallExpression = (function (_super) { + __extends(CallExpression, _super); + function CallExpression(nodeType, target, arguments) { + _super.call(this, nodeType); + this.target = target; + this.arguments = arguments; + this.signature = null; + this.minChar = this.target.minChar; + } + CallExpression.prototype.typeCheck = function (typeFlow) { + if(this.nodeType == TypeScript.NodeType.New) { + return typeFlow.typeCheckNew(this); + } else { + return typeFlow.typeCheckCall(this); + } + }; + CallExpression.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + if(this.nodeType == TypeScript.NodeType.New) { + emitter.emitNew(this.target, this.arguments); + } else { + emitter.emitCall(this, this.target, this.arguments); + } + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return CallExpression; + })(Expression); + TypeScript.CallExpression = CallExpression; + var BinaryExpression = (function (_super) { + __extends(BinaryExpression, _super); + function BinaryExpression(nodeType, operand1, operand2) { + _super.call(this, nodeType); + this.operand1 = operand1; + this.operand2 = operand2; + } + BinaryExpression.prototype.typeCheck = function (typeFlow) { + switch(this.nodeType) { + case TypeScript.NodeType.Dot: { + return typeFlow.typeCheckDotOperator(this); + + } + case TypeScript.NodeType.Asg: { + return typeFlow.typeCheckAsgOperator(this); + + } + case TypeScript.NodeType.Add: + case TypeScript.NodeType.Sub: + case TypeScript.NodeType.Mul: + case TypeScript.NodeType.Div: + case TypeScript.NodeType.Mod: + case TypeScript.NodeType.Or: + case TypeScript.NodeType.And: { + return typeFlow.typeCheckArithmeticOperator(this, false); + + } + case TypeScript.NodeType.Xor: { + return typeFlow.typeCheckBitwiseOperator(this, false); + + } + case TypeScript.NodeType.Ne: + case TypeScript.NodeType.Eq: { + var text; + if(typeFlow.checker.styleSettings.eqeqeq) { + text = TypeScript.nodeTypeTable[this.nodeType]; + typeFlow.checker.errorReporter.styleError(this, "use of " + text); + } else { + if(typeFlow.checker.styleSettings.eqnull) { + text = TypeScript.nodeTypeTable[this.nodeType]; + if((this.operand2 !== null) && (this.operand2.nodeType == TypeScript.NodeType.Null)) { + typeFlow.checker.errorReporter.styleError(this, "use of " + text + " to compare with null"); + } + } + } + + } + case TypeScript.NodeType.Eqv: + case TypeScript.NodeType.NEqv: + case TypeScript.NodeType.Lt: + case TypeScript.NodeType.Le: + case TypeScript.NodeType.Ge: + case TypeScript.NodeType.Gt: { + return typeFlow.typeCheckBooleanOperator(this); + + } + case TypeScript.NodeType.Index: { + return typeFlow.typeCheckIndex(this); + + } + case TypeScript.NodeType.Member: { + this.type = typeFlow.voidType; + return this; + + } + case TypeScript.NodeType.LogOr: { + return typeFlow.typeCheckLogOr(this); + + } + case TypeScript.NodeType.LogAnd: { + return typeFlow.typeCheckLogAnd(this); + + } + case TypeScript.NodeType.AsgAdd: + case TypeScript.NodeType.AsgSub: + case TypeScript.NodeType.AsgMul: + case TypeScript.NodeType.AsgDiv: + case TypeScript.NodeType.AsgMod: + case TypeScript.NodeType.AsgOr: + case TypeScript.NodeType.AsgAnd: { + return typeFlow.typeCheckArithmeticOperator(this, true); + + } + case TypeScript.NodeType.AsgXor: { + return typeFlow.typeCheckBitwiseOperator(this, true); + + } + case TypeScript.NodeType.Lsh: + case TypeScript.NodeType.Rsh: + case TypeScript.NodeType.Rs2: { + return typeFlow.typeCheckShift(this, false); + + } + case TypeScript.NodeType.AsgLsh: + case TypeScript.NodeType.AsgRsh: + case TypeScript.NodeType.AsgRs2: { + return typeFlow.typeCheckShift(this, true); + + } + case TypeScript.NodeType.Comma: { + return typeFlow.typeCheckCommaOperator(this); + + } + case TypeScript.NodeType.InstOf: { + return typeFlow.typeCheckInstOf(this); + + } + case TypeScript.NodeType.In: { + return typeFlow.typeCheckInOperator(this); + + } + case TypeScript.NodeType.From: { + typeFlow.checker.errorReporter.simpleError(this, "Illegal use of 'from' keyword in binary expression"); + break; + + } + default: { + throw new Error("please implement in derived class"); + + } + } + return this; + }; + BinaryExpression.prototype.emit = function (emitter, tokenId, startLine) { + var binTokenId = TypeScript.nodeTypeToTokTable[this.nodeType]; + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + if(binTokenId != undefined) { + emitter.emitJavascript(this.operand1, binTokenId, false); + if(TypeScript.tokenTable[binTokenId].text == "instanceof") { + emitter.writeToOutput(" instanceof "); + } else { + if(TypeScript.tokenTable[binTokenId].text == "in") { + emitter.writeToOutput(" in "); + } else { + emitter.writeToOutputTrimmable(" " + TypeScript.tokenTable[binTokenId].text + " "); + } + } + emitter.emitJavascript(this.operand2, binTokenId, false); + } else { + switch(this.nodeType) { + case TypeScript.NodeType.Dot: { + if(!emitter.tryEmitConstant(this)) { + emitter.emitJavascript(this.operand1, TypeScript.TokenID.Dot, false); + emitter.writeToOutput("."); + emitter.emitJavascriptName(this.operand2, false); + } + break; + + } + case TypeScript.NodeType.Index: { + emitter.emitIndex(this.operand1, this.operand2); + break; + + } + case TypeScript.NodeType.Member: { + if(this.operand2.nodeType == TypeScript.NodeType.FuncDecl && (this.operand2).isAccessor()) { + var funcDecl = this.operand2; + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { + emitter.writeToOutput("get "); + } else { + emitter.writeToOutput("set "); + } + emitter.emitJavascript(this.operand1, TypeScript.TokenID.Colon, false); + } else { + emitter.emitJavascript(this.operand1, TypeScript.TokenID.Colon, false); + emitter.writeToOutputTrimmable(": "); + } + emitter.emitJavascript(this.operand2, TypeScript.TokenID.Comma, false); + break; + + } + case TypeScript.NodeType.Comma: { + emitter.emitJavascript(this.operand1, TypeScript.TokenID.Comma, false); + if(emitter.emitState.inObjectLiteral) { + emitter.writeLineToOutput(", "); + } else { + emitter.writeToOutput(","); + } + emitter.emitJavascript(this.operand2, TypeScript.TokenID.Comma, false); + break; + + } + case TypeScript.NodeType.Is: { + throw new Error("should be de-sugared during type check"); + + } + default: { + throw new Error("please implement in derived class"); + + } + } + } + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return BinaryExpression; + })(Expression); + TypeScript.BinaryExpression = BinaryExpression; + var ConditionalExpression = (function (_super) { + __extends(ConditionalExpression, _super); + function ConditionalExpression(operand1, operand2, operand3) { + _super.call(this, TypeScript.NodeType.ConditionalExpression); + this.operand1 = operand1; + this.operand2 = operand2; + this.operand3 = operand3; + } + ConditionalExpression.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckQMark(this); + }; + ConditionalExpression.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.emitJavascript(this.operand1, TypeScript.TokenID.Question, false); + emitter.writeToOutput(" ? "); + emitter.emitJavascript(this.operand2, TypeScript.TokenID.Question, false); + emitter.writeToOutput(" : "); + emitter.emitJavascript(this.operand3, TypeScript.TokenID.Question, false); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return ConditionalExpression; + })(Expression); + TypeScript.ConditionalExpression = ConditionalExpression; + var NumberLiteral = (function (_super) { + __extends(NumberLiteral, _super); + function NumberLiteral(value, hasEmptyFraction) { + _super.call(this, TypeScript.NodeType.NumberLit); + this.value = value; + this.hasEmptyFraction = hasEmptyFraction; + this.isNegativeZero = false; + } + NumberLiteral.prototype.typeCheck = function (typeFlow) { + this.type = typeFlow.doubleType; + return this; + }; + NumberLiteral.prototype.treeViewLabel = function () { + return "num: " + this.printLabel(); + }; + NumberLiteral.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + if(this.isNegativeZero) { + emitter.writeToOutput("-"); + } + emitter.writeToOutput(this.value.toString()); + if(this.hasEmptyFraction) { + emitter.writeToOutput(".0"); + } + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + NumberLiteral.prototype.printLabel = function () { + if(Math.floor(this.value) != this.value) { + return this.value.toFixed(2).toString(); + } else { + if(this.hasEmptyFraction) { + return this.value.toString() + ".0"; + } else { + return this.value.toString(); + } + } + }; + return NumberLiteral; + })(Expression); + TypeScript.NumberLiteral = NumberLiteral; + var RegexLiteral = (function (_super) { + __extends(RegexLiteral, _super); + function RegexLiteral(regex) { + _super.call(this, TypeScript.NodeType.Regex); + this.regex = regex; + } + RegexLiteral.prototype.typeCheck = function (typeFlow) { + this.type = typeFlow.regexType; + return this; + }; + RegexLiteral.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput(this.regex.toString()); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return RegexLiteral; + })(Expression); + TypeScript.RegexLiteral = RegexLiteral; + var StringLiteral = (function (_super) { + __extends(StringLiteral, _super); + function StringLiteral(text) { + _super.call(this, TypeScript.NodeType.QString); + this.text = text; + } + StringLiteral.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.emitStringLiteral(this.text); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + StringLiteral.prototype.typeCheck = function (typeFlow) { + this.type = typeFlow.stringType; + return this; + }; + StringLiteral.prototype.treeViewLabel = function () { + return "st: " + this.text; + }; + StringLiteral.prototype.printLabel = function () { + return this.text; + }; + return StringLiteral; + })(Expression); + TypeScript.StringLiteral = StringLiteral; + var ModuleElement = (function (_super) { + __extends(ModuleElement, _super); + function ModuleElement(nodeType) { + _super.call(this, nodeType); + } + return ModuleElement; + })(AST); + TypeScript.ModuleElement = ModuleElement; + var ImportDeclaration = (function (_super) { + __extends(ImportDeclaration, _super); + function ImportDeclaration(id, alias) { + _super.call(this, TypeScript.NodeType.ImportDeclaration); + this.id = id; + this.alias = alias; + this.varFlags = TypeScript.VarFlags.None; + this.isDynamicImport = false; + } + ImportDeclaration.prototype.isStatementOrExpression = function () { + return true; + }; + ImportDeclaration.prototype.isDeclaration = function () { + return true; + }; + ImportDeclaration.prototype.emit = function (emitter, tokenId, startLine) { + var mod = this.alias.type; + if(!this.isDynamicImport || (this.id.sym && !(this.id.sym).onlyReferencedAsTypeRef)) { + var prevModAliasId = emitter.modAliasId; + var prevFirstModAlias = emitter.firstModAlias; + emitter.recordSourceMappingStart(this); + emitter.emitParensAndCommentsInPlace(this, true); + emitter.writeToOutput("var " + this.id.actualText + " = "); + emitter.modAliasId = this.id.actualText; + emitter.firstModAlias = this.firstAliasedModToString(); + emitter.emitJavascript(this.alias, TypeScript.TokenID.Tilde, false); + if(!this.isDynamicImport) { + emitter.writeToOutput(";"); + } + emitter.emitParensAndCommentsInPlace(this, false); + emitter.recordSourceMappingEnd(this); + emitter.modAliasId = prevModAliasId; + emitter.firstModAlias = prevFirstModAlias; + } + }; + ImportDeclaration.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckImportDecl(this); + }; + ImportDeclaration.prototype.getAliasName = function (aliasAST) { + if (typeof aliasAST === "undefined") { aliasAST = this.alias; } + if(aliasAST.nodeType == TypeScript.NodeType.Name) { + return (aliasAST).actualText; + } else { + var dotExpr = aliasAST; + return this.getAliasName(dotExpr.operand1) + "." + this.getAliasName(dotExpr.operand2); + } + }; + ImportDeclaration.prototype.firstAliasedModToString = function () { + if(this.alias.nodeType == TypeScript.NodeType.Name) { + return (this.alias).actualText; + } else { + var dotExpr = this.alias; + var firstMod = dotExpr.operand1; + return firstMod.actualText; + } + }; + return ImportDeclaration; + })(ModuleElement); + TypeScript.ImportDeclaration = ImportDeclaration; + var BoundDecl = (function (_super) { + __extends(BoundDecl, _super); + function BoundDecl(id, nodeType, nestingLevel) { + _super.call(this, nodeType); + this.id = id; + this.nestingLevel = nestingLevel; + this.init = null; + this.typeExpr = null; + this.varFlags = TypeScript.VarFlags.None; + this.sym = null; + } + BoundDecl.prototype.isDeclaration = function () { + return true; + }; + BoundDecl.prototype.isStatementOrExpression = function () { + return true; + }; + BoundDecl.prototype.isPrivate = function () { + return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Private); + }; + BoundDecl.prototype.isPublic = function () { + return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Public); + }; + BoundDecl.prototype.isProperty = function () { + return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Property); + }; + BoundDecl.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckBoundDecl(this); + }; + BoundDecl.prototype.printLabel = function () { + return this.treeViewLabel(); + }; + return BoundDecl; + })(AST); + TypeScript.BoundDecl = BoundDecl; + var VarDecl = (function (_super) { + __extends(VarDecl, _super); + function VarDecl(id, nest) { + _super.call(this, id, TypeScript.NodeType.VarDecl, nest); + } + VarDecl.prototype.isAmbient = function () { + return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Ambient); + }; + VarDecl.prototype.isExported = function () { + return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Exported); + }; + VarDecl.prototype.isStatic = function () { + return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Static); + }; + VarDecl.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitJavascriptVarDecl(this, tokenId); + }; + VarDecl.prototype.treeViewLabel = function () { + return "var " + this.id.actualText; + }; + return VarDecl; + })(BoundDecl); + TypeScript.VarDecl = VarDecl; + var ArgDecl = (function (_super) { + __extends(ArgDecl, _super); + function ArgDecl(id) { + _super.call(this, id, TypeScript.NodeType.ArgDecl, 0); + this.isOptional = false; + this.parameterPropertySym = null; + } + ArgDecl.prototype.isOptionalArg = function () { + return this.isOptional || this.init; + }; + ArgDecl.prototype.treeViewLabel = function () { + return "arg: " + this.id.actualText; + }; + ArgDecl.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput(this.id.actualText); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return ArgDecl; + })(BoundDecl); + TypeScript.ArgDecl = ArgDecl; + var internalId = 0; + var FuncDecl = (function (_super) { + __extends(FuncDecl, _super); + function FuncDecl(name, bod, isConstructor, arguments, vars, scopes, statics, nodeType) { + _super.call(this, nodeType); + this.name = name; + this.bod = bod; + this.isConstructor = isConstructor; + this.arguments = arguments; + this.vars = vars; + this.scopes = scopes; + this.statics = statics; + this.hint = null; + this.fncFlags = TypeScript.FncFlags.None; + this.returnTypeAnnotation = null; + this.variableArgList = false; + this.jumpRefs = null; + this.internalNameCache = null; + this.tmp1Declared = false; + this.enclosingFnc = null; + this.freeVariables = []; + this.unitIndex = -1; + this.classDecl = null; + this.boundToProperty = null; + this.isOverload = false; + this.innerStaticFuncs = []; + this.isTargetTypedAsMethod = false; + this.isInlineCallLiteral = false; + this.accessorSymbol = null; + this.leftCurlyCount = 0; + this.rightCurlyCount = 0; + this.returnStatementsWithExpressions = []; + this.scopeType = null; + this.endingToken = null; + } + FuncDecl.prototype.isDeclaration = function () { + return true; + }; + FuncDecl.prototype.internalName = function () { + if(this.internalNameCache == null) { + var extName = this.getNameText(); + if(extName) { + this.internalNameCache = "_internal_" + extName; + } else { + this.internalNameCache = "_internal_" + internalId++; + } + } + return this.internalNameCache; + }; + FuncDecl.prototype.hasSelfReference = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.HasSelfReference); + }; + FuncDecl.prototype.setHasSelfReference = function () { + this.fncFlags |= TypeScript.FncFlags.HasSelfReference; + }; + FuncDecl.prototype.hasSuperReferenceInFatArrowFunction = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.HasSuperReferenceInFatArrowFunction); + }; + FuncDecl.prototype.setHasSuperReferenceInFatArrowFunction = function () { + this.fncFlags |= TypeScript.FncFlags.HasSuperReferenceInFatArrowFunction; + }; + FuncDecl.prototype.addCloRef = function (id, sym) { + if(this.envids == null) { + this.envids = new Array(); + } + this.envids[this.envids.length] = id; + var outerFnc = this.enclosingFnc; + if(sym) { + while(outerFnc && (outerFnc.type.symbol != sym.container)) { + outerFnc.addJumpRef(sym); + outerFnc = outerFnc.enclosingFnc; + } + } + return this.envids.length - 1; + }; + FuncDecl.prototype.addJumpRef = function (sym) { + if(this.jumpRefs == null) { + this.jumpRefs = new Array(); + } + var id = new Identifier(sym.name); + this.jumpRefs[this.jumpRefs.length] = id; + id.sym = sym; + id.cloId = this.addCloRef(id, null); + }; + FuncDecl.prototype.buildControlFlow = function () { + var entry = new TypeScript.BasicBlock(); + var exit = new TypeScript.BasicBlock(); + var context = new TypeScript.ControlFlowContext(entry, exit); + var controlFlowPrefix = function (ast, parent, walker) { + ast.addToControlFlow(walker.state); + return ast; + }; + var walker = TypeScript.getAstWalkerFactory().getWalker(controlFlowPrefix, null, null, context); + context.walker = walker; + walker.walk(this.bod, this); + return context; + }; + FuncDecl.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckFunction(this); + }; + FuncDecl.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitJavascriptFunction(this); + }; + FuncDecl.prototype.getNameText = function () { + if(this.name) { + return this.name.actualText; + } else { + return this.hint; + } + }; + FuncDecl.prototype.isMethod = function () { + return (this.fncFlags & TypeScript.FncFlags.Method) != TypeScript.FncFlags.None; + }; + FuncDecl.prototype.isCallMember = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.CallMember); + }; + FuncDecl.prototype.isConstructMember = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.ConstructMember); + }; + FuncDecl.prototype.isIndexerMember = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.IndexerMember); + }; + FuncDecl.prototype.isSpecialFn = function () { + return this.isCallMember() || this.isIndexerMember() || this.isConstructMember(); + }; + FuncDecl.prototype.isAnonymousFn = function () { + return this.name === null; + }; + FuncDecl.prototype.isAccessor = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.GetAccessor) || TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.SetAccessor); + }; + FuncDecl.prototype.isGetAccessor = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.GetAccessor); + }; + FuncDecl.prototype.isSetAccessor = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.SetAccessor); + }; + FuncDecl.prototype.isAmbient = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Ambient); + }; + FuncDecl.prototype.isExported = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Exported); + }; + FuncDecl.prototype.isPrivate = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Private); + }; + FuncDecl.prototype.isPublic = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Public); + }; + FuncDecl.prototype.isStatic = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Static); + }; + FuncDecl.prototype.treeViewLabel = function () { + if(this.name == null) { + return "funcExpr"; + } else { + return "func: " + this.name.actualText; + } + }; + FuncDecl.prototype.ClearFlags = function () { + this.fncFlags = TypeScript.FncFlags.None; + }; + FuncDecl.prototype.isSignature = function () { + return (this.fncFlags & TypeScript.FncFlags.Signature) != TypeScript.FncFlags.None; + }; + return FuncDecl; + })(AST); + TypeScript.FuncDecl = FuncDecl; + var LocationInfo = (function () { + function LocationInfo(filename, lineMap, unitIndex) { + this.filename = filename; + this.lineMap = lineMap; + this.unitIndex = unitIndex; + } + return LocationInfo; + })(); + TypeScript.LocationInfo = LocationInfo; + TypeScript.unknownLocationInfo = new LocationInfo("unknown", null, -1); + var Script = (function (_super) { + __extends(Script, _super); + function Script(vars, scopes) { + _super.call(this, new Identifier("script"), null, false, null, vars, scopes, null, TypeScript.NodeType.Script); + this.locationInfo = null; + this.referencedFiles = []; + this.requiresGlobal = false; + this.requiresExtendsBlock = false; + this.isResident = false; + this.isDeclareFile = false; + this.hasBeenTypeChecked = false; + this.topLevelMod = null; + this.leftCurlyCount = 0; + this.rightCurlyCount = 0; + this.containsUnicodeChar = false; + this.containsUnicodeCharInComment = false; + this.externallyVisibleImportedSymbols = []; + this.vars = vars; + this.scopes = scopes; + } + Script.prototype.setCachedEmitRequired = function (value) { + this.cachedEmitRequired = value; + return this.cachedEmitRequired; + }; + Script.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckScript(this); + }; + Script.prototype.treeViewLabel = function () { + return "Script"; + }; + Script.prototype.emitRequired = function (emitOptions) { + if(this.cachedEmitRequired != undefined) { + return this.cachedEmitRequired; + } + if(!this.isDeclareFile && !this.isResident && this.bod) { + for(var i = 0, len = this.bod.members.length; i < len; i++) { + var stmt = this.bod.members[i]; + if(stmt.nodeType == TypeScript.NodeType.ModuleDeclaration) { + if(!TypeScript.hasFlag((stmt).modFlags, TypeScript.ModuleFlags.ShouldEmitModuleDecl | TypeScript.ModuleFlags.Ambient)) { + return this.setCachedEmitRequired(true); + } + } else { + if(stmt.nodeType == TypeScript.NodeType.ClassDeclaration) { + if(!TypeScript.hasFlag((stmt).varFlags, TypeScript.VarFlags.Ambient)) { + return this.setCachedEmitRequired(true); + } + } else { + if(stmt.nodeType == TypeScript.NodeType.VarDecl) { + if(!TypeScript.hasFlag((stmt).varFlags, TypeScript.VarFlags.Ambient)) { + return this.setCachedEmitRequired(true); + } + } else { + if(stmt.nodeType == TypeScript.NodeType.FuncDecl) { + if(!(stmt).isSignature()) { + return this.setCachedEmitRequired(true); + } + } else { + if(stmt.nodeType != TypeScript.NodeType.InterfaceDeclaration && stmt.nodeType != TypeScript.NodeType.Empty) { + return this.setCachedEmitRequired(true); + } + } + } + } + } + } + if(emitOptions.emitComments && ((this.bod.preComments && this.bod.preComments.length > 0) || (this.bod.postComments && this.bod.postComments.length > 0))) { + return this.setCachedEmitRequired(true); + } + } + return this.setCachedEmitRequired(false); + }; + Script.prototype.emit = function (emitter, tokenId, startLine) { + if(this.emitRequired(emitter.emitOptions)) { + emitter.emitParensAndCommentsInPlace(this.bod, true); + emitter.emitJavascriptList(this.bod, null, TypeScript.TokenID.Semicolon, true, false, false, true, this.requiresExtendsBlock); + emitter.emitParensAndCommentsInPlace(this.bod, false); + } + }; + Script.prototype.AddExternallyVisibleImportedSymbol = function (symbol, checker) { + if(this.isExternallyVisibleSymbol(symbol)) { + return; + } + if(!symbol.getType().symbol.isExternallyVisible(checker)) { + var quotes = ""; + var moduleName = symbol.getType().symbol.prettyName; + if(!TypeScript.isQuoted(moduleName)) { + quotes = "'"; + } + checker.errorReporter.simpleError(symbol.declAST, "Externally visible import statement uses non exported module " + quotes + moduleName + quotes); + } + this.externallyVisibleImportedSymbols.push(symbol); + }; + Script.prototype.isExternallyVisibleSymbol = function (symbol) { + for(var i = 0; i < this.externallyVisibleImportedSymbols.length; i++) { + if(this.externallyVisibleImportedSymbols[i] == symbol) { + return true; + } + } + return false; + }; + return Script; + })(FuncDecl); + TypeScript.Script = Script; + var NamedDeclaration = (function (_super) { + __extends(NamedDeclaration, _super); + function NamedDeclaration(nodeType, name, members) { + _super.call(this, nodeType); + this.name = name; + this.members = members; + this.leftCurlyCount = 0; + this.rightCurlyCount = 0; + } + NamedDeclaration.prototype.isDeclaration = function () { + return true; + }; + return NamedDeclaration; + })(ModuleElement); + TypeScript.NamedDeclaration = NamedDeclaration; + var ModuleDeclaration = (function (_super) { + __extends(ModuleDeclaration, _super); + function ModuleDeclaration(name, members, vars, scopes, endingToken) { + _super.call(this, TypeScript.NodeType.ModuleDeclaration, name, members); + this.endingToken = endingToken; + this.modFlags = TypeScript.ModuleFlags.ShouldEmitModuleDecl; + this.amdDependencies = []; + this.containsUnicodeChar = false; + this.containsUnicodeCharInComment = false; + this.vars = vars; + this.scopes = scopes; + this.prettyName = this.name.actualText; + } + ModuleDeclaration.prototype.isExported = function () { + return TypeScript.hasFlag(this.modFlags, TypeScript.ModuleFlags.Exported); + }; + ModuleDeclaration.prototype.isAmbient = function () { + return TypeScript.hasFlag(this.modFlags, TypeScript.ModuleFlags.Ambient); + }; + ModuleDeclaration.prototype.isEnum = function () { + return TypeScript.hasFlag(this.modFlags, TypeScript.ModuleFlags.IsEnum); + }; + ModuleDeclaration.prototype.recordNonInterface = function () { + this.modFlags &= ~TypeScript.ModuleFlags.ShouldEmitModuleDecl; + }; + ModuleDeclaration.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckModule(this); + }; + ModuleDeclaration.prototype.emit = function (emitter, tokenId, startLine) { + if(!TypeScript.hasFlag(this.modFlags, TypeScript.ModuleFlags.ShouldEmitModuleDecl)) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.emitJavascriptModule(this); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + } + }; + return ModuleDeclaration; + })(NamedDeclaration); + TypeScript.ModuleDeclaration = ModuleDeclaration; + var TypeDeclaration = (function (_super) { + __extends(TypeDeclaration, _super); + function TypeDeclaration(nodeType, name, extendsList, implementsList, members) { + _super.call(this, nodeType, name, members); + this.extendsList = extendsList; + this.implementsList = implementsList; + this.varFlags = TypeScript.VarFlags.None; + } + TypeDeclaration.prototype.isExported = function () { + return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Exported); + }; + TypeDeclaration.prototype.isAmbient = function () { + return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Ambient); + }; + return TypeDeclaration; + })(NamedDeclaration); + TypeScript.TypeDeclaration = TypeDeclaration; + var ClassDeclaration = (function (_super) { + __extends(ClassDeclaration, _super); + function ClassDeclaration(name, members, extendsList, implementsList) { + _super.call(this, TypeScript.NodeType.ClassDeclaration, name, extendsList, implementsList, members); + this.knownMemberNames = { + }; + this.constructorDecl = null; + this.constructorNestingLevel = 0; + this.endingToken = null; + } + ClassDeclaration.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckClass(this); + }; + ClassDeclaration.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitJavascriptClass(this); + }; + return ClassDeclaration; + })(TypeDeclaration); + TypeScript.ClassDeclaration = ClassDeclaration; + var InterfaceDeclaration = (function (_super) { + __extends(InterfaceDeclaration, _super); + function InterfaceDeclaration(name, members, extendsList, implementsList) { + _super.call(this, TypeScript.NodeType.InterfaceDeclaration, name, extendsList, implementsList, members); + } + InterfaceDeclaration.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckInterface(this); + }; + InterfaceDeclaration.prototype.emit = function (emitter, tokenId, startLine) { + }; + return InterfaceDeclaration; + })(TypeDeclaration); + TypeScript.InterfaceDeclaration = InterfaceDeclaration; + var Statement = (function (_super) { + __extends(Statement, _super); + function Statement(nodeType) { + _super.call(this, nodeType); + this.flags |= TypeScript.ASTFlags.IsStatement; + } + Statement.prototype.isLoop = function () { + return false; + }; + Statement.prototype.isStatementOrExpression = function () { + return true; + }; + Statement.prototype.isCompoundStatement = function () { + return this.isLoop(); + }; + Statement.prototype.typeCheck = function (typeFlow) { + this.type = typeFlow.voidType; + return this; + }; + return Statement; + })(ModuleElement); + TypeScript.Statement = Statement; + var LabeledStatement = (function (_super) { + __extends(LabeledStatement, _super); + function LabeledStatement(labels, stmt) { + _super.call(this, TypeScript.NodeType.LabeledStatement); + this.labels = labels; + this.stmt = stmt; + } + LabeledStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + if(this.labels) { + var labelsLen = this.labels.members.length; + for(var i = 0; i < labelsLen; i++) { + this.labels.members[i].emit(emitter, tokenId, startLine); + } + } + this.stmt.emit(emitter, tokenId, true); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + LabeledStatement.prototype.typeCheck = function (typeFlow) { + typeFlow.typeCheck(this.labels); + this.stmt = this.stmt.typeCheck(typeFlow); + return this; + }; + LabeledStatement.prototype.addToControlFlow = function (context) { + var beforeBB = context.current; + var bb = new TypeScript.BasicBlock(); + context.current = bb; + beforeBB.addSuccessor(bb); + }; + return LabeledStatement; + })(Statement); + TypeScript.LabeledStatement = LabeledStatement; + var Block = (function (_super) { + __extends(Block, _super); + function Block(statements, isStatementBlock) { + _super.call(this, TypeScript.NodeType.Block); + this.statements = statements; + this.isStatementBlock = isStatementBlock; + } + Block.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + if(this.isStatementBlock) { + emitter.writeLineToOutput(" {"); + emitter.indenter.increaseIndent(); + } else { + emitter.setInVarBlock(this.statements.members.length); + } + var temp = emitter.setInObjectLiteral(false); + if(this.statements) { + emitter.emitJavascriptList(this.statements, null, TypeScript.TokenID.Semicolon, true, false, false); + } + if(this.isStatementBlock) { + emitter.indenter.decreaseIndent(); + emitter.emitIndent(); + emitter.writeToOutput("}"); + } + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + Block.prototype.addToControlFlow = function (context) { + var afterIfNeeded = new TypeScript.BasicBlock(); + context.pushStatement(this, context.current, afterIfNeeded); + if(this.statements) { + context.walk(this.statements, this); + } + context.walker.options.goChildren = false; + context.popStatement(); + if(afterIfNeeded.predecessors.length > 0) { + context.current.addSuccessor(afterIfNeeded); + context.current = afterIfNeeded; + } + }; + Block.prototype.typeCheck = function (typeFlow) { + if(!typeFlow.checker.styleSettings.emptyBlocks) { + if((this.statements === null) || (this.statements.members.length == 0)) { + typeFlow.checker.errorReporter.styleError(this, "empty block"); + } + } + typeFlow.typeCheck(this.statements); + return this; + }; + return Block; + })(Statement); + TypeScript.Block = Block; + var Jump = (function (_super) { + __extends(Jump, _super); + function Jump(nodeType) { + _super.call(this, nodeType); + this.target = null; + this.resolvedTarget = null; + } + Jump.prototype.hasExplicitTarget = function () { + return (this.target); + }; + Jump.prototype.setResolvedTarget = function (parser, stmt) { + if(stmt.isLoop()) { + this.resolvedTarget = stmt; + return true; + } + if(this.nodeType === TypeScript.NodeType.Continue) { + parser.reportParseError("continue statement applies only to loops"); + return false; + } else { + if((stmt.nodeType == TypeScript.NodeType.Switch) || this.hasExplicitTarget()) { + this.resolvedTarget = stmt; + return true; + } else { + parser.reportParseError("break statement with no label can apply only to a loop or switch statement"); + return false; + } + } + }; + Jump.prototype.addToControlFlow = function (context) { + _super.prototype.addToControlFlow.call(this, context); + context.unconditionalBranch(this.resolvedTarget, (this.nodeType == TypeScript.NodeType.Continue)); + }; + Jump.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + if(this.nodeType == TypeScript.NodeType.Break) { + emitter.writeToOutput("break"); + } else { + emitter.writeToOutput("continue"); + } + if(this.hasExplicitTarget()) { + emitter.writeToOutput(" " + this.target); + } + emitter.recordSourceMappingEnd(this); + emitter.writeToOutput(";"); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return Jump; + })(Statement); + TypeScript.Jump = Jump; + var WhileStatement = (function (_super) { + __extends(WhileStatement, _super); + function WhileStatement(cond) { + _super.call(this, TypeScript.NodeType.While); + this.cond = cond; + this.body = null; + } + WhileStatement.prototype.isLoop = function () { + return true; + }; + WhileStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + emitter.writeToOutput("while("); + emitter.emitJavascript(this.cond, TypeScript.TokenID.While, false); + emitter.writeToOutput(")"); + emitter.emitJavascriptStatements(this.body, false); + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + WhileStatement.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckWhile(this); + }; + WhileStatement.prototype.addToControlFlow = function (context) { + var loopHeader = context.current; + var loopStart = new TypeScript.BasicBlock(); + var afterLoop = new TypeScript.BasicBlock(); + loopHeader.addSuccessor(loopStart); + context.current = loopStart; + context.addContent(this.cond); + var condBlock = context.current; + var targetInfo = null; + if(this.body) { + context.current = new TypeScript.BasicBlock(); + condBlock.addSuccessor(context.current); + context.pushStatement(this, loopStart, afterLoop); + context.walk(this.body, this); + targetInfo = context.popStatement(); + } + if(!(context.noContinuation)) { + var loopEnd = context.current; + loopEnd.addSuccessor(loopStart); + } + context.current = afterLoop; + condBlock.addSuccessor(afterLoop); + context.noContinuation = false; + context.walker.options.goChildren = false; + }; + return WhileStatement; + })(Statement); + TypeScript.WhileStatement = WhileStatement; + var DoWhileStatement = (function (_super) { + __extends(DoWhileStatement, _super); + function DoWhileStatement() { + _super.call(this, TypeScript.NodeType.DoWhile); + this.body = null; + this.whileAST = null; + this.cond = null; + } + DoWhileStatement.prototype.isLoop = function () { + return true; + }; + DoWhileStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + emitter.writeToOutput("do"); + emitter.emitJavascriptStatements(this.body, true); + emitter.recordSourceMappingStart(this.whileAST); + emitter.writeToOutput("while"); + emitter.recordSourceMappingEnd(this.whileAST); + emitter.writeToOutput('('); + emitter.emitJavascript(this.cond, TypeScript.TokenID.CloseParen, false); + emitter.writeToOutput(")"); + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.writeToOutput(";"); + emitter.emitParensAndCommentsInPlace(this, false); + }; + DoWhileStatement.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckDoWhile(this); + }; + DoWhileStatement.prototype.addToControlFlow = function (context) { + var loopHeader = context.current; + var loopStart = new TypeScript.BasicBlock(); + var afterLoop = new TypeScript.BasicBlock(); + loopHeader.addSuccessor(loopStart); + context.current = loopStart; + var targetInfo = null; + if(this.body) { + context.pushStatement(this, loopStart, afterLoop); + context.walk(this.body, this); + targetInfo = context.popStatement(); + } + if(!(context.noContinuation)) { + var loopEnd = context.current; + loopEnd.addSuccessor(loopStart); + context.addContent(this.cond); + context.current = afterLoop; + loopEnd.addSuccessor(afterLoop); + } else { + context.addUnreachable(this.cond); + } + context.walker.options.goChildren = false; + }; + return DoWhileStatement; + })(Statement); + TypeScript.DoWhileStatement = DoWhileStatement; + var IfStatement = (function (_super) { + __extends(IfStatement, _super); + function IfStatement(cond) { + _super.call(this, TypeScript.NodeType.If); + this.cond = cond; + this.elseBod = null; + this.statement = new ASTSpan(); + } + IfStatement.prototype.isCompoundStatement = function () { + return true; + }; + IfStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + emitter.recordSourceMappingStart(this.statement); + emitter.writeToOutput("if("); + emitter.emitJavascript(this.cond, TypeScript.TokenID.If, false); + emitter.writeToOutput(")"); + emitter.recordSourceMappingEnd(this.statement); + emitter.emitJavascriptStatements(this.thenBod, true); + if(this.elseBod) { + if(this.elseBod.nodeType === TypeScript.NodeType.If) { + emitter.writeToOutput(" else "); + this.elseBod.emit(emitter, tokenId, false); + } else { + emitter.writeToOutput(" else"); + emitter.emitJavascriptStatements(this.elseBod, true); + } + } + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + IfStatement.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckIf(this); + }; + IfStatement.prototype.addToControlFlow = function (context) { + this.cond.addToControlFlow(context); + var afterIf = new TypeScript.BasicBlock(); + var beforeIf = context.current; + context.pushStatement(this, beforeIf, afterIf); + var hasContinuation = false; + context.current = new TypeScript.BasicBlock(); + beforeIf.addSuccessor(context.current); + context.walk(this.thenBod, this); + if(!context.noContinuation) { + hasContinuation = true; + context.current.addSuccessor(afterIf); + } + if(this.elseBod) { + context.current = new TypeScript.BasicBlock(); + context.noContinuation = false; + beforeIf.addSuccessor(context.current); + context.walk(this.elseBod, this); + if(!context.noContinuation) { + hasContinuation = true; + context.current.addSuccessor(afterIf); + } else { + if(hasContinuation) { + context.noContinuation = false; + } + } + } else { + beforeIf.addSuccessor(afterIf); + context.noContinuation = false; + hasContinuation = true; + } + var targetInfo = context.popStatement(); + if(afterIf.predecessors.length > 0) { + context.noContinuation = false; + hasContinuation = true; + } + if(hasContinuation) { + context.current = afterIf; + } + context.walker.options.goChildren = false; + }; + return IfStatement; + })(Statement); + TypeScript.IfStatement = IfStatement; + var ReturnStatement = (function (_super) { + __extends(ReturnStatement, _super); + function ReturnStatement() { + _super.call(this, TypeScript.NodeType.Return); + this.returnExpression = null; + } + ReturnStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + if(this.returnExpression) { + emitter.writeToOutput("return "); + emitter.emitJavascript(this.returnExpression, TypeScript.TokenID.Semicolon, false); + if(this.returnExpression.nodeType === TypeScript.NodeType.FuncDecl) { + emitter.writeToOutput(";"); + } + } else { + emitter.writeToOutput("return;"); + } + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + ReturnStatement.prototype.addToControlFlow = function (context) { + _super.prototype.addToControlFlow.call(this, context); + context.returnStmt(); + }; + ReturnStatement.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckReturn(this); + }; + return ReturnStatement; + })(Statement); + TypeScript.ReturnStatement = ReturnStatement; + var EndCode = (function (_super) { + __extends(EndCode, _super); + function EndCode() { + _super.call(this, TypeScript.NodeType.EndCode); + } + return EndCode; + })(AST); + TypeScript.EndCode = EndCode; + var ForInStatement = (function (_super) { + __extends(ForInStatement, _super); + function ForInStatement(lval, obj) { + _super.call(this, TypeScript.NodeType.ForIn); + this.lval = lval; + this.obj = obj; + this.statement = new ASTSpan(); + if(this.lval && (this.lval.nodeType == TypeScript.NodeType.VarDecl)) { + (this.lval).varFlags |= TypeScript.VarFlags.AutoInit; + } + } + ForInStatement.prototype.isLoop = function () { + return true; + }; + ForInStatement.prototype.isFiltered = function () { + if(this.body) { + var singleItem = null; + if(this.body.nodeType == TypeScript.NodeType.List) { + var stmts = this.body; + if(stmts.members.length == 1) { + singleItem = stmts.members[0]; + } + } else { + singleItem = this.body; + } + if(singleItem !== null) { + if(singleItem.nodeType == TypeScript.NodeType.Block) { + var block = singleItem; + if((block.statements !== null) && (block.statements.members.length == 1)) { + singleItem = block.statements.members[0]; + } + } + if(singleItem.nodeType == TypeScript.NodeType.If) { + var cond = (singleItem).cond; + if(cond.nodeType == TypeScript.NodeType.Call) { + var target = (cond).target; + if(target.nodeType == TypeScript.NodeType.Dot) { + var binex = target; + if((binex.operand1.nodeType == TypeScript.NodeType.Name) && (this.obj.nodeType == TypeScript.NodeType.Name) && ((binex.operand1).actualText == (this.obj).actualText)) { + var prop = binex.operand2; + if(prop.actualText == "hasOwnProperty") { + var args = (cond).arguments; + if((args !== null) && (args.members.length == 1)) { + var arg = args.members[0]; + if((arg.nodeType == TypeScript.NodeType.Name) && (this.lval.nodeType == TypeScript.NodeType.Name)) { + if(((this.lval).actualText) == (arg).actualText) { + return true; + } + } + } + } + } + } + } + } + } + } + return false; + }; + ForInStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + emitter.recordSourceMappingStart(this.statement); + emitter.writeToOutput("for("); + emitter.emitJavascript(this.lval, TypeScript.TokenID.For, false); + emitter.writeToOutput(" in "); + emitter.emitJavascript(this.obj, TypeScript.TokenID.For, false); + emitter.writeToOutput(")"); + emitter.recordSourceMappingEnd(this.statement); + emitter.emitJavascriptStatements(this.body, true); + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + ForInStatement.prototype.typeCheck = function (typeFlow) { + if(typeFlow.checker.styleSettings.forin) { + if(!this.isFiltered()) { + typeFlow.checker.errorReporter.styleError(this, "no hasOwnProperty filter"); + } + } + return typeFlow.typeCheckForIn(this); + }; + ForInStatement.prototype.addToControlFlow = function (context) { + if(this.lval) { + context.addContent(this.lval); + } + if(this.obj) { + context.addContent(this.obj); + } + var loopHeader = context.current; + var loopStart = new TypeScript.BasicBlock(); + var afterLoop = new TypeScript.BasicBlock(); + loopHeader.addSuccessor(loopStart); + context.current = loopStart; + if(this.body) { + context.pushStatement(this, loopStart, afterLoop); + context.walk(this.body, this); + context.popStatement(); + } + if(!(context.noContinuation)) { + var loopEnd = context.current; + loopEnd.addSuccessor(loopStart); + } + context.current = afterLoop; + context.noContinuation = false; + loopHeader.addSuccessor(afterLoop); + context.walker.options.goChildren = false; + }; + return ForInStatement; + })(Statement); + TypeScript.ForInStatement = ForInStatement; + var ForStatement = (function (_super) { + __extends(ForStatement, _super); + function ForStatement(init) { + _super.call(this, TypeScript.NodeType.For); + this.init = init; + } + ForStatement.prototype.isLoop = function () { + return true; + }; + ForStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + emitter.writeToOutput("for("); + if(this.init) { + if(this.init.nodeType != TypeScript.NodeType.List) { + emitter.emitJavascript(this.init, TypeScript.TokenID.For, false); + } else { + emitter.setInVarBlock((this.init).members.length); + emitter.emitJavascriptList(this.init, null, TypeScript.TokenID.For, false, false, false); + } + } + emitter.writeToOutput("; "); + emitter.emitJavascript(this.cond, TypeScript.TokenID.For, false); + emitter.writeToOutput("; "); + emitter.emitJavascript(this.incr, TypeScript.TokenID.For, false); + emitter.writeToOutput(")"); + emitter.emitJavascriptStatements(this.body, true); + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + ForStatement.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckFor(this); + }; + ForStatement.prototype.addToControlFlow = function (context) { + if(this.init) { + context.addContent(this.init); + } + var loopHeader = context.current; + var loopStart = new TypeScript.BasicBlock(); + var afterLoop = new TypeScript.BasicBlock(); + loopHeader.addSuccessor(loopStart); + context.current = loopStart; + var condBlock = null; + var continueTarget = loopStart; + var incrBB = null; + if(this.incr) { + incrBB = new TypeScript.BasicBlock(); + continueTarget = incrBB; + } + if(this.cond) { + condBlock = context.current; + context.addContent(this.cond); + context.current = new TypeScript.BasicBlock(); + condBlock.addSuccessor(context.current); + } + var targetInfo = null; + if(this.body) { + context.pushStatement(this, continueTarget, afterLoop); + context.walk(this.body, this); + targetInfo = context.popStatement(); + } + if(this.incr) { + if(context.noContinuation) { + if(incrBB.predecessors.length == 0) { + context.addUnreachable(this.incr); + } + } else { + context.current.addSuccessor(incrBB); + context.current = incrBB; + context.addContent(this.incr); + } + } + var loopEnd = context.current; + if(!(context.noContinuation)) { + loopEnd.addSuccessor(loopStart); + } + if(condBlock) { + condBlock.addSuccessor(afterLoop); + context.noContinuation = false; + } + if(afterLoop.predecessors.length > 0) { + context.noContinuation = false; + context.current = afterLoop; + } + context.walker.options.goChildren = false; + }; + return ForStatement; + })(Statement); + TypeScript.ForStatement = ForStatement; + var WithStatement = (function (_super) { + __extends(WithStatement, _super); + function WithStatement(expr) { + _super.call(this, TypeScript.NodeType.With); + this.expr = expr; + this.withSym = null; + } + WithStatement.prototype.isCompoundStatement = function () { + return true; + }; + WithStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("with ("); + if(this.expr) { + emitter.emitJavascript(this.expr, TypeScript.TokenID.With, false); + } + emitter.writeToOutput(")"); + emitter.emitJavascriptStatements(this.body, true); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + WithStatement.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckWith(this); + }; + return WithStatement; + })(Statement); + TypeScript.WithStatement = WithStatement; + var SwitchStatement = (function (_super) { + __extends(SwitchStatement, _super); + function SwitchStatement(val) { + _super.call(this, TypeScript.NodeType.Switch); + this.val = val; + this.defaultCase = null; + this.statement = new ASTSpan(); + } + SwitchStatement.prototype.isCompoundStatement = function () { + return true; + }; + SwitchStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + emitter.recordSourceMappingStart(this.statement); + emitter.writeToOutput("switch("); + emitter.emitJavascript(this.val, TypeScript.TokenID.Identifier, false); + emitter.writeToOutput(")"); + emitter.recordSourceMappingEnd(this.statement); + emitter.writeLineToOutput(" {"); + emitter.indenter.increaseIndent(); + var casesLen = this.caseList.members.length; + for(var i = 0; i < casesLen; i++) { + var caseExpr = this.caseList.members[i]; + emitter.emitJavascript(caseExpr, TypeScript.TokenID.Case, true); + } + emitter.indenter.decreaseIndent(); + emitter.emitIndent(); + emitter.writeToOutput("}"); + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + SwitchStatement.prototype.typeCheck = function (typeFlow) { + var len = this.caseList.members.length; + this.val = typeFlow.typeCheck(this.val); + for(var i = 0; i < len; i++) { + this.caseList.members[i] = typeFlow.typeCheck(this.caseList.members[i]); + } + this.defaultCase = typeFlow.typeCheck(this.defaultCase); + this.type = typeFlow.voidType; + return this; + }; + SwitchStatement.prototype.addToControlFlow = function (context) { + var condBlock = context.current; + context.addContent(this.val); + var execBlock = new TypeScript.BasicBlock(); + var afterSwitch = new TypeScript.BasicBlock(); + condBlock.addSuccessor(execBlock); + context.pushSwitch(execBlock); + context.current = execBlock; + context.pushStatement(this, execBlock, afterSwitch); + context.walk(this.caseList, this); + context.popSwitch(); + var targetInfo = context.popStatement(); + var hasCondContinuation = (this.defaultCase == null); + if(this.defaultCase == null) { + condBlock.addSuccessor(afterSwitch); + } + if(afterSwitch.predecessors.length > 0) { + context.noContinuation = false; + context.current = afterSwitch; + } else { + context.noContinuation = true; + } + context.walker.options.goChildren = false; + }; + return SwitchStatement; + })(Statement); + TypeScript.SwitchStatement = SwitchStatement; + var CaseStatement = (function (_super) { + __extends(CaseStatement, _super); + function CaseStatement() { + _super.call(this, TypeScript.NodeType.Case); + this.expr = null; + } + CaseStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + if(this.expr) { + emitter.writeToOutput("case "); + emitter.emitJavascript(this.expr, TypeScript.TokenID.Identifier, false); + } else { + emitter.writeToOutput("default"); + } + emitter.writeToOutput(":"); + if(this.body.members.length == 1 && this.body.members[0].nodeType == TypeScript.NodeType.Block) { + emitter.emitJavascriptStatements(this.body, false); + } else { + emitter.writeLineToOutput(""); + emitter.indenter.increaseIndent(); + emitter.emitBareJavascriptStatements(this.body); + emitter.indenter.decreaseIndent(); + } + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + CaseStatement.prototype.typeCheck = function (typeFlow) { + this.expr = typeFlow.typeCheck(this.expr); + typeFlow.typeCheck(this.body); + this.type = typeFlow.voidType; + return this; + }; + CaseStatement.prototype.addToControlFlow = function (context) { + var execBlock = new TypeScript.BasicBlock(); + var sw = context.currentSwitch[context.currentSwitch.length - 1]; + if(this.expr) { + var exprBlock = new TypeScript.BasicBlock(); + context.current = exprBlock; + sw.addSuccessor(exprBlock); + context.addContent(this.expr); + exprBlock.addSuccessor(execBlock); + } else { + sw.addSuccessor(execBlock); + } + context.current = execBlock; + if(this.body) { + context.walk(this.body, this); + } + context.noContinuation = false; + context.walker.options.goChildren = false; + }; + return CaseStatement; + })(Statement); + TypeScript.CaseStatement = CaseStatement; + var TypeReference = (function (_super) { + __extends(TypeReference, _super); + function TypeReference(term, arrayCount) { + _super.call(this, TypeScript.NodeType.TypeRef); + this.term = term; + this.arrayCount = arrayCount; + } + TypeReference.prototype.emit = function (emitter, tokenId, startLine) { + throw new Error("should not emit a type ref"); + }; + TypeReference.prototype.typeCheck = function (typeFlow) { + var prevInTCTR = typeFlow.inTypeRefTypeCheck; + typeFlow.inTypeRefTypeCheck = true; + var typeLink = TypeScript.getTypeLink(this, typeFlow.checker, true); + typeFlow.checker.resolveTypeLink(typeFlow.scope, typeLink, false); + if(this.term) { + typeFlow.typeCheck(this.term); + } + typeFlow.checkForVoidConstructor(typeLink.type, this); + this.type = typeLink.type; + if(this.term) { + this.term.type = this.type; + } + typeFlow.inTypeRefTypeCheck = prevInTCTR; + return this; + }; + return TypeReference; + })(AST); + TypeScript.TypeReference = TypeReference; + var TryFinally = (function (_super) { + __extends(TryFinally, _super); + function TryFinally(tryNode, finallyNode) { + _super.call(this, TypeScript.NodeType.TryFinally); + this.tryNode = tryNode; + this.finallyNode = finallyNode; + } + TryFinally.prototype.isCompoundStatement = function () { + return true; + }; + TryFinally.prototype.emit = function (emitter, tokenId, startLine) { + emitter.recordSourceMappingStart(this); + emitter.emitJavascript(this.tryNode, TypeScript.TokenID.Try, false); + emitter.emitJavascript(this.finallyNode, TypeScript.TokenID.Finally, false); + emitter.recordSourceMappingEnd(this); + }; + TryFinally.prototype.typeCheck = function (typeFlow) { + this.tryNode = typeFlow.typeCheck(this.tryNode); + this.finallyNode = typeFlow.typeCheck(this.finallyNode); + this.type = typeFlow.voidType; + return this; + }; + TryFinally.prototype.addToControlFlow = function (context) { + var afterFinally = new TypeScript.BasicBlock(); + context.walk(this.tryNode, this); + var finBlock = new TypeScript.BasicBlock(); + if(context.current) { + context.current.addSuccessor(finBlock); + } + context.current = finBlock; + context.pushStatement(this, null, afterFinally); + context.walk(this.finallyNode, this); + if(!context.noContinuation && context.current) { + context.current.addSuccessor(afterFinally); + } + if(afterFinally.predecessors.length > 0) { + context.current = afterFinally; + } else { + context.noContinuation = true; + } + context.popStatement(); + context.walker.options.goChildren = false; + }; + return TryFinally; + })(Statement); + TypeScript.TryFinally = TryFinally; + var TryCatch = (function (_super) { + __extends(TryCatch, _super); + function TryCatch(tryNode, catchNode) { + _super.call(this, TypeScript.NodeType.TryCatch); + this.tryNode = tryNode; + this.catchNode = catchNode; + } + TryCatch.prototype.isCompoundStatement = function () { + return true; + }; + TryCatch.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.emitJavascript(this.tryNode, TypeScript.TokenID.Try, false); + emitter.emitJavascript(this.catchNode, TypeScript.TokenID.Catch, false); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + TryCatch.prototype.addToControlFlow = function (context) { + var beforeTry = context.current; + var tryBlock = new TypeScript.BasicBlock(); + beforeTry.addSuccessor(tryBlock); + context.current = tryBlock; + var afterTryCatch = new TypeScript.BasicBlock(); + context.pushStatement(this, null, afterTryCatch); + context.walk(this.tryNode, this); + if(!context.noContinuation) { + if(context.current) { + context.current.addSuccessor(afterTryCatch); + } + } + context.current = new TypeScript.BasicBlock(); + beforeTry.addSuccessor(context.current); + context.walk(this.catchNode, this); + context.popStatement(); + if(!context.noContinuation) { + if(context.current) { + context.current.addSuccessor(afterTryCatch); + } + } + context.current = afterTryCatch; + context.walker.options.goChildren = false; + }; + TryCatch.prototype.typeCheck = function (typeFlow) { + this.tryNode = typeFlow.typeCheck(this.tryNode); + this.catchNode = typeFlow.typeCheck(this.catchNode); + this.type = typeFlow.voidType; + return this; + }; + return TryCatch; + })(Statement); + TypeScript.TryCatch = TryCatch; + var Try = (function (_super) { + __extends(Try, _super); + function Try(body) { + _super.call(this, TypeScript.NodeType.Try); + this.body = body; + } + Try.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("try "); + emitter.emitJavascript(this.body, TypeScript.TokenID.Try, false); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + Try.prototype.typeCheck = function (typeFlow) { + this.body = typeFlow.typeCheck(this.body); + return this; + }; + Try.prototype.addToControlFlow = function (context) { + if(this.body) { + context.walk(this.body, this); + } + context.walker.options.goChildren = false; + context.noContinuation = false; + }; + return Try; + })(Statement); + TypeScript.Try = Try; + var Catch = (function (_super) { + __extends(Catch, _super); + function Catch(param, body) { + _super.call(this, TypeScript.NodeType.Catch); + this.param = param; + this.body = body; + this.statement = new ASTSpan(); + this.containedScope = null; + if(this.param) { + this.param.varFlags |= TypeScript.VarFlags.AutoInit; + } + } + Catch.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput(" "); + emitter.recordSourceMappingStart(this.statement); + emitter.writeToOutput("catch ("); + emitter.emitJavascript(this.param, TypeScript.TokenID.OpenParen, false); + emitter.writeToOutput(")"); + emitter.recordSourceMappingEnd(this.statement); + emitter.emitJavascript(this.body, TypeScript.TokenID.Catch, false); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + Catch.prototype.addToControlFlow = function (context) { + if(this.param) { + context.addContent(this.param); + var bodBlock = new TypeScript.BasicBlock(); + context.current.addSuccessor(bodBlock); + context.current = bodBlock; + } + if(this.body) { + context.walk(this.body, this); + } + context.noContinuation = false; + context.walker.options.goChildren = false; + }; + Catch.prototype.typeCheck = function (typeFlow) { + var prevScope = typeFlow.scope; + typeFlow.scope = this.containedScope; + this.param = typeFlow.typeCheck(this.param); + var exceptVar = new TypeScript.ValueLocation(); + var varSym = new TypeScript.VariableSymbol((this.param).id.text, this.param.minChar, typeFlow.checker.locationInfo.unitIndex, exceptVar); + exceptVar.symbol = varSym; + exceptVar.typeLink = new TypeScript.TypeLink(); + exceptVar.typeLink.type = typeFlow.anyType; + var thisFnc = typeFlow.thisFnc; + if(thisFnc && thisFnc.type) { + exceptVar.symbol.container = thisFnc.type.symbol; + } else { + exceptVar.symbol.container = null; + } + this.param.sym = exceptVar.symbol; + typeFlow.scope.enter(exceptVar.symbol.container, this.param, exceptVar.symbol, typeFlow.checker.errorReporter, false, false, false); + this.body = typeFlow.typeCheck(this.body); + if(typeFlow.checker.inProvisionalTypecheckMode()) { + var table = typeFlow.scope.getTable(); + (table).secondaryTable.table[exceptVar.symbol.name] = undefined; + } + this.type = typeFlow.voidType; + typeFlow.scope = prevScope; + return this; + }; + return Catch; + })(Statement); + TypeScript.Catch = Catch; + var Finally = (function (_super) { + __extends(Finally, _super); + function Finally(body) { + _super.call(this, TypeScript.NodeType.Finally); + this.body = body; + } + Finally.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("finally"); + emitter.emitJavascript(this.body, TypeScript.TokenID.Finally, false); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + Finally.prototype.addToControlFlow = function (context) { + if(this.body) { + context.walk(this.body, this); + } + context.walker.options.goChildren = false; + context.noContinuation = false; + }; + Finally.prototype.typeCheck = function (typeFlow) { + this.body = typeFlow.typeCheck(this.body); + return this; + }; + return Finally; + })(Statement); + TypeScript.Finally = Finally; + var Comment = (function (_super) { + __extends(Comment, _super); + function Comment(content, isBlockComment, endsLine) { + _super.call(this, TypeScript.NodeType.Comment); + this.content = content; + this.isBlockComment = isBlockComment; + this.endsLine = endsLine; + this.text = null; + this.docCommentText = null; + } + Comment.prototype.getText = function () { + if(this.text == null) { + if(this.isBlockComment) { + this.text = this.content.split("\n"); + for(var i = 0; i < this.text.length; i++) { + this.text[i] = this.text[i].replace(/^\s+|\s+$/g, ''); + } + } else { + this.text = [ + (this.content.replace(/^\s+|\s+$/g, '')) + ]; + } + } + return this.text; + }; + Comment.prototype.isDocComment = function () { + if(this.isBlockComment) { + return this.content.charAt(2) == "*"; + } + return false; + }; + Comment.prototype.getDocCommentText = function () { + if(this.docCommentText == null) { + this.docCommentText = Comment.cleanJSDocComment(this.content); + } + return this.docCommentText; + }; + Comment.consumeLeadingSpace = function consumeLeadingSpace(line, startIndex, maxSpacesToRemove) { + var endIndex = line.length; + if(maxSpacesToRemove != undefined) { + endIndex = TypeScript.min(startIndex + maxSpacesToRemove, endIndex); + } + for(; startIndex < endIndex; startIndex++) { + var charCode = line.charCodeAt(startIndex); + if(charCode != TypeScript.LexCodeSpace && charCode != TypeScript.LexCodeTAB) { + return startIndex; + } + } + if(endIndex != line.length) { + return endIndex; + } + return -1; + } + Comment.isSpaceChar = function isSpaceChar(line, index) { + var length = line.length; + if(index < length) { + var charCode = line.charCodeAt(index); + return charCode == TypeScript.LexCodeSpace || charCode == TypeScript.LexCodeTAB; + } + return index == length; + } + Comment.cleanDocCommentLine = function cleanDocCommentLine(line, jsDocStyleComment, jsDocLineSpaceToRemove) { + var nonSpaceIndex = Comment.consumeLeadingSpace(line, 0); + if(nonSpaceIndex != -1) { + var jsDocSpacesRemoved = nonSpaceIndex; + if(jsDocStyleComment && line.charAt(nonSpaceIndex) == '*') { + var startIndex = nonSpaceIndex + 1; + nonSpaceIndex = Comment.consumeLeadingSpace(line, startIndex, jsDocLineSpaceToRemove); + if(nonSpaceIndex != -1) { + jsDocSpacesRemoved = nonSpaceIndex - startIndex; + } else { + return null; + } + } + return { + minChar: nonSpaceIndex, + limChar: line.charAt(line.length - 1) == "\r" ? line.length - 1 : line.length, + jsDocSpacesRemoved: jsDocSpacesRemoved + }; + } + return null; + } + Comment.cleanJSDocComment = function cleanJSDocComment(content, spacesToRemove) { + var docCommentLines = []; + content = content.replace("/**", ""); + if(content.length >= 2 && content.charAt(content.length - 1) == "/" && content.charAt(content.length - 2) == "*") { + content = content.substring(0, content.length - 2); + } + var lines = content.split("\n"); + var inParamTag = false; + for(var l = 0; l < lines.length; l++) { + var line = lines[l]; + var cleanLinePos = Comment.cleanDocCommentLine(line, true, spacesToRemove); + if(!cleanLinePos) { + continue; + } + var docCommentText = ""; + var prevPos = cleanLinePos.minChar; + for(var i = line.indexOf("@", cleanLinePos.minChar); 0 <= i && i < cleanLinePos.limChar; i = line.indexOf("@", i + 1)) { + var wasInParamtag = inParamTag; + if(line.indexOf("param", i + 1) == i + 1 && Comment.isSpaceChar(line, i + 6)) { + if(!wasInParamtag) { + docCommentText += line.substring(prevPos, i); + } + prevPos = i; + inParamTag = true; + } else { + if(wasInParamtag) { + prevPos = i; + inParamTag = false; + } + } + } + if(!inParamTag) { + docCommentText += line.substring(prevPos, cleanLinePos.limChar); + } + var newCleanPos = Comment.cleanDocCommentLine(docCommentText, false); + if(newCleanPos) { + if(spacesToRemove == undefined) { + spacesToRemove = cleanLinePos.jsDocSpacesRemoved; + } + docCommentLines.push(docCommentText); + } + } + return docCommentLines.join("\n"); + } + Comment.getDocCommentText = function getDocCommentText(comments) { + var docCommentText = []; + for(var c = 0; c < comments.length; c++) { + var commentText = comments[c].getDocCommentText(); + if(commentText != "") { + docCommentText.push(commentText); + } + } + return docCommentText.join("\n"); + } + Comment.getParameterDocCommentText = function getParameterDocCommentText(param, fncDocComments) { + if(fncDocComments.length == 0 || !fncDocComments[0].isBlockComment) { + return ""; + } + for(var i = 0; i < fncDocComments.length; i++) { + var commentContents = fncDocComments[i].content; + for(var j = commentContents.indexOf("@param", 0); 0 <= j; j = commentContents.indexOf("@param", j)) { + j += 6; + if(!Comment.isSpaceChar(commentContents, j)) { + continue; + } + j = Comment.consumeLeadingSpace(commentContents, j); + if(j == -1) { + break; + } + if(commentContents.charCodeAt(j) == TypeScript.LexCodeLC) { + j++; + var charCode = 0; + for(var curlies = 1; j < commentContents.length; j++) { + charCode = commentContents.charCodeAt(j); + if(charCode == TypeScript.LexCodeLC) { + curlies++; + continue; + } + if(charCode == TypeScript.LexCodeRC) { + curlies--; + if(curlies == 0) { + break; + } else { + continue; + } + } + if(charCode == TypeScript.LexCodeAtSign) { + break; + } + } + if(j == commentContents.length) { + break; + } + if(charCode == TypeScript.LexCodeAtSign) { + continue; + } + j = Comment.consumeLeadingSpace(commentContents, j + 1); + if(j == -1) { + break; + } + } + if(param != commentContents.substr(j, param.length) || !Comment.isSpaceChar(commentContents, j + param.length)) { + continue; + } + j = Comment.consumeLeadingSpace(commentContents, j + param.length); + if(j == -1) { + return ""; + } + var endOfParam = commentContents.indexOf("@", j); + var paramHelpString = commentContents.substring(j, endOfParam < 0 ? commentContents.length : endOfParam); + var paramSpacesToRemove = undefined; + var paramLineIndex = commentContents.substring(0, j).lastIndexOf("\n") + 1; + if(paramLineIndex != 0) { + if(paramLineIndex < j && commentContents.charAt(paramLineIndex + 1) == "\r") { + paramLineIndex++; + } + } + var startSpaceRemovalIndex = Comment.consumeLeadingSpace(commentContents, paramLineIndex); + if(startSpaceRemovalIndex != j && commentContents.charAt(startSpaceRemovalIndex) == "*") { + paramSpacesToRemove = j - startSpaceRemovalIndex - 1; + } + return Comment.cleanJSDocComment(paramHelpString, paramSpacesToRemove); + } + } + return ""; + } + Comment.getDocCommentTextOfSignatures = function getDocCommentTextOfSignatures(signatures) { + var comments = []; + for(var i = 0; i < signatures.length; i++) { + var signatureDocComment = TypeScript.Comment.getDocCommentText(signatures[i].declAST.getDocComments()); + if(signatureDocComment != "") { + comments.push(signatureDocComment); + } + } + return comments.join("\n"); + } + return Comment; + })(AST); + TypeScript.Comment = Comment; + var DebuggerStatement = (function (_super) { + __extends(DebuggerStatement, _super); + function DebuggerStatement() { + _super.call(this, TypeScript.NodeType.Debugger); + } + DebuggerStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeLineToOutput("debugger;"); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return DebuggerStatement; + })(Statement); + TypeScript.DebuggerStatement = DebuggerStatement; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var AstWalkOptions = (function () { + function AstWalkOptions() { + this.goChildren = true; + this.goNextSibling = true; + this.reverseSiblings = false; + } + AstWalkOptions.prototype.stopWalk = function (stop) { + if (typeof stop === "undefined") { stop = true; } + this.goChildren = !stop; + this.goNextSibling = !stop; + }; + return AstWalkOptions; + })(); + TypeScript.AstWalkOptions = AstWalkOptions; + var AstWalker = (function () { + function AstWalker(childrenWalkers, pre, post, options, state) { + this.childrenWalkers = childrenWalkers; + this.pre = pre; + this.post = post; + this.options = options; + this.state = state; + } + AstWalker.prototype.walk = function (ast, parent) { + var preAst = this.pre(ast, parent, this); + if(preAst === undefined) { + preAst = ast; + } + if(this.options.goChildren) { + var svGoSib = this.options.goNextSibling; + this.options.goNextSibling = true; + this.childrenWalkers[ast.nodeType](ast, parent, this); + this.options.goNextSibling = svGoSib; + } else { + this.options.goChildren = true; + } + if(this.post) { + var postAst = this.post(preAst, parent, this); + if(postAst === undefined) { + postAst = preAst; + } + return postAst; + } else { + return preAst; + } + }; + return AstWalker; + })(); + var AstWalkerFactory = (function () { + function AstWalkerFactory() { + this.childrenWalkers = []; + this.initChildrenWalkers(); + } + AstWalkerFactory.prototype.walk = function (ast, pre, post, options, state) { + return this.getWalker(pre, post, options, state).walk(ast, null); + }; + AstWalkerFactory.prototype.getWalker = function (pre, post, options, state) { + return this.getSlowWalker(pre, post, options, state); + }; + AstWalkerFactory.prototype.getSlowWalker = function (pre, post, options, state) { + if(!options) { + options = new AstWalkOptions(); + } + return new AstWalker(this.childrenWalkers, pre, post, options, state); + }; + AstWalkerFactory.prototype.initChildrenWalkers = function () { + this.childrenWalkers[TypeScript.NodeType.None] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Empty] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.EmptyExpr] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.True] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.False] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.This] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Super] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.QString] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Regex] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Null] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.ArrayLit] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.ObjectLit] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Void] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Comma] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Pos] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Neg] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Delete] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Await] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.In] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Dot] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.From] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Is] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.InstOf] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Typeof] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.NumberLit] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Name] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.TypeRef] = ChildrenWalkers.walkTypeReferenceChildren; + this.childrenWalkers[TypeScript.NodeType.Index] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Call] = ChildrenWalkers.walkCallExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.New] = ChildrenWalkers.walkCallExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Asg] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgAdd] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgSub] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgDiv] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgMul] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgMod] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgAnd] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgXor] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgOr] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgLsh] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgRsh] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgRs2] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.ConditionalExpression] = ChildrenWalkers.walkTrinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.LogOr] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.LogAnd] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Or] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Xor] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.And] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Eq] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Ne] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Eqv] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.NEqv] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Lt] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Le] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Gt] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Ge] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Add] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Sub] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Mul] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Div] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Mod] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Lsh] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Rsh] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Rs2] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Not] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.LogNot] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.IncPre] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.DecPre] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.IncPost] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.DecPost] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.TypeAssertion] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.FuncDecl] = ChildrenWalkers.walkFuncDeclChildren; + this.childrenWalkers[TypeScript.NodeType.Member] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.VarDecl] = ChildrenWalkers.walkBoundDeclChildren; + this.childrenWalkers[TypeScript.NodeType.ArgDecl] = ChildrenWalkers.walkBoundDeclChildren; + this.childrenWalkers[TypeScript.NodeType.Return] = ChildrenWalkers.walkReturnStatementChildren; + this.childrenWalkers[TypeScript.NodeType.Break] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Continue] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Throw] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.For] = ChildrenWalkers.walkForStatementChildren; + this.childrenWalkers[TypeScript.NodeType.ForIn] = ChildrenWalkers.walkForInStatementChildren; + this.childrenWalkers[TypeScript.NodeType.If] = ChildrenWalkers.walkIfStatementChildren; + this.childrenWalkers[TypeScript.NodeType.While] = ChildrenWalkers.walkWhileStatementChildren; + this.childrenWalkers[TypeScript.NodeType.DoWhile] = ChildrenWalkers.walkDoWhileStatementChildren; + this.childrenWalkers[TypeScript.NodeType.Block] = ChildrenWalkers.walkBlockChildren; + this.childrenWalkers[TypeScript.NodeType.Case] = ChildrenWalkers.walkCaseStatementChildren; + this.childrenWalkers[TypeScript.NodeType.Switch] = ChildrenWalkers.walkSwitchStatementChildren; + this.childrenWalkers[TypeScript.NodeType.Try] = ChildrenWalkers.walkTryChildren; + this.childrenWalkers[TypeScript.NodeType.TryCatch] = ChildrenWalkers.walkTryCatchChildren; + this.childrenWalkers[TypeScript.NodeType.TryFinally] = ChildrenWalkers.walkTryFinallyChildren; + this.childrenWalkers[TypeScript.NodeType.Finally] = ChildrenWalkers.walkFinallyChildren; + this.childrenWalkers[TypeScript.NodeType.Catch] = ChildrenWalkers.walkCatchChildren; + this.childrenWalkers[TypeScript.NodeType.List] = ChildrenWalkers.walkListChildren; + this.childrenWalkers[TypeScript.NodeType.Script] = ChildrenWalkers.walkScriptChildren; + this.childrenWalkers[TypeScript.NodeType.ClassDeclaration] = ChildrenWalkers.walkClassDeclChildren; + this.childrenWalkers[TypeScript.NodeType.InterfaceDeclaration] = ChildrenWalkers.walkTypeDeclChildren; + this.childrenWalkers[TypeScript.NodeType.ModuleDeclaration] = ChildrenWalkers.walkModuleDeclChildren; + this.childrenWalkers[TypeScript.NodeType.ImportDeclaration] = ChildrenWalkers.walkImportDeclChildren; + this.childrenWalkers[TypeScript.NodeType.With] = ChildrenWalkers.walkWithStatementChildren; + this.childrenWalkers[TypeScript.NodeType.Label] = ChildrenWalkers.walkLabelChildren; + this.childrenWalkers[TypeScript.NodeType.LabeledStatement] = ChildrenWalkers.walkLabeledStatementChildren; + this.childrenWalkers[TypeScript.NodeType.EBStart] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.GotoEB] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.EndCode] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Error] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Comment] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Debugger] = ChildrenWalkers.walkNone; + for(var e in (TypeScript.NodeType)._map) { + if((this.childrenWalkers)[e] === undefined) { + throw new Error("initWalkers function is not up to date with enum content!"); + } + } + }; + return AstWalkerFactory; + })(); + TypeScript.AstWalkerFactory = AstWalkerFactory; + var globalAstWalkerFactory; + function getAstWalkerFactory() { + if(!globalAstWalkerFactory) { + globalAstWalkerFactory = new AstWalkerFactory(); + } + return globalAstWalkerFactory; + } + TypeScript.getAstWalkerFactory = getAstWalkerFactory; + var ChildrenWalkers; + (function (ChildrenWalkers) { + function walkNone(preAst, parent, walker) { + } + ChildrenWalkers.walkNone = walkNone; + function walkListChildren(preAst, parent, walker) { + var len = preAst.members.length; + if(walker.options.reverseSiblings) { + for(var i = len - 1; i >= 0; i--) { + if(walker.options.goNextSibling) { + preAst.members[i] = walker.walk(preAst.members[i], preAst); + } + } + } else { + for(var i = 0; i < len; i++) { + if(walker.options.goNextSibling) { + preAst.members[i] = walker.walk(preAst.members[i], preAst); + } + } + } + } + ChildrenWalkers.walkListChildren = walkListChildren; + function walkUnaryExpressionChildren(preAst, parent, walker) { + if(preAst.castTerm) { + preAst.castTerm = walker.walk(preAst.castTerm, preAst); + } + if(preAst.operand) { + preAst.operand = walker.walk(preAst.operand, preAst); + } + } + ChildrenWalkers.walkUnaryExpressionChildren = walkUnaryExpressionChildren; + function walkBinaryExpressionChildren(preAst, parent, walker) { + if(walker.options.reverseSiblings) { + if(preAst.operand2) { + preAst.operand2 = walker.walk(preAst.operand2, preAst); + } + if((preAst.operand1) && (walker.options.goNextSibling)) { + preAst.operand1 = walker.walk(preAst.operand1, preAst); + } + } else { + if(preAst.operand1) { + preAst.operand1 = walker.walk(preAst.operand1, preAst); + } + if((preAst.operand2) && (walker.options.goNextSibling)) { + preAst.operand2 = walker.walk(preAst.operand2, preAst); + } + } + } + ChildrenWalkers.walkBinaryExpressionChildren = walkBinaryExpressionChildren; + function walkTypeReferenceChildren(preAst, parent, walker) { + if(preAst.term) { + preAst.term = walker.walk(preAst.term, preAst); + } + } + ChildrenWalkers.walkTypeReferenceChildren = walkTypeReferenceChildren; + function walkCallExpressionChildren(preAst, parent, walker) { + if(!walker.options.reverseSiblings) { + preAst.target = walker.walk(preAst.target, preAst); + } + if(preAst.arguments && (walker.options.goNextSibling)) { + preAst.arguments = walker.walk(preAst.arguments, preAst); + } + if((walker.options.reverseSiblings) && (walker.options.goNextSibling)) { + preAst.target = walker.walk(preAst.target, preAst); + } + } + ChildrenWalkers.walkCallExpressionChildren = walkCallExpressionChildren; + function walkTrinaryExpressionChildren(preAst, parent, walker) { + if(preAst.operand1) { + preAst.operand1 = walker.walk(preAst.operand1, preAst); + } + if(preAst.operand2 && (walker.options.goNextSibling)) { + preAst.operand2 = walker.walk(preAst.operand2, preAst); + } + if(preAst.operand3 && (walker.options.goNextSibling)) { + preAst.operand3 = walker.walk(preAst.operand3, preAst); + } + } + ChildrenWalkers.walkTrinaryExpressionChildren = walkTrinaryExpressionChildren; + function walkFuncDeclChildren(preAst, parent, walker) { + if(preAst.name) { + preAst.name = walker.walk(preAst.name, preAst); + } + if(preAst.arguments && (preAst.arguments.members.length > 0) && (walker.options.goNextSibling)) { + preAst.arguments = walker.walk(preAst.arguments, preAst); + } + if(preAst.returnTypeAnnotation && (walker.options.goNextSibling)) { + preAst.returnTypeAnnotation = walker.walk(preAst.returnTypeAnnotation, preAst); + } + if(preAst.bod && (preAst.bod.members.length > 0) && (walker.options.goNextSibling)) { + preAst.bod = walker.walk(preAst.bod, preAst); + } + } + ChildrenWalkers.walkFuncDeclChildren = walkFuncDeclChildren; + function walkBoundDeclChildren(preAst, parent, walker) { + if(preAst.id) { + preAst.id = walker.walk(preAst.id, preAst); + } + if(preAst.init) { + preAst.init = walker.walk(preAst.init, preAst); + } + if((preAst.typeExpr) && (walker.options.goNextSibling)) { + preAst.typeExpr = walker.walk(preAst.typeExpr, preAst); + } + } + ChildrenWalkers.walkBoundDeclChildren = walkBoundDeclChildren; + function walkReturnStatementChildren(preAst, parent, walker) { + if(preAst.returnExpression) { + preAst.returnExpression = walker.walk(preAst.returnExpression, preAst); + } + } + ChildrenWalkers.walkReturnStatementChildren = walkReturnStatementChildren; + function walkForStatementChildren(preAst, parent, walker) { + if(preAst.init) { + preAst.init = walker.walk(preAst.init, preAst); + } + if(preAst.cond && walker.options.goNextSibling) { + preAst.cond = walker.walk(preAst.cond, preAst); + } + if(preAst.incr && walker.options.goNextSibling) { + preAst.incr = walker.walk(preAst.incr, preAst); + } + if(preAst.body && walker.options.goNextSibling) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkForStatementChildren = walkForStatementChildren; + function walkForInStatementChildren(preAst, parent, walker) { + preAst.lval = walker.walk(preAst.lval, preAst); + if(walker.options.goNextSibling) { + preAst.obj = walker.walk(preAst.obj, preAst); + } + if(preAst.body && (walker.options.goNextSibling)) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkForInStatementChildren = walkForInStatementChildren; + function walkIfStatementChildren(preAst, parent, walker) { + preAst.cond = walker.walk(preAst.cond, preAst); + if(preAst.thenBod && (walker.options.goNextSibling)) { + preAst.thenBod = walker.walk(preAst.thenBod, preAst); + } + if(preAst.elseBod && (walker.options.goNextSibling)) { + preAst.elseBod = walker.walk(preAst.elseBod, preAst); + } + } + ChildrenWalkers.walkIfStatementChildren = walkIfStatementChildren; + function walkWhileStatementChildren(preAst, parent, walker) { + preAst.cond = walker.walk(preAst.cond, preAst); + if(preAst.body && (walker.options.goNextSibling)) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkWhileStatementChildren = walkWhileStatementChildren; + function walkDoWhileStatementChildren(preAst, parent, walker) { + preAst.cond = walker.walk(preAst.cond, preAst); + if(preAst.body && (walker.options.goNextSibling)) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkDoWhileStatementChildren = walkDoWhileStatementChildren; + function walkBlockChildren(preAst, parent, walker) { + if(preAst.statements) { + preAst.statements = walker.walk(preAst.statements, preAst); + } + } + ChildrenWalkers.walkBlockChildren = walkBlockChildren; + function walkCaseStatementChildren(preAst, parent, walker) { + if(preAst.expr) { + preAst.expr = walker.walk(preAst.expr, preAst); + } + if(preAst.body && walker.options.goNextSibling) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkCaseStatementChildren = walkCaseStatementChildren; + function walkSwitchStatementChildren(preAst, parent, walker) { + if(preAst.val) { + preAst.val = walker.walk(preAst.val, preAst); + } + if((preAst.caseList) && walker.options.goNextSibling) { + preAst.caseList = walker.walk(preAst.caseList, preAst); + } + } + ChildrenWalkers.walkSwitchStatementChildren = walkSwitchStatementChildren; + function walkTryChildren(preAst, parent, walker) { + if(preAst.body) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkTryChildren = walkTryChildren; + function walkTryCatchChildren(preAst, parent, walker) { + if(preAst.tryNode) { + preAst.tryNode = walker.walk(preAst.tryNode, preAst); + } + if((preAst.catchNode) && walker.options.goNextSibling) { + preAst.catchNode = walker.walk(preAst.catchNode, preAst); + } + } + ChildrenWalkers.walkTryCatchChildren = walkTryCatchChildren; + function walkTryFinallyChildren(preAst, parent, walker) { + if(preAst.tryNode) { + preAst.tryNode = walker.walk(preAst.tryNode, preAst); + } + if(preAst.finallyNode && walker.options.goNextSibling) { + preAst.finallyNode = walker.walk(preAst.finallyNode, preAst); + } + } + ChildrenWalkers.walkTryFinallyChildren = walkTryFinallyChildren; + function walkFinallyChildren(preAst, parent, walker) { + if(preAst.body) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkFinallyChildren = walkFinallyChildren; + function walkCatchChildren(preAst, parent, walker) { + if(preAst.param) { + preAst.param = walker.walk(preAst.param, preAst); + } + if((preAst.body) && walker.options.goNextSibling) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkCatchChildren = walkCatchChildren; + function walkRecordChildren(preAst, parent, walker) { + preAst.name = walker.walk(preAst.name, preAst); + if(walker.options.goNextSibling && preAst.members) { + preAst.members = walker.walk(preAst.members, preAst); + } + } + ChildrenWalkers.walkRecordChildren = walkRecordChildren; + function walkNamedTypeChildren(preAst, parent, walker) { + walkRecordChildren(preAst, parent, walker); + } + ChildrenWalkers.walkNamedTypeChildren = walkNamedTypeChildren; + function walkClassDeclChildren(preAst, parent, walker) { + walkNamedTypeChildren(preAst, parent, walker); + if(walker.options.goNextSibling && preAst.extendsList) { + preAst.extendsList = walker.walk(preAst.extendsList, preAst); + } + if(walker.options.goNextSibling && preAst.implementsList) { + preAst.implementsList = walker.walk(preAst.implementsList, preAst); + } + } + ChildrenWalkers.walkClassDeclChildren = walkClassDeclChildren; + function walkScriptChildren(preAst, parent, walker) { + if(preAst.bod) { + preAst.bod = walker.walk(preAst.bod, preAst); + } + } + ChildrenWalkers.walkScriptChildren = walkScriptChildren; + function walkTypeDeclChildren(preAst, parent, walker) { + walkNamedTypeChildren(preAst, parent, walker); + if(walker.options.goNextSibling && preAst.extendsList) { + preAst.extendsList = walker.walk(preAst.extendsList, preAst); + } + if(walker.options.goNextSibling && preAst.implementsList) { + preAst.implementsList = walker.walk(preAst.implementsList, preAst); + } + } + ChildrenWalkers.walkTypeDeclChildren = walkTypeDeclChildren; + function walkModuleDeclChildren(preAst, parent, walker) { + walkRecordChildren(preAst, parent, walker); + } + ChildrenWalkers.walkModuleDeclChildren = walkModuleDeclChildren; + function walkImportDeclChildren(preAst, parent, walker) { + if(preAst.id) { + preAst.id = walker.walk(preAst.id, preAst); + } + if(preAst.alias) { + preAst.alias = walker.walk(preAst.alias, preAst); + } + } + ChildrenWalkers.walkImportDeclChildren = walkImportDeclChildren; + function walkWithStatementChildren(preAst, parent, walker) { + if(preAst.expr) { + preAst.expr = walker.walk(preAst.expr, preAst); + } + if(preAst.body && walker.options.goNextSibling) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkWithStatementChildren = walkWithStatementChildren; + function walkLabelChildren(preAst, parent, walker) { + } + ChildrenWalkers.walkLabelChildren = walkLabelChildren; + function walkLabeledStatementChildren(preAst, parent, walker) { + preAst.labels = walker.walk(preAst.labels, preAst); + if(walker.options.goNextSibling) { + preAst.stmt = walker.walk(preAst.stmt, preAst); + } + } + ChildrenWalkers.walkLabeledStatementChildren = walkLabeledStatementChildren; + })(ChildrenWalkers || (ChildrenWalkers = {})); +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (AstWalkerWithDetailCallback) { + function walk(script, callback) { + var pre = function (cur, parent) { + walker.options.goChildren = AstWalkerCallback(true, cur, callback); + return cur; + }; + var post = function (cur, parent) { + AstWalkerCallback(false, cur, callback); + return cur; + }; + var walker = TypeScript.getAstWalkerFactory().getWalker(pre, post); + walker.walk(script, null); + } + AstWalkerWithDetailCallback.walk = walk; + function AstWalkerCallback(pre, ast, callback) { + var nodeType = ast.nodeType; + var callbackString = (TypeScript.NodeType)._map[nodeType] + "Callback"; + if(callback[callbackString]) { + return callback[callbackString](pre, ast); + } + if(callback.DefaultCallback) { + return callback.DefaultCallback(pre, ast); + } + return true; + } + })(TypeScript.AstWalkerWithDetailCallback || (TypeScript.AstWalkerWithDetailCallback = {})); + var AstWalkerWithDetailCallback = TypeScript.AstWalkerWithDetailCallback; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + function lastOf(items) { + return (items === null || items.length === 0) ? null : items[items.length - 1]; + } + TypeScript.lastOf = lastOf; + function max(a, b) { + return a >= b ? a : b; + } + TypeScript.max = max; + function min(a, b) { + return a <= b ? a : b; + } + TypeScript.min = min; + var AstPath = (function () { + function AstPath() { + this.asts = []; + this.top = -1; + } + AstPath.reverseIndexOf = function reverseIndexOf(items, index) { + return (items === null || items.length <= index) ? null : items[items.length - index - 1]; + } + AstPath.prototype.clone = function () { + var clone = new AstPath(); + clone.asts = this.asts.map(function (value) { + return value; + }); + clone.top = this.top; + return clone; + }; + AstPath.prototype.pop = function () { + var head = this.ast(); + this.up(); + while(this.asts.length > this.count()) { + this.asts.pop(); + } + return head; + }; + AstPath.prototype.push = function (ast) { + while(this.asts.length > this.count()) { + this.asts.pop(); + } + this.top = this.asts.length; + this.asts.push(ast); + }; + AstPath.prototype.up = function () { + if(this.top <= -1) { + throw new Error("Invalid call to 'up'"); + } + this.top--; + }; + AstPath.prototype.down = function () { + if(this.top == this.ast.length - 1) { + throw new Error("Invalid call to 'down'"); + } + this.top++; + }; + AstPath.prototype.nodeType = function () { + if(this.ast() == null) { + return TypeScript.NodeType.None; + } + return this.ast().nodeType; + }; + AstPath.prototype.ast = function () { + return AstPath.reverseIndexOf(this.asts, this.asts.length - (this.top + 1)); + }; + AstPath.prototype.parent = function () { + return AstPath.reverseIndexOf(this.asts, this.asts.length - this.top); + }; + AstPath.prototype.count = function () { + return this.top + 1; + }; + AstPath.prototype.get = function (index) { + return this.asts[index]; + }; + AstPath.prototype.isNameOfClass = function () { + if(this.ast() === null || this.parent() === null) { + return false; + } + return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.ClassDeclaration) && ((this.parent()).name === this.ast()); + }; + AstPath.prototype.isNameOfInterface = function () { + if(this.ast() === null || this.parent() === null) { + return false; + } + return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.InterfaceDeclaration) && ((this.parent()).name === this.ast()); + }; + AstPath.prototype.isNameOfArgument = function () { + if(this.ast() === null || this.parent() === null) { + return false; + } + return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.ArgDecl) && ((this.parent()).id === this.ast()); + }; + AstPath.prototype.isNameOfVariable = function () { + if(this.ast() === null || this.parent() === null) { + return false; + } + return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.VarDecl) && ((this.parent()).id === this.ast()); + }; + AstPath.prototype.isNameOfModule = function () { + if(this.ast() === null || this.parent() === null) { + return false; + } + return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.ModuleDeclaration) && ((this.parent()).name === this.ast()); + }; + AstPath.prototype.isNameOfFunction = function () { + if(this.ast() === null || this.parent() === null) { + return false; + } + return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.FuncDecl) && ((this.parent()).name === this.ast()); + }; + AstPath.prototype.isChildOfScript = function () { + var ast = lastOf(this.asts); + return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.Script; + }; + AstPath.prototype.isChildOfModule = function () { + var ast = lastOf(this.asts); + return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.ModuleDeclaration; + }; + AstPath.prototype.isChildOfClass = function () { + var ast = lastOf(this.asts); + return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.ClassDeclaration; + }; + AstPath.prototype.isArgumentOfClassConstructor = function () { + var ast = lastOf(this.asts); + return this.count() >= 5 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.FuncDecl && this.asts[this.top - 3].nodeType === TypeScript.NodeType.List && this.asts[this.top - 4].nodeType === TypeScript.NodeType.ClassDeclaration && ((this.asts[this.top - 2]).isConstructor) && ((this.asts[this.top - 2]).arguments === this.asts[this.top - 1]) && ((this.asts[this.top - 4]).constructorDecl === this.asts[this.top - 2]); + }; + AstPath.prototype.isChildOfInterface = function () { + var ast = lastOf(this.asts); + return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.InterfaceDeclaration; + }; + AstPath.prototype.isTopLevelImplicitModule = function () { + return this.count() >= 1 && this.asts[this.top].nodeType === TypeScript.NodeType.ModuleDeclaration && TypeScript.hasFlag((this.asts[this.top]).modFlags, TypeScript.ModuleFlags.IsWholeFile); + }; + AstPath.prototype.isBodyOfTopLevelImplicitModule = function () { + return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ModuleDeclaration && (this.asts[this.top - 1]).members == this.asts[this.top - 0] && TypeScript.hasFlag((this.asts[this.top - 1]).modFlags, TypeScript.ModuleFlags.IsWholeFile); + }; + AstPath.prototype.isBodyOfScript = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Script && (this.asts[this.top - 1]).bod == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfSwitch = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Switch && (this.asts[this.top - 1]).caseList == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfModule = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ModuleDeclaration && (this.asts[this.top - 1]).members == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfClass = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ClassDeclaration && (this.asts[this.top - 1]).members == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfFunction = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.FuncDecl && (this.asts[this.top - 1]).bod == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfInterface = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.InterfaceDeclaration && (this.asts[this.top - 1]).members == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfBlock = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Block && (this.asts[this.top - 1]).statements == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfFor = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.For && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfCase = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Case && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfTry = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Try && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfCatch = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Catch && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfDoWhile = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.DoWhile && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfWhile = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.While && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfForIn = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ForIn && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfWith = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.With && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfFinally = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Finally && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + }; + AstPath.prototype.isCaseOfSwitch = function () { + return this.count() >= 3 && this.asts[this.top - 2].nodeType === TypeScript.NodeType.Switch && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 2]).caseList == this.asts[this.top - 1]; + }; + AstPath.prototype.isDefaultCaseOfSwitch = function () { + return this.count() >= 3 && this.asts[this.top - 2].nodeType === TypeScript.NodeType.Switch && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 2]).caseList == this.asts[this.top - 1] && (this.asts[this.top - 2]).defaultCase == this.asts[this.top - 0]; + }; + AstPath.prototype.isListOfObjectLit = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 1]).operand == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfObjectLit = function () { + return this.isListOfObjectLit(); + }; + AstPath.prototype.isEmptyListOfObjectLit = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 1]).operand == this.asts[this.top - 0] && (this.asts[this.top - 0]).members.length == 0; + }; + AstPath.prototype.isMemberOfObjectLit = function () { + return this.count() >= 3 && this.asts[this.top - 2].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 0].nodeType === TypeScript.NodeType.Member && (this.asts[this.top - 2]).operand == this.asts[this.top - 1]; + }; + AstPath.prototype.isNameOfMemberOfObjectLit = function () { + return this.count() >= 4 && this.asts[this.top - 3].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 2].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Member && this.asts[this.top - 0].nodeType === TypeScript.NodeType.Name && (this.asts[this.top - 3]).operand == this.asts[this.top - 2]; + }; + AstPath.prototype.isListOfArrayLit = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ArrayLit && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 1]).operand == this.asts[this.top - 0]; + }; + AstPath.prototype.isTargetOfMember = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Member && (this.asts[this.top - 1]).operand1 === this.asts[this.top - 0]; + }; + AstPath.prototype.isMemberOfMember = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Member && (this.asts[this.top - 1]).operand2 === this.asts[this.top - 0]; + }; + AstPath.prototype.isItemOfList = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List; + }; + AstPath.prototype.isThenOfIf = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.If && (this.asts[this.top - 1]).thenBod == this.asts[this.top - 0]; + }; + AstPath.prototype.isElseOfIf = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.If && (this.asts[this.top - 1]).elseBod == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfDefaultCase = function () { + return this.isBodyOfCase(); + }; + AstPath.prototype.isSingleStatementList = function () { + return this.count() >= 1 && this.asts[this.top].nodeType === TypeScript.NodeType.List && (this.asts[this.top]).members.length === 1; + }; + AstPath.prototype.isArgumentListOfFunction = function () { + return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.FuncDecl && (this.asts[this.top - 1]).arguments === this.asts[this.top - 0]; + }; + AstPath.prototype.isArgumentOfFunction = function () { + return this.count() >= 3 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.FuncDecl && (this.asts[this.top - 2]).arguments === this.asts[this.top - 1]; + }; + AstPath.prototype.isArgumentListOfCall = function () { + return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Call && (this.asts[this.top - 1]).arguments === this.asts[this.top - 0]; + }; + AstPath.prototype.isArgumentListOfNew = function () { + return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.New && (this.asts[this.top - 1]).arguments === this.asts[this.top - 0]; + }; + AstPath.prototype.isSynthesizedBlock = function () { + return this.count() >= 1 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.Block && (this.asts[this.top - 0]).isStatementBlock === false; + }; + return AstPath; + })(); + TypeScript.AstPath = AstPath; + function isValidAstNode(ast) { + if(ast === null) { + return false; + } + if(ast.minChar === -1 || ast.limChar === -1) { + return false; + } + return true; + } + TypeScript.isValidAstNode = isValidAstNode; + var AstPathContext = (function () { + function AstPathContext() { + this.path = new TypeScript.AstPath(); + } + return AstPathContext; + })(); + TypeScript.AstPathContext = AstPathContext; + (function (GetAstPathOptions) { + GetAstPathOptions._map = []; + GetAstPathOptions.Default = 0; + GetAstPathOptions.EdgeInclusive = 1; + GetAstPathOptions.DontPruneSearchBasedOnPosition = 1 << 1; + })(TypeScript.GetAstPathOptions || (TypeScript.GetAstPathOptions = {})); + var GetAstPathOptions = TypeScript.GetAstPathOptions; + function getAstPathToPosition(script, pos, options) { + if (typeof options === "undefined") { options = GetAstPathOptions.Default; } + var lookInComments = function (comments) { + if(comments && comments.length > 0) { + for(var i = 0; i < comments.length; i++) { + var minChar = comments[i].minChar; + var limChar = comments[i].limChar; + if(!comments[i].isBlockComment) { + limChar++; + } + if(pos >= minChar && pos < limChar) { + ctx.path.push(comments[i]); + } + } + } + }; + var pre = function (cur, parent, walker) { + if(isValidAstNode(cur)) { + var inclusive = TypeScript.hasFlag(options, GetAstPathOptions.EdgeInclusive) || cur.nodeType === TypeScript.NodeType.Name || pos === script.limChar; + var minChar = cur.minChar; + var limChar = cur.limChar + (inclusive ? 1 : 0); + if(pos >= minChar && pos < limChar) { + var previous = ctx.path.ast(); + if(previous == null || (cur.minChar >= previous.minChar && cur.limChar <= previous.limChar)) { + ctx.path.push(cur); + } else { + } + } + if(pos < limChar) { + lookInComments(cur.preComments); + } + if(pos >= minChar) { + lookInComments(cur.postComments); + } + if(!TypeScript.hasFlag(options, GetAstPathOptions.DontPruneSearchBasedOnPosition)) { + walker.options.goChildren = (minChar <= pos && pos <= limChar); + } + } + return cur; + }; + var ctx = new AstPathContext(); + TypeScript.getAstWalkerFactory().walk(script, pre, null, null, ctx); + return ctx.path; + } + TypeScript.getAstPathToPosition = getAstPathToPosition; + function getTokenizationOffset(script, position) { + var bestOffset = 0; + var pre = function (cur, parent, walker) { + if(TypeScript.isValidAstNode(cur)) { + if(cur.minChar <= position) { + bestOffset = max(bestOffset, cur.minChar); + } + if(cur.minChar > position || cur.limChar < bestOffset) { + walker.options.goChildren = false; + } + } + return cur; + }; + TypeScript.getAstWalkerFactory().walk(script, pre); + return bestOffset; + } + TypeScript.getTokenizationOffset = getTokenizationOffset; + function walkAST(ast, callback) { + var pre = function (cur, parent, walker) { + var path = walker.state; + path.push(cur); + callback(path, walker); + return cur; + }; + var post = function (cur, parent, walker) { + var path = walker.state; + path.pop(); + return cur; + }; + var path = new AstPath(); + TypeScript.getAstWalkerFactory().walk(ast, pre, post, null, path); + } + TypeScript.walkAST = walkAST; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var AstLogger = (function () { + function AstLogger(logger) { + this.logger = logger; + } + AstLogger.prototype.logScript = function (script) { + var _this = this; + this.logLinemap(script.locationInfo.lineMap); + var stack = []; + var pre = function (cur, parent) { + stack.push(cur); + var indent = (stack.length - 1) * 2; + _this.logComments(script, cur.preComments, indent); + _this.logNode(script, cur, indent); + _this.logComments(script, cur.postComments, indent); + return cur; + }; + var post = function (cur, parent) { + stack.pop(); + return cur; + }; + TypeScript.getAstWalkerFactory().walk(script, pre, post); + }; + AstLogger.prototype.logNode = function (script, cur, indent) { + var msg = this.addPadding("", indent, "| ", true); + msg = msg.concat("+ " + cur.treeViewLabel()); + msg = this.addPadding(msg, 70, " ", false); + msg = msg + this.addLineColumn(script, cur.minChar); + msg = this.addPadding(msg, 80, " ", false); + msg = msg + "=> "; + msg = msg + this.addLineColumn(script, cur.limChar); + msg = this.addPadding(msg, 102, " ", false); + msg = msg.concat("[" + this.addPadding(cur.minChar.toString(), 1, " ", true) + ", " + this.addPadding(cur.limChar.toString(), 1, " ", true) + "]"); + msg = this.addPadding(msg, 115, " ", false); + msg = msg.concat("sym=" + (cur).sym); + msg = this.addPadding(msg, 135, " ", false); + msg = msg.concat("type=" + (cur.type === null ? "null" : cur.type.getTypeName())); + this.logger.log(msg); + }; + AstLogger.prototype.logComments = function (script, comments, indent) { + if(comments == null) { + return; + } + for(var i = 0; i < comments.length; i++) { + this.logNode(script, comments[i], indent); + } + }; + AstLogger.prototype.logLinemap = function (linemap) { + var result = "["; + for(var i = 0; i < linemap.length; i++) { + if(i > 0) { + result += ","; + } + result += linemap[i]; + } + result += "]"; + this.logger.log("linemap: " + result); + }; + AstLogger.prototype.addPadding = function (s, targetLength, paddingString, leftPadding) { + var result = (leftPadding ? "" : s); + for(var i = s.length; i < targetLength; i++) { + result = result + paddingString; + } + result = result + (leftPadding ? s : ""); + return result; + }; + AstLogger.prototype.addLineColumn = function (script, position) { + var lineInfo = { + line: -1, + col: -1 + }; + TypeScript.getSourceLineColFromMap(lineInfo, position, script.locationInfo.lineMap); + if(lineInfo.col !== -1) { + lineInfo.col++; + } + return "(" + lineInfo.line + ", " + lineInfo.col + ")"; + }; + return AstLogger; + })(); + TypeScript.AstLogger = AstLogger; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Binder = (function () { + function Binder(checker) { + this.checker = checker; + } + Binder.prototype.resolveBaseTypeLinks = function (typeLinks, scope) { + var extendsList = null; + if(typeLinks) { + extendsList = new Array(); + for(var i = 0, len = typeLinks.length; i < len; i++) { + extendsList[i] = this.checker.resolveBaseTypeLink(typeLinks[i], scope); + } + } + return extendsList; + }; + Binder.prototype.resolveBases = function (scope, type) { + type.extendsList = this.resolveBaseTypeLinks(type.extendsTypeLinks, scope); + var i = 0, len = type.extendsList.length; + var derivedIsClass = type.isClassInstance(); + for(; i < len; i++) { + var baseIsClass = type.extendsList[i].isClassInstance(); + if(type.extendsList[i] != this.checker.anyType) { + var baseRef = type.extendsTypeLinks[i].ast; + if(derivedIsClass) { + if(!baseIsClass) { + this.checker.errorReporter.simpleError(baseRef, "A class may only extend other classes, " + type.extendsList[i].symbol.fullName() + " is not a class."); + } + } else { + if(baseIsClass) { + this.checker.errorReporter.simpleError(baseRef, "An interface may only extend other interfaces, " + type.extendsList[i].symbol.fullName() + " is a class."); + } + } + } + } + type.implementsList = this.resolveBaseTypeLinks(type.implementsTypeLinks, scope); + if(type.implementsList) { + for(i = 0 , len = type.implementsList.length; i < len; i++) { + var iface = type.implementsList[i]; + var baseRef = type.implementsTypeLinks[i].ast; + if(iface.isClassInstance()) { + if(derivedIsClass) { + this.checker.errorReporter.simpleError(baseRef, "A class may only implement an interface; " + iface.symbol.fullName() + " is a class."); + } + } + } + } + }; + Binder.prototype.resolveSignatureGroup = function (signatureGroup, scope, instanceType) { + var supplyVar = !(signatureGroup.hasImplementation); + for(var i = 0, len = signatureGroup.signatures.length; i < len; i++) { + var signature = signatureGroup.signatures[i]; + if(instanceType) { + signature.returnType.type = instanceType; + } else { + this.checker.resolveTypeLink(scope, signature.returnType, supplyVar); + } + var paramLen = signature.parameters.length; + for(var j = 0; j < paramLen; j++) { + this.bindSymbol(scope, signature.parameters[j]); + } + if(signature.hasVariableArgList) { + var lastParam = signature.parameters[paramLen - 1]; + lastParam.argsOffset = paramLen - 1; + if(!lastParam.getType().isArray()) { + this.checker.errorReporter.simpleErrorFromSym(lastParam, "... parameter must have array type"); + lastParam.parameter.typeLink.type = this.checker.makeArrayType(lastParam.parameter.typeLink.type); + } + } + } + }; + Binder.prototype.bindType = function (scope, type, instanceType) { + if(instanceType) { + this.bindType(scope, instanceType, null); + } + if(type.hasMembers()) { + var members = type.members; + var ambientMembers = type.ambientMembers; + var typeMembers = type.getAllEnclosedTypes(); + var ambientTypeMembers = type.getAllAmbientEnclosedTypes(); + var memberScope = new TypeScript.SymbolTableScope(members, ambientMembers, typeMembers, ambientTypeMembers, type.symbol); + var agg = new TypeScript.SymbolAggregateScope(type.symbol); + var prevCurrentModDecl = this.checker.currentModDecl; + var prevBindStatus = this.checker.inBind; + agg.addParentScope(memberScope); + agg.addParentScope(scope); + if(type.isModuleType()) { + this.checker.currentModDecl = type.symbol.declAST; + this.checker.inBind = true; + } + if(members) { + this.bind(agg, type.members.allMembers); + } + if(typeMembers) { + this.bind(agg, typeMembers.allMembers); + } + if(ambientMembers) { + this.bind(agg, ambientMembers.allMembers); + } + if(ambientTypeMembers) { + this.bind(agg, ambientTypeMembers.allMembers); + } + this.checker.currentModDecl = prevCurrentModDecl; + this.checker.inBind = prevBindStatus; + } + if(type.extendsTypeLinks) { + this.resolveBases(scope, type); + } + if(type.construct) { + this.resolveSignatureGroup(type.construct, scope, instanceType); + } + if(type.call) { + this.resolveSignatureGroup(type.call, scope, null); + } + if(type.index) { + this.resolveSignatureGroup(type.index, scope, null); + } + if(type.elementType) { + this.bindType(scope, type.elementType, null); + } + }; + Binder.prototype.bindSymbol = function (scope, symbol) { + if(!symbol.bound) { + var prevLocationInfo = this.checker.locationInfo; + if((this.checker.units) && (symbol.unitIndex >= 0) && (symbol.unitIndex < this.checker.units.length)) { + this.checker.locationInfo = this.checker.units[symbol.unitIndex]; + } + switch(symbol.kind()) { + case TypeScript.SymbolKind.Type: { + if(symbol.flags & TypeScript.SymbolFlags.Bound) { + break; + } + var typeSymbol = symbol; + typeSymbol.flags |= TypeScript.SymbolFlags.Bound; + if(typeSymbol.aliasLink && !typeSymbol.type && typeSymbol.aliasLink.alias.nodeType == TypeScript.NodeType.Name) { + var modPath = (typeSymbol.aliasLink.alias).text; + var modSym = this.checker.findSymbolForDynamicModule(modPath, this.checker.locationInfo.filename, function (id) { + return scope.find(id, false, true); + }); + if(modSym) { + typeSymbol.type = modSym.getType(); + } + } + if(typeSymbol.type && typeSymbol.type != this.checker.gloModType) { + this.bindType(scope, typeSymbol.type, typeSymbol.instanceType); + if(typeSymbol.type.isModuleType()) { + for(var i = 0; i < typeSymbol.expansions.length; i++) { + this.bindType(scope, typeSymbol.expansions[i], typeSymbol.instanceType); + } + } + } + break; + + } + case TypeScript.SymbolKind.Field: { + this.checker.resolveTypeLink(scope, (symbol).field.typeLink, false); + break; + + } + case TypeScript.SymbolKind.Parameter: { + this.checker.resolveTypeLink(scope, (symbol).parameter.typeLink, true); + break; + + } + } + this.checker.locationInfo = prevLocationInfo; + } + symbol.bound = true; + }; + Binder.prototype.bind = function (scope, table) { + table.map(function (key, sym, binder) { + binder.bindSymbol(scope, sym); + }, this); + }; + return Binder; + })(); + TypeScript.Binder = Binder; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Base64Format = (function () { + function Base64Format() { } + Base64Format.encodedValues = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + Base64Format.encode = function encode(inValue) { + if(inValue < 64) { + return Base64Format.encodedValues.charAt(inValue); + } + throw TypeError(inValue + ": not a 64 based value"); + } + Base64Format.decodeChar = function decodeChar(inChar) { + if(inChar.length === 1) { + return Base64Format.encodedValues.indexOf(inChar); + } else { + throw TypeError('"' + inChar + '" must have length 1'); + } + } + return Base64Format; + })(); + var Base64VLQFormat = (function () { + function Base64VLQFormat() { } + Base64VLQFormat.encode = function encode(inValue) { + if(inValue < 0) { + inValue = ((-inValue) << 1) + 1; + } else { + inValue = inValue << 1; + } + var encodedStr = ""; + do { + var currentDigit = inValue & 31; + inValue = inValue >> 5; + if(inValue > 0) { + currentDigit = currentDigit | 32; + } + encodedStr = encodedStr + Base64Format.encode(currentDigit); + }while(inValue > 0) + return encodedStr; + } + Base64VLQFormat.decode = function decode(inString) { + var result = 0; + var negative = false; + var shift = 0; + for(var i = 0; i < inString.length; i++) { + var byte = Base64Format.decodeChar(inString[i]); + if(i === 0) { + if((byte & 1) === 1) { + negative = true; + } + result = (byte >> 1) & 15; + } else { + result = result | ((byte & 31) << shift); + } + shift += (i == 0) ? 4 : 5; + if((byte & 32) === 32) { + } else { + return { + value: negative ? -(result) : result, + rest: inString.substr(i + 1) + }; + } + } + throw new Error('Base64 value "' + inString + '" finished with a continuation bit'); + } + return Base64VLQFormat; + })(); + TypeScript.Base64VLQFormat = Base64VLQFormat; +})(TypeScript || (TypeScript = {})); +var JSON2 = { +}; +((function () { + 'use strict'; + function f(n) { + return n < 10 ? '0' + n : n; + } + if(typeof Date.prototype.toJSON !== 'function') { + Date.prototype.toJSON = function (key) { + return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; + }; + var strProto = String.prototype; + var numProto = Number.prototype; + numProto.JSON = strProto.JSON = (Boolean).prototype.toJSON = function (key) { + return this.valueOf(); + }; + } + var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { +'\b': '\\b', +'\t': '\\t', +'\n': '\\n', +'\f': '\\f', +'\r': '\\r', +'"': '\\"', +'\\': '\\\\' }, rep; + function quote(string) { + escapable.lastIndex = 0; + return escapable.test(string) ? '"' + string.replace(escapable, function (a) { + var c = meta[a]; + return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); + }) + '"' : '"' + string + '"'; + } + function str(key, holder) { + var i, k = null, v, length, mind = gap, partial, value = holder[key]; + if(value && typeof value === 'object' && typeof value.toJSON === 'function') { + value = value.toJSON(key); + } + if(typeof rep === 'function') { + value = rep.call(holder, key, value); + } + switch(typeof value) { + case 'string': { + return quote(value); + + } + case 'number': { + return isFinite(value) ? String(value) : 'null'; + + } + case 'boolean': + case 'null': { + return String(value); + + } + case 'object': { + if(!value) { + return 'null'; + } + gap += indent; + partial = []; + if(Object.prototype.toString.apply(value, []) === '[object Array]') { + length = value.length; + for(i = 0; i < length; i += 1) { + partial[i] = str(i, value) || 'null'; + } + v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; + gap = mind; + return v; + } + if(rep && typeof rep === 'object') { + length = rep.length; + for(i = 0; i < length; i += 1) { + if(typeof rep[i] === 'string') { + k = rep[i]; + v = str(k, value); + if(v) { + partial.push(quote(k) + (gap ? ': ' : ':') + v); + } + } + } + } else { + for(k in value) { + if(Object.prototype.hasOwnProperty.call(value, k)) { + v = str(k, value); + if(v) { + partial.push(quote(k) + (gap ? ': ' : ':') + v); + } + } + } + } + v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; + gap = mind; + return v; + + } + } + } + if(typeof JSON2.stringify !== 'function') { + JSON2.stringify = function (value, replacer, space) { + var i; + gap = ''; + indent = ''; + if(typeof space === 'number') { + for(i = 0; i < space; i += 1) { + indent += ' '; + } + } else { + if(typeof space === 'string') { + indent = space; + } + } + rep = replacer; + if(replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { + throw new Error('JSON.stringify'); + } + return str('', { + '': value + }); + }; + } + if(typeof JSON2.parse !== 'function') { + JSON2.parse = function (text, reviver) { + var j; + function walk(holder, key) { + var k = null, v, value = holder[key]; + if(value && typeof value === 'object') { + for(k in value) { + if(Object.prototype.hasOwnProperty.call(value, k)) { + v = walk(value, k); + if(v !== undefined) { + value[k] = v; + } else { + delete value[k]; + } + } + } + } + return reviver.call(holder, key, value); + } + text = String(text); + cx.lastIndex = 0; + if(cx.test(text)) { + text = text.replace(cx, function (a) { + return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); + }); + } + if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { + j = eval('(' + text + ')'); + return typeof reviver === 'function' ? walk({ + '': j + }, '') : j; + } + throw new SyntaxError('JSON.parse'); + }; + } +})()); +var TypeScript; +(function (TypeScript) { + var SourceMapPosition = (function () { + function SourceMapPosition() { } + return SourceMapPosition; + })(); + TypeScript.SourceMapPosition = SourceMapPosition; + var SourceMapping = (function () { + function SourceMapping() { + this.start = new SourceMapPosition(); + this.end = new SourceMapPosition(); + this.nameIndex = -1; + this.childMappings = []; + } + return SourceMapping; + })(); + TypeScript.SourceMapping = SourceMapping; + var SourceMapper = (function () { + function SourceMapper(tsFileName, jsFileName, jsFile, sourceMapOut, errorReporter) { + this.jsFile = jsFile; + this.sourceMapOut = sourceMapOut; + this.errorReporter = errorReporter; + this.sourceMappings = []; + this.currentMappings = []; + this.names = []; + this.currentNameIndex = []; + this.currentMappings.push(this.sourceMappings); + jsFileName = TypeScript.switchToForwardSlashes(jsFileName); + this.jsFileName = TypeScript.getPrettyName(jsFileName, false, true); + var removalIndex = jsFileName.lastIndexOf(this.jsFileName); + var fixedPath = jsFileName.substring(0, removalIndex); + this.tsFileName = TypeScript.getRelativePathToFixedPath(fixedPath, tsFileName); + } + SourceMapper.MapFileExtension = ".map"; + SourceMapper.EmitSourceMapping = function EmitSourceMapping(allSourceMappers) { + var sourceMapper = allSourceMappers[0]; + sourceMapper.jsFile.WriteLine("//@ sourceMappingURL=" + sourceMapper.jsFileName + SourceMapper.MapFileExtension); + var sourceMapOut = sourceMapper.sourceMapOut; + var mappingsString = ""; + var tsFiles = []; + var prevEmittedColumn = 0; + var prevEmittedLine = 0; + var prevSourceColumn = 0; + var prevSourceLine = 0; + var prevSourceIndex = 0; + var prevNameIndex = 0; + var namesList = []; + var namesCount = 0; + var emitComma = false; + var recordedPosition = null; + for(var sourceMapperIndex = 0; sourceMapperIndex < allSourceMappers.length; sourceMapperIndex++) { + sourceMapper = allSourceMappers[sourceMapperIndex]; + var currentSourceIndex = tsFiles.length; + tsFiles.push(sourceMapper.tsFileName); + if(sourceMapper.names.length > 0) { + namesList.push.apply(namesList, sourceMapper.names); + } + var recordSourceMapping = function (mappedPosition, nameIndex) { + if(recordedPosition != null && recordedPosition.emittedColumn == mappedPosition.emittedColumn && recordedPosition.emittedLine == mappedPosition.emittedLine) { + return; + } + if(prevEmittedLine !== mappedPosition.emittedLine) { + while(prevEmittedLine < mappedPosition.emittedLine) { + prevEmittedColumn = 0; + mappingsString = mappingsString + ";"; + prevEmittedLine++; + } + emitComma = false; + } else { + if(emitComma) { + mappingsString = mappingsString + ","; + } + } + mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(mappedPosition.emittedColumn - prevEmittedColumn); + prevEmittedColumn = mappedPosition.emittedColumn; + mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(currentSourceIndex - prevSourceIndex); + prevSourceIndex = currentSourceIndex; + mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(mappedPosition.sourceLine - 1 - prevSourceLine); + prevSourceLine = mappedPosition.sourceLine - 1; + mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(mappedPosition.sourceColumn - prevSourceColumn); + prevSourceColumn = mappedPosition.sourceColumn; + if(nameIndex >= 0) { + mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(namesCount + nameIndex - prevNameIndex); + prevNameIndex = namesCount + nameIndex; + } + emitComma = true; + recordedPosition = mappedPosition; + }; + var recordSourceMappingSiblings = function (sourceMappings) { + for(var i = 0; i < sourceMappings.length; i++) { + var sourceMapping = sourceMappings[i]; + recordSourceMapping(sourceMapping.start, sourceMapping.nameIndex); + recordSourceMappingSiblings(sourceMapping.childMappings); + recordSourceMapping(sourceMapping.end, sourceMapping.nameIndex); + } + }; + recordSourceMappingSiblings(sourceMapper.sourceMappings, -1); + namesCount = namesCount + sourceMapper.names.length; + } + if(mappingsString != "") { + sourceMapOut.Write(JSON2.stringify({ + version: 3, + file: sourceMapper.jsFileName, + sources: tsFiles, + names: namesList, + mappings: mappingsString + })); + } + try { + sourceMapOut.Close(); + } catch (ex) { + sourceMapper.errorReporter.emitterError(null, ex.message); + } + } + return SourceMapper; + })(); + TypeScript.SourceMapper = SourceMapper; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (EmitContainer) { + EmitContainer._map = []; + EmitContainer._map[0] = "Prog"; + EmitContainer.Prog = 0; + EmitContainer._map[1] = "Module"; + EmitContainer.Module = 1; + EmitContainer._map[2] = "DynamicModule"; + EmitContainer.DynamicModule = 2; + EmitContainer._map[3] = "Class"; + EmitContainer.Class = 3; + EmitContainer._map[4] = "Constructor"; + EmitContainer.Constructor = 4; + EmitContainer._map[5] = "Function"; + EmitContainer.Function = 5; + EmitContainer._map[6] = "Args"; + EmitContainer.Args = 6; + EmitContainer._map[7] = "Interface"; + EmitContainer.Interface = 7; + })(TypeScript.EmitContainer || (TypeScript.EmitContainer = {})); + var EmitContainer = TypeScript.EmitContainer; + var EmitState = (function () { + function EmitState() { + this.column = 0; + this.line = 0; + this.pretty = false; + this.inObjectLiteral = false; + this.container = EmitContainer.Prog; + } + return EmitState; + })(); + TypeScript.EmitState = EmitState; + var EmitOptions = (function () { + function EmitOptions(settings) { + this.ioHost = null; + this.outputMany = true; + this.commonDirectoryPath = ""; + this.minWhitespace = settings.minWhitespace; + this.propagateConstants = settings.propagateConstants; + this.emitComments = settings.emitComments; + this.outputOption = settings.outputOption; + } + EmitOptions.prototype.mapOutputFileName = function (fileName, extensionChanger) { + if(this.outputMany) { + var updatedFileName = fileName; + if(this.outputOption != "") { + updatedFileName = fileName.replace(this.commonDirectoryPath, ""); + updatedFileName = this.outputOption + updatedFileName; + } + return extensionChanger(updatedFileName, false); + } else { + return extensionChanger(this.outputOption, true); + } + }; + return EmitOptions; + })(); + TypeScript.EmitOptions = EmitOptions; + var Indenter = (function () { + function Indenter() { + this.indentAmt = 0; + } + Indenter.indentStep = 4; + Indenter.indentStepString = " "; + Indenter.indentStrings = []; + Indenter.prototype.increaseIndent = function () { + this.indentAmt += Indenter.indentStep; + }; + Indenter.prototype.decreaseIndent = function () { + this.indentAmt -= Indenter.indentStep; + }; + Indenter.prototype.getIndent = function () { + var indentString = Indenter.indentStrings[this.indentAmt]; + if(indentString === undefined) { + indentString = ""; + for(var i = 0; i < this.indentAmt; i = i + Indenter.indentStep) { + indentString += Indenter.indentStepString; + } + Indenter.indentStrings[this.indentAmt] = indentString; + } + return indentString; + }; + return Indenter; + })(); + TypeScript.Indenter = Indenter; + var Emitter = (function () { + function Emitter(checker, emittingFileName, outfile, emitOptions, errorReporter) { + this.checker = checker; + this.emittingFileName = emittingFileName; + this.outfile = outfile; + this.emitOptions = emitOptions; + this.errorReporter = errorReporter; + this.prologueEmitted = false; + this.thisClassNode = null; + this.thisFnc = null; + this.moduleDeclList = []; + this.moduleName = ""; + this.emitState = new EmitState(); + this.indenter = new Indenter(); + this.ambientModule = false; + this.modAliasId = null; + this.firstModAlias = null; + this.allSourceMappers = []; + this.sourceMapper = null; + this.captureThisStmtString = "var _this = this;"; + this.varListCountStack = [ + 0 + ]; + } + Emitter.prototype.setSourceMappings = function (mapper) { + this.allSourceMappers.push(mapper); + this.sourceMapper = mapper; + }; + Emitter.prototype.writeToOutput = function (s) { + this.outfile.Write(s); + this.emitState.column += s.length; + }; + Emitter.prototype.writeToOutputTrimmable = function (s) { + if(this.emitOptions.minWhitespace) { + s = s.replace(/[\s]*/g, ''); + } + this.writeToOutput(s); + }; + Emitter.prototype.writeLineToOutput = function (s) { + if(this.emitOptions.minWhitespace) { + this.writeToOutput(s); + var c = s.charCodeAt(s.length - 1); + if(!((c == TypeScript.LexCodeSpace) || (c == TypeScript.LexCodeSMC) || (c == TypeScript.LexCodeLBR))) { + this.writeToOutput(' '); + } + } else { + this.outfile.WriteLine(s); + this.emitState.column = 0; + this.emitState.line++; + } + }; + Emitter.prototype.writeCaptureThisStatement = function (ast) { + this.emitIndent(); + this.recordSourceMappingStart(ast); + this.writeToOutput(this.captureThisStmtString); + this.recordSourceMappingEnd(ast); + this.writeLineToOutput(""); + }; + Emitter.prototype.setInVarBlock = function (count) { + this.varListCountStack[this.varListCountStack.length - 1] = count; + }; + Emitter.prototype.setInObjectLiteral = function (val) { + var temp = this.emitState.inObjectLiteral; + this.emitState.inObjectLiteral = val; + return temp; + }; + Emitter.prototype.setContainer = function (c) { + var temp = this.emitState.container; + this.emitState.container = c; + return temp; + }; + Emitter.prototype.getIndentString = function () { + if(this.emitOptions.minWhitespace) { + return ""; + } else { + return this.indenter.getIndent(); + } + }; + Emitter.prototype.emitIndent = function () { + this.writeToOutput(this.getIndentString()); + }; + Emitter.prototype.emitCommentInPlace = function (comment) { + this.recordSourceMappingStart(comment); + var text = comment.getText(); + var hadNewLine = false; + if(comment.isBlockComment) { + if(this.emitState.column == 0) { + this.emitIndent(); + } + this.writeToOutput(text[0]); + if(text.length > 1 || comment.endsLine) { + this.writeLineToOutput(""); + for(var i = 1; i < text.length; i++) { + this.emitIndent(); + this.writeLineToOutput(text[i]); + } + hadNewLine = true; + } + } else { + if(this.emitState.column == 0) { + this.emitIndent(); + } + this.writeLineToOutput(text[0]); + hadNewLine = true; + } + if(hadNewLine) { + this.emitIndent(); + } else { + this.writeToOutput(" "); + } + this.recordSourceMappingEnd(comment); + }; + Emitter.prototype.emitParensAndCommentsInPlace = function (ast, pre) { + var comments = pre ? ast.preComments : ast.postComments; + if(ast.isParenthesized && !pre) { + this.writeToOutput(")"); + } + if(this.emitOptions.emitComments && comments && comments.length != 0) { + for(var i = 0; i < comments.length; i++) { + this.emitCommentInPlace(comments[i]); + } + } + if(ast.isParenthesized && pre) { + this.writeToOutput("("); + } + }; + Emitter.prototype.emitObjectLiteral = function (content) { + this.writeLineToOutput("{"); + this.indenter.increaseIndent(); + var inObjectLiteral = this.setInObjectLiteral(true); + this.emitJavascriptList(content, ",", TypeScript.TokenID.Comma, true, false, false); + this.setInObjectLiteral(inObjectLiteral); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeToOutput("}"); + }; + Emitter.prototype.emitArrayLiteral = function (content) { + this.writeToOutput("["); + if(content) { + this.writeLineToOutput(""); + this.indenter.increaseIndent(); + this.emitJavascriptList(content, ", ", TypeScript.TokenID.Comma, true, false, false); + this.indenter.decreaseIndent(); + this.emitIndent(); + } + this.writeToOutput("]"); + }; + Emitter.prototype.emitNew = function (target, args) { + this.writeToOutput("new "); + if(target.nodeType == TypeScript.NodeType.TypeRef) { + var typeRef = target; + if(typeRef.arrayCount) { + this.writeToOutput("Array()"); + } else { + this.emitJavascript(typeRef.term, TypeScript.TokenID.Tilde, false); + this.writeToOutput("()"); + } + } else { + this.emitJavascript(target, TypeScript.TokenID.Tilde, false); + this.recordSourceMappingStart(args); + this.writeToOutput("("); + this.emitJavascriptList(args, ", ", TypeScript.TokenID.Comma, false, false, false); + this.writeToOutput(")"); + this.recordSourceMappingEnd(args); + } + }; + Emitter.prototype.tryEmitConstant = function (dotExpr) { + if(!this.emitOptions.propagateConstants) { + return false; + } + var propertyName = dotExpr.operand2; + if(propertyName && propertyName.sym && propertyName.sym.isVariable()) { + if(TypeScript.hasFlag(propertyName.sym.flags, TypeScript.SymbolFlags.Constant)) { + if(propertyName.sym.declAST) { + var boundDecl = propertyName.sym.declAST; + if(boundDecl.init && (boundDecl.init.nodeType == TypeScript.NodeType.NumberLit)) { + var numLit = boundDecl.init; + this.writeToOutput(numLit.value.toString()); + var comment = " /* "; + comment += propertyName.actualText; + comment += " */ "; + this.writeToOutput(comment); + return true; + } + } + } + } + return false; + }; + Emitter.prototype.emitCall = function (callNode, target, args) { + if(!this.emitSuperCall(callNode)) { + if(!TypeScript.hasFlag(callNode.flags, TypeScript.ASTFlags.ClassBaseConstructorCall)) { + if(target.nodeType == TypeScript.NodeType.FuncDecl && !target.isParenthesized) { + this.writeToOutput("("); + } + if(callNode.target.nodeType == TypeScript.NodeType.Super && this.emitState.container == EmitContainer.Constructor) { + this.writeToOutput("_super.call"); + } else { + this.emitJavascript(target, TypeScript.TokenID.OpenParen, false); + } + if(target.nodeType == TypeScript.NodeType.FuncDecl && !target.isParenthesized) { + this.writeToOutput(")"); + } + this.recordSourceMappingStart(args); + this.writeToOutput("("); + if(callNode.target.nodeType == TypeScript.NodeType.Super && this.emitState.container == EmitContainer.Constructor) { + this.writeToOutput("this"); + if(args && args.members.length) { + this.writeToOutput(", "); + } + } + this.emitJavascriptList(args, ", ", TypeScript.TokenID.Comma, false, false, false); + this.writeToOutput(")"); + this.recordSourceMappingEnd(args); + } else { + this.indenter.decreaseIndent(); + this.indenter.decreaseIndent(); + var constructorCall = new TypeScript.ASTList(); + constructorCall.members[0] = callNode; + this.emitConstructorCalls(constructorCall, this.thisClassNode); + this.indenter.increaseIndent(); + this.indenter.increaseIndent(); + } + } + }; + Emitter.prototype.emitConstructorCalls = function (bases, classDecl) { + if(bases == null) { + return; + } + var basesLen = bases.members.length; + this.recordSourceMappingStart(classDecl); + for(var i = 0; i < basesLen; i++) { + var baseExpr = bases.members[i]; + var baseSymbol = null; + if(baseExpr.nodeType == TypeScript.NodeType.Call) { + baseSymbol = (baseExpr).target.type.symbol; + } else { + baseSymbol = baseExpr.type.symbol; + } + var baseName = baseSymbol.name; + if(baseSymbol.declModule != classDecl.type.symbol.declModule) { + baseName = baseSymbol.fullName(); + } + if(baseExpr.nodeType == TypeScript.NodeType.Call) { + this.emitIndent(); + this.writeToOutput("_super.call(this"); + var args = (baseExpr).arguments; + if(args && (args.members.length > 0)) { + this.writeToOutput(", "); + this.emitJavascriptList(args, ", ", TypeScript.TokenID.Comma, false, false, false); + } + this.writeToOutput(")"); + } else { + if(baseExpr.type && (baseExpr.type.isClassInstance())) { + this.emitIndent(); + this.writeToOutput(classDecl.name.actualText + "._super.constructor"); + this.writeToOutput(".call(this)"); + } + } + } + this.recordSourceMappingEnd(classDecl); + }; + Emitter.prototype.emitInnerFunction = function (funcDecl, printName, isMember, bases, hasSelfRef, classDecl) { + var isClassConstructor = funcDecl.isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod); + var hasNonObjectBaseType = isClassConstructor && TypeScript.hasFlag(this.thisClassNode.type.instanceType.typeFlags, TypeScript.TypeFlags.HasBaseType) && !TypeScript.hasFlag(this.thisClassNode.type.instanceType.typeFlags, TypeScript.TypeFlags.HasBaseTypeOfObject); + var classPropertiesMustComeAfterSuperCall = hasNonObjectBaseType && TypeScript.hasFlag((this.thisClassNode).varFlags, TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor); + var shouldParenthesize = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFunctionExpression) && !funcDecl.isParenthesized && !funcDecl.isAccessor() && (TypeScript.hasFlag(funcDecl.flags, TypeScript.ASTFlags.ExplicitSemicolon) || TypeScript.hasFlag(funcDecl.flags, TypeScript.ASTFlags.AutomaticSemicolon)); + this.emitParensAndCommentsInPlace(funcDecl, true); + if(shouldParenthesize) { + this.writeToOutput("("); + } + this.recordSourceMappingStart(funcDecl); + if(!(funcDecl.isAccessor() && (funcDecl.accessorSymbol).isObjectLitField)) { + this.writeToOutput("function "); + } + if(printName) { + var id = funcDecl.getNameText(); + if(id && !funcDecl.isAccessor()) { + if(funcDecl.name) { + this.recordSourceMappingStart(funcDecl.name); + } + this.writeToOutput(id); + if(funcDecl.name) { + this.recordSourceMappingEnd(funcDecl.name); + } + } + } + this.writeToOutput("("); + var argsLen = 0; + var i = 0; + var arg; + var defaultArgs = []; + if(funcDecl.arguments) { + var tempContainer = this.setContainer(EmitContainer.Args); + argsLen = funcDecl.arguments.members.length; + var printLen = argsLen; + if(funcDecl.variableArgList) { + printLen--; + } + for(i = 0; i < printLen; i++) { + arg = funcDecl.arguments.members[i]; + if(arg.init) { + defaultArgs.push(arg); + } + this.emitJavascript(arg, TypeScript.TokenID.OpenParen, false); + if(i < (printLen - 1)) { + this.writeToOutput(", "); + } + } + this.setContainer(tempContainer); + } + this.writeLineToOutput(") {"); + if(funcDecl.isConstructor) { + this.recordSourceMappingNameStart("constructor"); + } else { + if(funcDecl.isGetAccessor()) { + this.recordSourceMappingNameStart("get_" + funcDecl.getNameText()); + } else { + if(funcDecl.isSetAccessor()) { + this.recordSourceMappingNameStart("set_" + funcDecl.getNameText()); + } else { + this.recordSourceMappingNameStart(funcDecl.getNameText()); + } + } + } + this.indenter.increaseIndent(); + for(i = 0; i < defaultArgs.length; i++) { + var arg = defaultArgs[i]; + this.emitIndent(); + this.recordSourceMappingStart(arg); + this.writeToOutput("if (typeof " + arg.id.actualText + " === \"undefined\") { "); + this.recordSourceMappingStart(arg.id); + this.writeToOutput(arg.id.actualText); + this.recordSourceMappingEnd(arg.id); + this.writeToOutput(" = "); + this.emitJavascript(arg.init, TypeScript.TokenID.OpenParen, false); + this.writeLineToOutput("; }"); + this.recordSourceMappingEnd(arg); + } + if(funcDecl.isConstructor && ((funcDecl.classDecl).varFlags & TypeScript.VarFlags.MustCaptureThis)) { + this.writeCaptureThisStatement(funcDecl); + } + if(funcDecl.isConstructor && !classPropertiesMustComeAfterSuperCall) { + if(funcDecl.arguments) { + argsLen = funcDecl.arguments.members.length; + for(i = 0; i < argsLen; i++) { + arg = funcDecl.arguments.members[i]; + if((arg.varFlags & TypeScript.VarFlags.Property) != TypeScript.VarFlags.None) { + this.emitIndent(); + this.recordSourceMappingStart(arg); + this.recordSourceMappingStart(arg.id); + this.writeToOutput("this." + arg.id.actualText); + this.recordSourceMappingEnd(arg.id); + this.writeToOutput(" = "); + this.recordSourceMappingStart(arg.id); + this.writeToOutput(arg.id.actualText); + this.recordSourceMappingEnd(arg.id); + this.writeLineToOutput(";"); + this.recordSourceMappingEnd(arg); + } + } + } + if(!TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { + this.emitConstructorCalls(bases, classDecl); + } + } + if(hasSelfRef) { + this.writeCaptureThisStatement(funcDecl); + } + if(funcDecl.variableArgList) { + argsLen = funcDecl.arguments.members.length; + var lastArg = funcDecl.arguments.members[argsLen - 1]; + this.emitIndent(); + this.recordSourceMappingStart(lastArg); + this.writeToOutput("var "); + this.recordSourceMappingStart(lastArg.id); + this.writeToOutput(lastArg.id.actualText); + this.recordSourceMappingEnd(lastArg.id); + this.writeLineToOutput(" = [];"); + this.recordSourceMappingEnd(lastArg); + this.emitIndent(); + this.writeToOutput("for ("); + this.recordSourceMappingStart(lastArg); + this.writeToOutput("var _i = 0;"); + this.recordSourceMappingEnd(lastArg); + this.writeToOutput(" "); + this.recordSourceMappingStart(lastArg); + this.writeToOutput("_i < (arguments.length - " + (argsLen - 1) + ")"); + this.recordSourceMappingEnd(lastArg); + this.writeToOutput("; "); + this.recordSourceMappingStart(lastArg); + this.writeToOutput("_i++"); + this.recordSourceMappingEnd(lastArg); + this.writeLineToOutput(") {"); + this.indenter.increaseIndent(); + this.emitIndent(); + this.recordSourceMappingStart(lastArg); + this.writeToOutput(lastArg.id.actualText + "[_i] = arguments[_i + " + (argsLen - 1) + "];"); + this.recordSourceMappingEnd(lastArg); + this.writeLineToOutput(""); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeLineToOutput("}"); + } + if(funcDecl.isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod) && !classPropertiesMustComeAfterSuperCall) { + var nProps = (this.thisClassNode.members).members.length; + for(var i = 0; i < nProps; i++) { + if((this.thisClassNode.members).members[i].nodeType == TypeScript.NodeType.VarDecl) { + var varDecl = (this.thisClassNode.members).members[i]; + if(!TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static) && varDecl.init) { + this.emitIndent(); + this.emitJavascriptVarDecl(varDecl, TypeScript.TokenID.Tilde); + this.writeLineToOutput(""); + } + } + } + } + this.emitBareJavascriptStatements(funcDecl.bod, classPropertiesMustComeAfterSuperCall); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.recordSourceMappingStart(funcDecl.endingToken); + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(funcDecl.endingToken); + this.recordSourceMappingEnd(funcDecl); + if(shouldParenthesize) { + this.writeToOutput(")"); + } + this.recordSourceMappingEnd(funcDecl); + this.emitParensAndCommentsInPlace(funcDecl, false); + if(!isMember && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFunctionExpression) && (TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Definition) || funcDecl.isConstructor)) { + this.writeLineToOutput(""); + } else { + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFunctionExpression)) { + if(TypeScript.hasFlag(funcDecl.flags, TypeScript.ASTFlags.ExplicitSemicolon) || TypeScript.hasFlag(funcDecl.flags, TypeScript.ASTFlags.AutomaticSemicolon)) { + this.writeLineToOutput(";"); + } + } + } + }; + Emitter.prototype.emitJavascriptModule = function (moduleDecl) { + var modName = moduleDecl.name.actualText; + if(TypeScript.isTSFile(modName)) { + moduleDecl.name.setText(modName.substring(0, modName.length - 3)); + } else { + if(TypeScript.isSTRFile(modName)) { + moduleDecl.name.setText(modName.substring(0, modName.length - 4)); + } + } + if(!TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.Ambient)) { + var isDynamicMod = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsDynamic); + var prevOutFile = this.outfile; + var prevOutFileName = this.emittingFileName; + var prevAllSourceMappers = this.allSourceMappers; + var prevSourceMapper = this.sourceMapper; + var prevColumn = this.emitState.column; + var prevLine = this.emitState.line; + var temp = this.setContainer(EmitContainer.Module); + var svModuleName = this.moduleName; + var isExported = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.Exported); + this.moduleDeclList[this.moduleDeclList.length] = moduleDecl; + var isWholeFile = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsWholeFile); + this.moduleName = moduleDecl.name.actualText; + if(isDynamicMod) { + var tsModFileName = TypeScript.stripQuotes(moduleDecl.name.actualText); + var modFilePath = TypeScript.trimModName(tsModFileName) + ".js"; + modFilePath = this.emitOptions.mapOutputFileName(modFilePath, TypeScript.TypeScriptCompiler.mapToJSFileName); + if(this.emitOptions.ioHost) { + if(TypeScript.switchToForwardSlashes(modFilePath) != TypeScript.switchToForwardSlashes(this.emittingFileName)) { + this.emittingFileName = modFilePath; + var useUTF8InOutputfile = moduleDecl.containsUnicodeChar || (this.emitOptions.emitComments && moduleDecl.containsUnicodeCharInComment); + this.outfile = this.createFile(this.emittingFileName, useUTF8InOutputfile); + if(prevSourceMapper != null) { + this.allSourceMappers = []; + var sourceMappingFile = this.createFile(this.emittingFileName + TypeScript.SourceMapper.MapFileExtension, false); + this.setSourceMappings(new TypeScript.SourceMapper(tsModFileName, this.emittingFileName, this.outfile, sourceMappingFile, this.errorReporter)); + this.emitState.column = 0; + this.emitState.line = 0; + } + } else { + TypeScript.CompilerDiagnostics.assert(this.emitOptions.outputMany, "Cannot have dynamic modules compiling into single file"); + } + } + this.setContainer(EmitContainer.DynamicModule); + this.recordSourceMappingStart(moduleDecl); + if(TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { + var dependencyList = "[\"require\", \"exports\""; + var importList = "require, exports"; + var importStatement = null; + for(var i = 0; i < (moduleDecl.mod).importedModules.length; i++) { + importStatement = (moduleDecl.mod).importedModules[i]; + if(importStatement.id.sym && !(importStatement.id.sym).onlyReferencedAsTypeRef) { + if(i <= (moduleDecl.mod).importedModules.length - 1) { + dependencyList += ", "; + importList += ", "; + } + importList += "__" + importStatement.id.actualText + "__"; + dependencyList += importStatement.firstAliasedModToString(); + } + } + for(var i = 0; i < moduleDecl.amdDependencies.length; i++) { + dependencyList += ", \"" + moduleDecl.amdDependencies[i] + "\""; + } + dependencyList += "]"; + this.writeLineToOutput("define(" + dependencyList + "," + " function(" + importList + ") {"); + } else { + } + } else { + if(!isExported) { + this.recordSourceMappingStart(moduleDecl); + this.writeToOutput("var "); + this.recordSourceMappingStart(moduleDecl.name); + this.writeToOutput(this.moduleName); + this.recordSourceMappingEnd(moduleDecl.name); + this.writeLineToOutput(";"); + this.recordSourceMappingEnd(moduleDecl); + this.emitIndent(); + } + this.writeToOutput("("); + this.recordSourceMappingStart(moduleDecl); + this.writeToOutput("function ("); + this.recordSourceMappingStart(moduleDecl.name); + this.writeToOutput(this.moduleName); + this.recordSourceMappingEnd(moduleDecl.name); + this.writeLineToOutput(") {"); + } + if(!isWholeFile) { + this.recordSourceMappingNameStart(this.moduleName); + } + if(!isDynamicMod || TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { + this.indenter.increaseIndent(); + } + if(moduleDecl.modFlags & TypeScript.ModuleFlags.MustCaptureThis) { + this.writeCaptureThisStatement(moduleDecl); + } + this.emitJavascriptList(moduleDecl.members, null, TypeScript.TokenID.Semicolon, true, false, false); + if(!isDynamicMod || TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { + this.indenter.decreaseIndent(); + } + this.emitIndent(); + if(isDynamicMod) { + if(TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { + this.writeLineToOutput("})"); + } else { + } + if(!isWholeFile) { + this.recordSourceMappingNameEnd(); + } + this.recordSourceMappingEnd(moduleDecl); + if(this.outfile != prevOutFile) { + this.Close(); + if(prevSourceMapper != null) { + this.allSourceMappers = prevAllSourceMappers; + this.sourceMapper = prevSourceMapper; + this.emitState.column = prevColumn; + this.emitState.line = prevLine; + } + this.outfile = prevOutFile; + this.emittingFileName = prevOutFileName; + } + } else { + var containingMod = null; + if(moduleDecl.type && moduleDecl.type.symbol.container && moduleDecl.type.symbol.container.declAST) { + containingMod = moduleDecl.type.symbol.container.declAST; + } + var parentIsDynamic = containingMod && TypeScript.hasFlag(containingMod.modFlags, TypeScript.ModuleFlags.IsDynamic); + this.recordSourceMappingStart(moduleDecl.endingToken); + if(temp == EmitContainer.Prog && isExported) { + this.writeToOutput("}"); + if(!isWholeFile) { + this.recordSourceMappingNameEnd(); + } + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeLineToOutput(")(this." + this.moduleName + " || (this." + this.moduleName + " = {}));"); + } else { + if(isExported || temp == EmitContainer.Prog) { + var dotMod = svModuleName != "" ? (parentIsDynamic ? "exports" : svModuleName) + "." : svModuleName; + this.writeToOutput("}"); + if(!isWholeFile) { + this.recordSourceMappingNameEnd(); + } + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeLineToOutput(")(" + dotMod + this.moduleName + " || (" + dotMod + this.moduleName + " = {}));"); + } else { + if(!isExported && temp != EmitContainer.Prog) { + this.writeToOutput("}"); + if(!isWholeFile) { + this.recordSourceMappingNameEnd(); + } + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeLineToOutput(")(" + this.moduleName + " || (" + this.moduleName + " = {}));"); + } else { + this.writeToOutput("}"); + if(!isWholeFile) { + this.recordSourceMappingNameEnd(); + } + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeLineToOutput(")();"); + } + } + } + this.recordSourceMappingEnd(moduleDecl); + if(temp != EmitContainer.Prog && isExported) { + this.emitIndent(); + this.recordSourceMappingStart(moduleDecl); + if(parentIsDynamic) { + this.writeLineToOutput("var " + this.moduleName + " = exports." + this.moduleName + ";"); + } else { + this.writeLineToOutput("var " + this.moduleName + " = " + svModuleName + "." + this.moduleName + ";"); + } + this.recordSourceMappingEnd(moduleDecl); + } + } + this.setContainer(temp); + this.moduleName = svModuleName; + this.moduleDeclList.length--; + } + }; + Emitter.prototype.emitIndex = function (operand1, operand2) { + var temp = this.setInObjectLiteral(false); + this.emitJavascript(operand1, TypeScript.TokenID.Tilde, false); + this.writeToOutput("["); + this.emitJavascriptList(operand2, ", ", TypeScript.TokenID.Comma, false, false, false); + this.writeToOutput("]"); + this.setInObjectLiteral(temp); + }; + Emitter.prototype.emitStringLiteral = function (text) { + this.writeToOutput(text); + }; + Emitter.prototype.emitJavascriptFunction = function (funcDecl) { + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Signature) || funcDecl.isOverload) { + return; + } + var temp; + var tempFnc = this.thisFnc; + this.thisFnc = funcDecl; + if(funcDecl.isConstructor) { + temp = this.setContainer(EmitContainer.Constructor); + } else { + temp = this.setContainer(EmitContainer.Function); + } + var bases = null; + var hasSelfRef = false; + var funcName = funcDecl.getNameText(); + if((this.emitState.inObjectLiteral || !funcDecl.isAccessor()) && ((temp != EmitContainer.Constructor) || ((funcDecl.fncFlags & TypeScript.FncFlags.Method) == TypeScript.FncFlags.None))) { + var tempLit = this.setInObjectLiteral(false); + if(this.thisClassNode) { + bases = this.thisClassNode.extendsList; + } + hasSelfRef = Emitter.shouldCaptureThis(funcDecl); + this.recordSourceMappingStart(funcDecl); + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Exported | TypeScript.FncFlags.ClassPropertyMethodExported) && funcDecl.type.symbol.container == this.checker.gloMod && !funcDecl.isConstructor) { + this.writeToOutput("this." + funcName + " = "); + this.emitInnerFunction(funcDecl, false, false, bases, hasSelfRef, this.thisClassNode); + } else { + this.emitInnerFunction(funcDecl, (funcDecl.name && !funcDecl.name.isMissing()), false, bases, hasSelfRef, this.thisClassNode); + } + this.setInObjectLiteral(tempLit); + } + this.setContainer(temp); + this.thisFnc = tempFnc; + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Definition)) { + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static)) { + if(this.thisClassNode) { + if(funcDecl.isAccessor()) { + this.emitPropertyAccessor(funcDecl, this.thisClassNode.name.actualText, false); + } else { + this.emitIndent(); + this.recordSourceMappingStart(funcDecl); + this.writeLineToOutput(this.thisClassNode.name.actualText + "." + funcName + " = " + funcName + ";"); + this.recordSourceMappingEnd(funcDecl); + } + } + } else { + if((this.emitState.container == EmitContainer.Module || this.emitState.container == EmitContainer.DynamicModule) && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Exported | TypeScript.FncFlags.ClassPropertyMethodExported)) { + this.emitIndent(); + var modName = this.emitState.container == EmitContainer.Module ? this.moduleName : "exports"; + this.recordSourceMappingStart(funcDecl); + this.writeLineToOutput(modName + "." + funcName + " = " + funcName + ";"); + this.recordSourceMappingEnd(funcDecl); + } + } + } + }; + Emitter.prototype.emitAmbientVarDecl = function (varDecl) { + if(varDecl.init) { + this.emitParensAndCommentsInPlace(varDecl, true); + this.recordSourceMappingStart(varDecl); + this.recordSourceMappingStart(varDecl.id); + this.writeToOutput(varDecl.id.actualText); + this.recordSourceMappingEnd(varDecl.id); + this.writeToOutput(" = "); + this.emitJavascript(varDecl.init, TypeScript.TokenID.Comma, false); + this.recordSourceMappingEnd(varDecl); + this.writeToOutput(";"); + this.emitParensAndCommentsInPlace(varDecl, false); + } + }; + Emitter.prototype.varListCount = function () { + return this.varListCountStack[this.varListCountStack.length - 1]; + }; + Emitter.prototype.emitVarDeclVar = function () { + if(this.varListCount() >= 0) { + this.writeToOutput("var "); + this.setInVarBlock(-this.varListCount()); + } + return true; + }; + Emitter.prototype.onEmitVar = function () { + if(this.varListCount() > 0) { + this.setInVarBlock(this.varListCount() - 1); + } else { + if(this.varListCount() < 0) { + this.setInVarBlock(this.varListCount() + 1); + } + } + }; + Emitter.prototype.emitJavascriptVarDecl = function (varDecl, tokenId) { + if((varDecl.varFlags & TypeScript.VarFlags.Ambient) == TypeScript.VarFlags.Ambient) { + this.emitAmbientVarDecl(varDecl); + this.onEmitVar(); + } else { + var sym = varDecl.sym; + var hasInitializer = (varDecl.init != null); + this.emitParensAndCommentsInPlace(varDecl, true); + this.recordSourceMappingStart(varDecl); + if(sym && sym.isMember() && sym.container && (sym.container.kind() == TypeScript.SymbolKind.Type)) { + var type = (sym.container).type; + if(type.isClass() && (!TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.ModuleMember))) { + if(this.emitState.container != EmitContainer.Args) { + if(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Static)) { + this.writeToOutput(sym.container.name + "."); + } else { + this.writeToOutput("this."); + } + } + } else { + if(type.hasImplementation()) { + if(!TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Exported) && (sym.container == this.checker.gloMod || !TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Property))) { + this.emitVarDeclVar(); + } else { + if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.LocalStatic)) { + this.writeToOutput("."); + } else { + if(this.emitState.container == EmitContainer.DynamicModule) { + this.writeToOutput("exports."); + } else { + this.writeToOutput(this.moduleName + "."); + } + } + } + } else { + if(tokenId != TypeScript.TokenID.OpenParen) { + if(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Exported) && sym.container == this.checker.gloMod) { + this.writeToOutput("this."); + } else { + this.emitVarDeclVar(); + } + } + } + } + } else { + if(tokenId != TypeScript.TokenID.OpenParen) { + this.emitVarDeclVar(); + } + } + this.recordSourceMappingStart(varDecl.id); + this.writeToOutput(varDecl.id.actualText); + this.recordSourceMappingEnd(varDecl.id); + if(hasInitializer) { + this.writeToOutputTrimmable(" = "); + this.varListCountStack.push(0); + this.emitJavascript(varDecl.init, TypeScript.TokenID.Comma, false); + this.varListCountStack.pop(); + } + this.onEmitVar(); + if((tokenId != TypeScript.TokenID.OpenParen)) { + if(this.varListCount() < 0) { + this.writeToOutput(", "); + } else { + if(tokenId != TypeScript.TokenID.For) { + this.writeToOutputTrimmable(";"); + } + } + } + this.recordSourceMappingEnd(varDecl); + this.emitParensAndCommentsInPlace(varDecl, false); + } + }; + Emitter.prototype.declEnclosed = function (moduleDecl) { + if(moduleDecl == null) { + return true; + } + for(var i = 0, len = this.moduleDeclList.length; i < len; i++) { + if(this.moduleDeclList[i] == moduleDecl) { + return true; + } + } + return false; + }; + Emitter.prototype.emitJavascriptName = function (name, addThis) { + var sym = name.sym; + this.emitParensAndCommentsInPlace(name, true); + this.recordSourceMappingStart(name); + if(!name.isMissing()) { + if(addThis && (this.emitState.container != EmitContainer.Args) && sym) { + if(sym.container && (sym.container.name != TypeScript.globalId)) { + if(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Static) && (TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Property))) { + if(sym.declModule && TypeScript.hasFlag(sym.declModule.modFlags, TypeScript.ModuleFlags.IsDynamic)) { + this.writeToOutput("exports."); + } else { + this.writeToOutput(sym.container.name + "."); + } + } else { + if(sym.kind() == TypeScript.SymbolKind.Field) { + var fieldSym = sym; + if(TypeScript.hasFlag(fieldSym.flags, TypeScript.SymbolFlags.ModuleMember)) { + if((sym.container != this.checker.gloMod) && ((TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Property)) || TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Exported))) { + if(TypeScript.hasFlag(sym.declModule.modFlags, TypeScript.ModuleFlags.IsDynamic)) { + this.writeToOutput("exports."); + } else { + this.writeToOutput(sym.container.name + "."); + } + } + } else { + if(sym.isInstanceProperty()) { + this.emitThis(); + this.writeToOutput("."); + } + } + } else { + if(sym.kind() == TypeScript.SymbolKind.Type) { + if(sym.isInstanceProperty()) { + var typeSym = sym; + var type = typeSym.type; + if(type.call && !TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.ModuleMember)) { + this.emitThis(); + this.writeToOutput("."); + } + } else { + if((sym.unitIndex != this.checker.locationInfo.unitIndex) || (!this.declEnclosed(sym.declModule))) { + this.writeToOutput(sym.container.name + "."); + } + } + } + } + } + } else { + if(sym.container == this.checker.gloMod && TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Exported) && !TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Ambient) && !((sym.isType() || sym.isMember()) && sym.declModule && TypeScript.hasFlag(sym.declModule.modFlags, TypeScript.ModuleFlags.Ambient)) && this.emitState.container == EmitContainer.Prog && sym.declAST.nodeType != TypeScript.NodeType.FuncDecl) { + this.writeToOutput("this."); + } + } + } + if(sym && sym.declAST && sym.declAST.nodeType == TypeScript.NodeType.ModuleDeclaration && (TypeScript.hasFlag((sym.declAST).modFlags, TypeScript.ModuleFlags.IsDynamic))) { + var moduleDecl = sym.declAST; + if(TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { + this.writeLineToOutput("__" + this.modAliasId + "__;"); + } else { + var modPath = name.actualText; + var isAmbient = moduleDecl.mod.symbol.declAST && TypeScript.hasFlag((moduleDecl.mod.symbol.declAST).modFlags, TypeScript.ModuleFlags.Ambient); + modPath = isAmbient ? modPath : this.firstModAlias ? this.firstModAlias : TypeScript.quoteBaseName(modPath); + modPath = isAmbient ? modPath : (!TypeScript.isRelative(TypeScript.stripQuotes(modPath)) ? TypeScript.quoteStr("./" + TypeScript.stripQuotes(modPath)) : modPath); + this.writeToOutput("require(" + modPath + ")"); + } + } else { + this.writeToOutput(name.actualText); + } + } + this.recordSourceMappingEnd(name); + this.emitParensAndCommentsInPlace(name, false); + }; + Emitter.prototype.emitJavascriptStatements = function (stmts, emitEmptyBod) { + if(stmts) { + if(stmts.nodeType != TypeScript.NodeType.Block) { + var hasContents = (stmts && (stmts.nodeType != TypeScript.NodeType.List || ((stmts).members.length > 0))); + if(emitEmptyBod || hasContents) { + var hasOnlyBlockStatement = ((stmts.nodeType == TypeScript.NodeType.Block) || ((stmts.nodeType == TypeScript.NodeType.List) && ((stmts).members.length == 1) && ((stmts).members[0].nodeType == TypeScript.NodeType.Block))); + this.recordSourceMappingStart(stmts); + if(!hasOnlyBlockStatement) { + this.writeLineToOutput(" {"); + this.indenter.increaseIndent(); + } + this.emitJavascriptList(stmts, null, TypeScript.TokenID.Semicolon, true, false, false); + if(!hasOnlyBlockStatement) { + this.writeLineToOutput(""); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeToOutput("}"); + } + this.recordSourceMappingEnd(stmts); + } + } else { + this.emitJavascript(stmts, TypeScript.TokenID.Semicolon, true); + } + } else { + if(emitEmptyBod) { + this.writeToOutput("{ }"); + } + } + }; + Emitter.prototype.emitBareJavascriptStatements = function (stmts, emitClassPropertiesAfterSuperCall) { + if (typeof emitClassPropertiesAfterSuperCall === "undefined") { emitClassPropertiesAfterSuperCall = false; } + if(stmts.nodeType != TypeScript.NodeType.Block) { + if(stmts.nodeType == TypeScript.NodeType.List) { + var stmtList = stmts; + if((stmtList.members.length == 2) && (stmtList.members[0].nodeType == TypeScript.NodeType.Block) && (stmtList.members[1].nodeType == TypeScript.NodeType.EndCode)) { + this.emitJavascript(stmtList.members[0], TypeScript.TokenID.Semicolon, true); + this.writeLineToOutput(""); + } else { + this.emitJavascriptList(stmts, null, TypeScript.TokenID.Semicolon, true, false, emitClassPropertiesAfterSuperCall); + } + } else { + this.emitJavascript(stmts, TypeScript.TokenID.Semicolon, true); + } + } else { + this.emitJavascript(stmts, TypeScript.TokenID.Semicolon, true); + } + }; + Emitter.prototype.recordSourceMappingNameStart = function (name) { + if(this.sourceMapper) { + var finalName = name; + if(!name) { + finalName = ""; + } else { + if(this.sourceMapper.currentNameIndex.length > 0) { + finalName = this.sourceMapper.names[this.sourceMapper.currentNameIndex.length - 1] + "." + name; + } + } + this.sourceMapper.names.push(finalName); + this.sourceMapper.currentNameIndex.push(this.sourceMapper.names.length - 1); + } + }; + Emitter.prototype.recordSourceMappingNameEnd = function () { + if(this.sourceMapper) { + this.sourceMapper.currentNameIndex.pop(); + } + }; + Emitter.prototype.recordSourceMappingStart = function (ast) { + if(this.sourceMapper && TypeScript.isValidAstNode(ast)) { + var lineCol = { + line: -1, + col: -1 + }; + var sourceMapping = new TypeScript.SourceMapping(); + sourceMapping.start.emittedColumn = this.emitState.column; + sourceMapping.start.emittedLine = this.emitState.line; + TypeScript.getSourceLineColFromMap(lineCol, ast.minChar, this.checker.locationInfo.lineMap); + sourceMapping.start.sourceColumn = lineCol.col; + sourceMapping.start.sourceLine = lineCol.line; + TypeScript.getSourceLineColFromMap(lineCol, ast.limChar, this.checker.locationInfo.lineMap); + sourceMapping.end.sourceColumn = lineCol.col; + sourceMapping.end.sourceLine = lineCol.line; + if(this.sourceMapper.currentNameIndex.length > 0) { + sourceMapping.nameIndex = this.sourceMapper.currentNameIndex[this.sourceMapper.currentNameIndex.length - 1]; + } + var siblings = this.sourceMapper.currentMappings[this.sourceMapper.currentMappings.length - 1]; + siblings.push(sourceMapping); + this.sourceMapper.currentMappings.push(sourceMapping.childMappings); + } + }; + Emitter.prototype.recordSourceMappingEnd = function (ast) { + if(this.sourceMapper && TypeScript.isValidAstNode(ast)) { + this.sourceMapper.currentMappings.pop(); + var siblings = this.sourceMapper.currentMappings[this.sourceMapper.currentMappings.length - 1]; + var sourceMapping = siblings[siblings.length - 1]; + sourceMapping.end.emittedColumn = this.emitState.column; + sourceMapping.end.emittedLine = this.emitState.line; + } + }; + Emitter.prototype.Close = function () { + if(this.sourceMapper != null) { + TypeScript.SourceMapper.EmitSourceMapping(this.allSourceMappers); + } + try { + this.outfile.Close(); + } catch (ex) { + this.errorReporter.emitterError(null, ex.message); + } + }; + Emitter.prototype.emitJavascriptList = function (ast, delimiter, tokenId, startLine, onlyStatics, emitClassPropertiesAfterSuperCall, emitPrologue, requiresExtendsBlock) { + if (typeof emitClassPropertiesAfterSuperCall === "undefined") { emitClassPropertiesAfterSuperCall = false; } + if (typeof emitPrologue === "undefined") { emitPrologue = false; } + if(ast == null) { + return; + } else { + if(ast.nodeType != TypeScript.NodeType.List) { + this.emitPrologue(emitPrologue); + this.emitJavascript(ast, tokenId, startLine); + } else { + var list = ast; + if(list.members.length == 0) { + return; + } + this.emitParensAndCommentsInPlace(ast, true); + var len = list.members.length; + for(var i = 0; i < len; i++) { + if(emitPrologue) { + if(i == 1 || !TypeScript.hasFlag(list.flags, TypeScript.ASTFlags.StrictMode)) { + this.emitPrologue(requiresExtendsBlock); + emitPrologue = false; + } + } + if(i == 1 && emitClassPropertiesAfterSuperCall) { + var constructorDecl = (this.thisClassNode).constructorDecl; + if(constructorDecl && constructorDecl.arguments) { + var argsLen = constructorDecl.arguments.members.length; + for(var iArg = 0; iArg < argsLen; iArg++) { + var arg = constructorDecl.arguments.members[iArg]; + if((arg.varFlags & TypeScript.VarFlags.Property) != TypeScript.VarFlags.None) { + this.emitIndent(); + this.recordSourceMappingStart(arg); + this.recordSourceMappingStart(arg.id); + this.writeToOutput("this." + arg.id.actualText); + this.recordSourceMappingEnd(arg.id); + this.writeToOutput(" = "); + this.recordSourceMappingStart(arg.id); + this.writeToOutput(arg.id.actualText); + this.recordSourceMappingEnd(arg.id); + this.writeLineToOutput(";"); + this.recordSourceMappingEnd(arg); + } + } + } + var nProps = (this.thisClassNode.members).members.length; + for(var iMember = 0; iMember < nProps; iMember++) { + if((this.thisClassNode.members).members[iMember].nodeType == TypeScript.NodeType.VarDecl) { + var varDecl = (this.thisClassNode.members).members[iMember]; + if(!TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static) && varDecl.init) { + this.emitIndent(); + this.emitJavascriptVarDecl(varDecl, TypeScript.TokenID.Tilde); + this.writeLineToOutput(""); + } + } + } + } + var emitNode = list.members[i]; + var isStaticDecl = (emitNode.nodeType == TypeScript.NodeType.FuncDecl && TypeScript.hasFlag((emitNode).fncFlags, TypeScript.FncFlags.Static)) || (emitNode.nodeType == TypeScript.NodeType.VarDecl && TypeScript.hasFlag((emitNode).varFlags, TypeScript.VarFlags.Static)); + if(onlyStatics ? !isStaticDecl : isStaticDecl) { + continue; + } + this.emitJavascript(emitNode, tokenId, startLine); + if(delimiter && (i < (len - 1))) { + if(startLine) { + this.writeLineToOutput(delimiter); + } else { + this.writeToOutput(delimiter); + } + } else { + if(startLine && (emitNode.nodeType != TypeScript.NodeType.ModuleDeclaration) && (emitNode.nodeType != TypeScript.NodeType.InterfaceDeclaration) && (!((emitNode.nodeType == TypeScript.NodeType.VarDecl) && ((((emitNode).varFlags) & TypeScript.VarFlags.Ambient) == TypeScript.VarFlags.Ambient) && (((emitNode).init) == null)) && this.varListCount() >= 0) && (emitNode.nodeType != TypeScript.NodeType.Block || (emitNode).isStatementBlock) && (emitNode.nodeType != TypeScript.NodeType.EndCode) && (emitNode.nodeType != TypeScript.NodeType.FuncDecl)) { + this.writeLineToOutput(""); + } + } + } + this.emitParensAndCommentsInPlace(ast, false); + } + } + }; + Emitter.prototype.emitJavascript = function (ast, tokenId, startLine) { + if(ast == null) { + return; + } + if(startLine && (this.indenter.indentAmt > 0) && (ast.nodeType != TypeScript.NodeType.List) && (ast.nodeType != TypeScript.NodeType.Block)) { + if((ast.nodeType != TypeScript.NodeType.InterfaceDeclaration) && (!((ast.nodeType == TypeScript.NodeType.VarDecl) && ((((ast).varFlags) & TypeScript.VarFlags.Ambient) == TypeScript.VarFlags.Ambient) && (((ast).init) == null)) && this.varListCount() >= 0) && (ast.nodeType != TypeScript.NodeType.EndCode) && ((ast.nodeType != TypeScript.NodeType.FuncDecl) || (this.emitState.container != EmitContainer.Constructor))) { + this.emitIndent(); + } + } + ast.emit(this, tokenId, startLine); + if((tokenId == TypeScript.TokenID.Semicolon) && (ast.nodeType < TypeScript.NodeType.GeneralNode)) { + this.writeToOutput(";"); + } + }; + Emitter.prototype.emitPropertyAccessor = function (funcDecl, className, isProto) { + if(!(funcDecl.accessorSymbol).hasBeenEmitted) { + var accessorSymbol = funcDecl.accessorSymbol; + this.emitIndent(); + this.recordSourceMappingStart(funcDecl); + this.writeLineToOutput("Object.defineProperty(" + className + (isProto ? ".prototype, \"" : ", \"") + funcDecl.name.actualText + "\"" + ", {"); + this.indenter.increaseIndent(); + if(accessorSymbol.getter) { + var getter = accessorSymbol.getter.declAST; + this.emitIndent(); + this.recordSourceMappingStart(getter); + this.writeToOutput("get: "); + this.emitInnerFunction(getter, false, isProto, null, Emitter.shouldCaptureThis(getter), null); + this.writeLineToOutput(","); + } + if(accessorSymbol.setter) { + var setter = accessorSymbol.setter.declAST; + this.emitIndent(); + this.recordSourceMappingStart(setter); + this.writeToOutput("set: "); + this.emitInnerFunction(setter, false, isProto, null, Emitter.shouldCaptureThis(setter), null); + this.writeLineToOutput(","); + } + this.emitIndent(); + this.writeLineToOutput("enumerable: true,"); + this.emitIndent(); + this.writeLineToOutput("configurable: true"); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeLineToOutput("});"); + this.recordSourceMappingEnd(funcDecl); + accessorSymbol.hasBeenEmitted = true; + } + }; + Emitter.prototype.emitPrototypeMember = function (member, className) { + if(member.nodeType == TypeScript.NodeType.FuncDecl) { + var funcDecl = member; + if(funcDecl.isAccessor()) { + this.emitPropertyAccessor(funcDecl, className, true); + } else { + this.emitIndent(); + this.recordSourceMappingStart(funcDecl); + this.writeToOutput(className + ".prototype." + funcDecl.getNameText() + " = "); + this.emitInnerFunction(funcDecl, false, true, null, Emitter.shouldCaptureThis(funcDecl), null); + this.writeLineToOutput(";"); + } + } else { + if(member.nodeType == TypeScript.NodeType.VarDecl) { + var varDecl = member; + if(varDecl.init) { + this.emitIndent(); + this.recordSourceMappingStart(varDecl); + this.recordSourceMappingStart(varDecl.id); + this.writeToOutput(className + ".prototype." + varDecl.id.actualText); + this.recordSourceMappingEnd(varDecl.id); + this.writeToOutput(" = "); + this.emitJavascript(varDecl.init, TypeScript.TokenID.Equals, false); + this.recordSourceMappingEnd(varDecl); + this.writeLineToOutput(";"); + } + } + } + }; + Emitter.prototype.emitAddBaseMethods = function (className, base, classDecl) { + if(base.members) { + var baseSymbol = base.symbol; + var baseName = baseSymbol.name; + if(baseSymbol.declModule != classDecl.type.symbol.declModule) { + baseName = baseSymbol.fullName(); + } + base.members.allMembers.map(function (key, s, c) { + var sym = s; + if((sym.kind() == TypeScript.SymbolKind.Type) && (sym).type.call) { + this.recordSourceMappingStart(sym.declAST); + this.writeLineToOutput(className + ".prototype." + sym.name + " = " + baseName + ".prototype." + sym.name + ";"); + this.recordSourceMappingEnd(sym.declAST); + } + }, null); + } + if(base.extendsList) { + for(var i = 0, len = base.extendsList.length; i < len; i++) { + this.emitAddBaseMethods(className, base.extendsList[i], classDecl); + } + } + }; + Emitter.prototype.emitJavascriptClass = function (classDecl) { + if(!TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Ambient)) { + var svClassNode = this.thisClassNode; + var i = 0; + this.thisClassNode = classDecl; + var className = classDecl.name.actualText; + this.emitParensAndCommentsInPlace(classDecl, true); + var temp = this.setContainer(EmitContainer.Class); + this.recordSourceMappingStart(classDecl); + if(TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Exported) && classDecl.type.symbol.container == this.checker.gloMod) { + this.writeToOutput("this." + className); + } else { + this.writeToOutput("var " + className); + } + var hasBaseClass = classDecl.extendsList && classDecl.extendsList.members.length; + var baseNameDecl = null; + var baseName = null; + if(hasBaseClass) { + this.writeLineToOutput(" = (function (_super) {"); + } else { + this.writeLineToOutput(" = (function () {"); + } + this.recordSourceMappingNameStart(className); + this.indenter.increaseIndent(); + if(hasBaseClass) { + baseNameDecl = classDecl.extendsList.members[0]; + baseName = baseNameDecl.nodeType == TypeScript.NodeType.Call ? (baseNameDecl).target : baseNameDecl; + this.emitIndent(); + this.writeLineToOutput("__extends(" + className + ", _super);"); + } + this.emitIndent(); + var constrDecl = classDecl.constructorDecl; + if(constrDecl) { + this.emitJavascript(classDecl.constructorDecl, TypeScript.TokenID.OpenParen, false); + } else { + var wroteProps = 0; + this.recordSourceMappingStart(classDecl); + this.indenter.increaseIndent(); + this.writeToOutput("function " + classDecl.name.actualText + "() {"); + this.recordSourceMappingNameStart("constructor"); + if(hasBaseClass) { + this.writeLineToOutput(""); + this.emitIndent(); + this.writeLineToOutput("_super.apply(this, arguments);"); + wroteProps++; + } + if(classDecl.varFlags & TypeScript.VarFlags.MustCaptureThis) { + this.writeCaptureThisStatement(classDecl); + } + var members = (this.thisClassNode.members).members; + for(var i = 0; i < members.length; i++) { + if(members[i].nodeType == TypeScript.NodeType.VarDecl) { + var varDecl = members[i]; + if(!TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static) && varDecl.init) { + this.writeLineToOutput(""); + this.emitIndent(); + this.emitJavascriptVarDecl(varDecl, TypeScript.TokenID.Tilde); + wroteProps++; + } + } + } + if(wroteProps) { + this.writeLineToOutput(""); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeLineToOutput("}"); + } else { + this.writeLineToOutput(" }"); + this.indenter.decreaseIndent(); + } + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(classDecl); + } + var membersLen = classDecl.members.members.length; + for(var j = 0; j < membersLen; j++) { + var memberDecl = classDecl.members.members[j]; + if(memberDecl.nodeType == TypeScript.NodeType.FuncDecl) { + var fn = memberDecl; + if(TypeScript.hasFlag(fn.fncFlags, TypeScript.FncFlags.Method) && !fn.isSignature()) { + if(!TypeScript.hasFlag(fn.fncFlags, TypeScript.FncFlags.Static)) { + this.emitPrototypeMember(fn, className); + } else { + if(fn.isAccessor()) { + this.emitPropertyAccessor(fn, this.thisClassNode.name.actualText, false); + } else { + this.emitIndent(); + this.recordSourceMappingStart(fn); + this.writeToOutput(classDecl.name.actualText + "." + fn.name.actualText + " = "); + this.emitInnerFunction(fn, (fn.name && !fn.name.isMissing()), true, null, Emitter.shouldCaptureThis(fn), null); + this.writeLineToOutput(";"); + } + } + } + } else { + if(memberDecl.nodeType == TypeScript.NodeType.VarDecl) { + var varDecl = memberDecl; + if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static)) { + if(varDecl.init) { + this.emitIndent(); + this.recordSourceMappingStart(varDecl); + this.writeToOutput(classDecl.name.actualText + "." + varDecl.id.actualText + " = "); + this.emitJavascript(varDecl.init, TypeScript.TokenID.Equals, false); + this.writeLineToOutput(";"); + this.recordSourceMappingEnd(varDecl); + } + } + } else { + throw Error("We want to catch this"); + } + } + } + this.emitIndent(); + this.recordSourceMappingStart(classDecl.endingToken); + this.writeLineToOutput("return " + className + ";"); + this.recordSourceMappingEnd(classDecl.endingToken); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.recordSourceMappingStart(classDecl.endingToken); + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(classDecl.endingToken); + this.recordSourceMappingStart(classDecl); + this.writeToOutput(")("); + if(hasBaseClass) { + this.emitJavascript(baseName, TypeScript.TokenID.Tilde, false); + } + this.writeToOutput(");"); + this.recordSourceMappingEnd(classDecl); + if((temp == EmitContainer.Module || temp == EmitContainer.DynamicModule) && TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Exported)) { + this.writeLineToOutput(""); + this.emitIndent(); + var modName = temp == EmitContainer.Module ? this.moduleName : "exports"; + this.recordSourceMappingStart(classDecl); + this.writeToOutput(modName + "." + className + " = " + className + ";"); + this.recordSourceMappingEnd(classDecl); + } + this.emitIndent(); + this.recordSourceMappingEnd(classDecl); + this.emitParensAndCommentsInPlace(classDecl, false); + this.setContainer(temp); + this.thisClassNode = svClassNode; + } + }; + Emitter.prototype.emitPrologue = function (reqInherits) { + if(!this.prologueEmitted) { + if(reqInherits) { + this.prologueEmitted = true; + this.writeLineToOutput("var __extends = this.__extends || function (d, b) {"); + this.writeLineToOutput(" function __() { this.constructor = d; }"); + this.writeLineToOutput(" __.prototype = b.prototype;"); + this.writeLineToOutput(" d.prototype = new __();"); + this.writeLineToOutput("};"); + } + if(this.checker.mustCaptureGlobalThis) { + this.prologueEmitted = true; + this.writeLineToOutput(this.captureThisStmtString); + } + } + }; + Emitter.prototype.emitSuperReference = function () { + this.writeToOutput("_super.prototype"); + }; + Emitter.prototype.emitSuperCall = function (callEx) { + if(callEx.target.nodeType == TypeScript.NodeType.Dot) { + var dotNode = callEx.target; + if(dotNode.operand1.nodeType == TypeScript.NodeType.Super) { + this.emitJavascript(dotNode, TypeScript.TokenID.OpenParen, false); + this.writeToOutput(".call("); + this.emitThis(); + if(callEx.arguments && callEx.arguments.members.length > 0) { + this.writeToOutput(", "); + this.emitJavascriptList(callEx.arguments, ", ", TypeScript.TokenID.Comma, false, false, false); + } + this.writeToOutput(")"); + return true; + } + } + return false; + }; + Emitter.prototype.emitThis = function () { + if(this.thisFnc && !this.thisFnc.isMethod() && (!this.thisFnc.isConstructor)) { + this.writeToOutput("_this"); + } else { + this.writeToOutput("this"); + } + }; + Emitter.shouldCaptureThis = function shouldCaptureThis(func) { + return func.hasSelfReference() || func.hasSuperReferenceInFatArrowFunction(); + } + Emitter.prototype.createFile = function (fileName, useUTF8) { + try { + return this.emitOptions.ioHost.createFile(fileName, useUTF8); + } catch (ex) { + this.errorReporter.emitterError(null, ex.message); + } + }; + return Emitter; + })(); + TypeScript.Emitter = Emitter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ErrorReporter = (function () { + function ErrorReporter(outfile) { + this.outfile = outfile; + this.parser = null; + this.checker = null; + this.lineCol = { + line: 0, + col: 0 + }; + this.emitAsComments = true; + this.hasErrors = false; + this.pushToErrorSink = false; + this.errorSink = []; + } + ErrorReporter.prototype.getCapturedErrors = function () { + return this.errorSink; + }; + ErrorReporter.prototype.freeCapturedErrors = function () { + this.errorSink = []; + }; + ErrorReporter.prototype.captureError = function (emsg) { + this.errorSink[this.errorSink.length] = emsg; + }; + ErrorReporter.prototype.setErrOut = function (outerr) { + this.outfile = outerr; + this.emitAsComments = false; + }; + ErrorReporter.prototype.emitPrefix = function () { + if(this.emitAsComments) { + this.outfile.Write("// "); + } + this.outfile.Write(this.checker.locationInfo.filename + "(" + this.lineCol.line + "," + this.lineCol.col + "): "); + }; + ErrorReporter.prototype.writePrefix = function (ast) { + if(ast) { + this.setError(ast); + } else { + this.lineCol.line = 0; + this.lineCol.col = 0; + } + this.emitPrefix(); + }; + ErrorReporter.prototype.writePrefixFromSym = function (symbol) { + if(symbol && this.checker.locationInfo.lineMap) { + TypeScript.getSourceLineColFromMap(this.lineCol, symbol.location, this.checker.locationInfo.lineMap); + } else { + this.lineCol.line = -1; + this.lineCol.col = -1; + } + this.emitPrefix(); + }; + ErrorReporter.prototype.setError = function (ast) { + if(ast) { + ast.flags |= TypeScript.ASTFlags.Error; + if(this.checker.locationInfo.lineMap) { + TypeScript.getSourceLineColFromMap(this.lineCol, ast.minChar, this.checker.locationInfo.lineMap); + } + } + }; + ErrorReporter.prototype.reportError = function (ast, message) { + if(this.pushToErrorSink) { + this.captureError(message); + return; + } + this.hasErrors = true; + if(ast && this.parser.errorRecovery && this.parser.errorCallback) { + var len = (ast.limChar - ast.minChar); + this.parser.errorCallback(ast.minChar, len, message, this.checker.locationInfo.unitIndex); + } else { + this.writePrefix(ast); + this.outfile.WriteLine(message); + } + }; + ErrorReporter.prototype.reportErrorFromSym = function (symbol, message) { + if(this.pushToErrorSink) { + this.captureError(message); + return; + } + this.hasErrors = true; + if(this.parser.errorRecovery && this.parser.errorCallback) { + this.parser.errorCallback(symbol.location, symbol.length, message, this.checker.locationInfo.unitIndex); + } else { + this.writePrefixFromSym(symbol); + this.outfile.WriteLine(message); + } + }; + ErrorReporter.prototype.emitterError = function (ast, message) { + this.reportError(ast, message); + throw Error("EmitError"); + }; + ErrorReporter.prototype.duplicateIdentifier = function (ast, name) { + this.reportError(ast, "Duplicate identifier '" + name + "'"); + }; + ErrorReporter.prototype.showRef = function (ast, text, symbol) { + var defLineCol = { + line: -1, + col: -1 + }; + this.parser.getSourceLineCol(defLineCol, symbol.location); + this.reportError(ast, "symbol " + text + " defined at (" + defLineCol.line + "," + defLineCol.col + ")"); + }; + ErrorReporter.prototype.unresolvedSymbol = function (ast, name) { + this.reportError(ast, "The name '" + name + "' does not exist in the current scope"); + }; + ErrorReporter.prototype.symbolDoesNotReferToAValue = function (ast, name) { + this.reportError(ast, "The name '" + name + "' does not refer to a value"); + }; + ErrorReporter.prototype.styleError = function (ast, msg) { + var bkThrow = this.pushToErrorSink; + this.pushToErrorSink = false; + this.reportError(ast, "STYLE: " + msg); + this.pushToErrorSink = bkThrow; + }; + ErrorReporter.prototype.simpleError = function (ast, msg) { + this.reportError(ast, msg); + }; + ErrorReporter.prototype.simpleErrorFromSym = function (sym, msg) { + this.reportErrorFromSym(sym, msg); + }; + ErrorReporter.prototype.invalidSuperReference = function (ast) { + this.simpleError(ast, "Keyword 'super' can only be used inside a class instance method"); + }; + ErrorReporter.prototype.valueCannotBeModified = function (ast) { + this.simpleError(ast, "The left-hand side of an assignment expression must be a variable, property or indexer"); + }; + ErrorReporter.prototype.invalidCall = function (ast, nodeType, scope) { + var targetType = ast.target.type; + var typeName = targetType.getScopedTypeName(scope); + if(targetType.construct && (nodeType == TypeScript.NodeType.Call)) { + this.reportError(ast, "Value of type '" + typeName + "' is not callable. Did you mean to include 'new'?"); + } else { + var catString = (nodeType == TypeScript.NodeType.Call) ? "callable" : "newable"; + this.reportError(ast, "Value of type '" + typeName + "' is not " + catString); + } + }; + ErrorReporter.prototype.indexLHS = function (ast, scope) { + var targetType = ast.operand1.type.getScopedTypeName(scope); + var indexType = ast.operand2.type.getScopedTypeName(scope); + this.simpleError(ast, "Value of type '" + targetType + "' is not indexable by type '" + indexType + "'"); + }; + ErrorReporter.prototype.incompatibleTypes = function (ast, t1, t2, op, scope, comparisonInfo) { + if(!t1) { + t1 = this.checker.anyType; + } + if(!t2) { + t2 = this.checker.anyType; + } + var reason = comparisonInfo ? comparisonInfo.message : ""; + if(op) { + this.reportError(ast, "Operator '" + op + "' cannot be applied to types '" + t1.getScopedTypeName(scope) + "' and '" + t2.getScopedTypeName(scope) + "'" + (reason ? ": " + reason : "")); + } else { + this.reportError(ast, "Cannot convert '" + t1.getScopedTypeName(scope) + "' to '" + t2.getScopedTypeName(scope) + "'" + (reason ? ": " + reason : "")); + } + }; + ErrorReporter.prototype.expectedClassOrInterface = function (ast) { + this.simpleError(ast, "Expected var, class, interface, or module"); + }; + ErrorReporter.prototype.unaryOperatorTypeError = function (ast, op, type) { + this.reportError(ast, "Operator '" + op + "' cannot be applied to type '" + type.getTypeName() + "'"); + }; + return ErrorReporter; + })(); + TypeScript.ErrorReporter = ErrorReporter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (TypeContext) { + TypeContext._map = []; + TypeContext.NoTypes = 0; + TypeContext.ArraySuffix = 1; + TypeContext.Primitive = 2; + TypeContext.Named = 4; + TypeContext.AllSimpleTypes = TypeContext.Primitive | TypeContext.Named; + TypeContext.AllTypes = TypeContext.Primitive | TypeContext.Named | TypeContext.ArraySuffix; + })(TypeScript.TypeContext || (TypeScript.TypeContext = {})); + var TypeContext = TypeScript.TypeContext; + (function (ParseState) { + ParseState._map = []; + ParseState._map[0] = "None"; + ParseState.None = 0; + ParseState._map[1] = "StartScript"; + ParseState.StartScript = 1; + ParseState._map[2] = "StartStatementList"; + ParseState.StartStatementList = 2; + ParseState._map[3] = "StartStatement"; + ParseState.StartStatement = 3; + ParseState._map[4] = "StartFncDecl"; + ParseState.StartFncDecl = 4; + ParseState._map[5] = "FncDeclName"; + ParseState.FncDeclName = 5; + ParseState._map[6] = "FncDeclArgs"; + ParseState.FncDeclArgs = 6; + ParseState._map[7] = "FncDeclReturnType"; + ParseState.FncDeclReturnType = 7; + ParseState._map[8] = "ForInit"; + ParseState.ForInit = 8; + ParseState._map[9] = "ForInitAfterVar"; + ParseState.ForInitAfterVar = 9; + ParseState._map[10] = "ForCondStart"; + ParseState.ForCondStart = 10; + ParseState._map[11] = "EndStmtList"; + ParseState.EndStmtList = 11; + ParseState._map[12] = "EndScript"; + ParseState.EndScript = 12; + })(TypeScript.ParseState || (TypeScript.ParseState = {})); + var ParseState = TypeScript.ParseState; + var QuickParseResult = (function () { + function QuickParseResult(Script, endLexState) { + this.Script = Script; + this.endLexState = endLexState; + } + return QuickParseResult; + })(); + TypeScript.QuickParseResult = QuickParseResult; + var Parser = (function () { + function Parser() { + this.varLists = []; + this.scopeLists = []; + this.staticsLists = []; + this.scanner = new TypeScript.Scanner(); + this.currentToken = null; + this.needTerminator = false; + this.inFunction = false; + this.inInterfaceDecl = false; + this.currentClassDecl = null; + this.inFncDecl = false; + this.anonId = new TypeScript.Identifier("_anonymous"); + this.style_requireSemi = false; + this.style_funcInLoop = true; + this.incremental = false; + this.errorRecovery = false; + this.outfile = undefined; + this.errorCallback = null; + this.state = ParseState.StartStatementList; + this.ambientModule = false; + this.ambientClass = false; + this.topLevel = true; + this.allowImportDeclaration = true; + this.currentUnitIndex = (-1); + this.prevIDTok = null; + this.statementInfoStack = new Array(); + this.hasTopLevelImportOrExport = false; + this.strictMode = false; + this.nestingLevel = 0; + this.prevExpr = null; + this.currentClassDefinition = null; + this.parsingClassConstructorDefinition = false; + this.parsingDeclareFile = false; + this.amdDependencies = []; + this.inferPropertiesFromThisAssignment = false; + this.requiresExtendsBlock = false; + this.fname = ""; + } + Parser.prototype.resetStmtStack = function () { + this.statementInfoStack = new Array(); + }; + Parser.prototype.inLoop = function () { + for(var j = this.statementInfoStack.length - 1; j >= 0; j--) { + if(this.statementInfoStack[j].stmt.isLoop()) { + return true; + } + } + return false; + }; + Parser.prototype.pushStmt = function (stmt, labels) { + var info = { + stmt: stmt, + labels: labels + }; + this.statementInfoStack.push(info); + }; + Parser.prototype.popStmt = function () { + return this.statementInfoStack.pop(); + }; + Parser.prototype.resolveJumpTarget = function (jump) { + var resolvedTarget = TypeScript.AST.getResolvedIdentifierName(jump.target); + var len = this.statementInfoStack.length; + for(var i = len - 1; i >= 0; i--) { + var info = this.statementInfoStack[i]; + if(jump.target) { + if(info.labels && (info.labels.members.length > 0)) { + for(var j = 0, labLen = info.labels.members.length; j < labLen; j++) { + var label = info.labels.members[j]; + if(label.id.text == resolvedTarget) { + jump.setResolvedTarget(this, info.stmt); + return; + } + } + } + } else { + if(info.stmt.isLoop()) { + jump.setResolvedTarget(this, info.stmt); + return; + } else { + if((info.stmt.nodeType == TypeScript.NodeType.Switch) && (jump.nodeType == TypeScript.NodeType.Break)) { + jump.setResolvedTarget(this, info.stmt); + return; + } + } + } + } + if(jump.target) { + this.reportParseError("could not find enclosing statement with label " + jump.target); + } else { + if(jump.nodeType == TypeScript.NodeType.Break) { + this.reportParseError("break statement requires enclosing loop or switch"); + } else { + this.reportParseError("continue statement requires enclosing loop"); + } + } + }; + Parser.prototype.setErrorRecovery = function (outfile) { + this.outfile = outfile; + this.errorRecovery = true; + }; + Parser.prototype.getSourceLineCol = function (lineCol, minChar) { + TypeScript.getSourceLineColFromMap(lineCol, minChar, this.scanner.lineMap); + }; + Parser.prototype.createRef = function (text, hasEscapeSequence, minChar) { + var id = new TypeScript.Identifier(text, hasEscapeSequence); + id.minChar = minChar; + return id; + }; + Parser.prototype.reportParseStyleError = function (message) { + this.reportParseError("STYLE: " + message); + }; + Parser.prototype.reportParseError = function (message, startPos, pos) { + if (typeof startPos === "undefined") { startPos = this.scanner.startPos; } + if (typeof pos === "undefined") { pos = this.scanner.pos; } + var len = Math.max(1, pos - startPos); + if(this.errorCallback) { + this.errorCallback(startPos, len, message, this.currentUnitIndex); + } else { + if(this.errorRecovery) { + var lineCol = { + line: -1, + col: -1 + }; + this.getSourceLineCol(lineCol, startPos); + if(this.outfile) { + this.outfile.WriteLine("// " + this.fname + " (" + lineCol.line + "," + lineCol.col + "): " + message); + } + } else { + throw new SyntaxError(this.fname + " (" + this.scanner.line + "," + this.scanner.col + "): " + message); + } + } + }; + Parser.prototype.checkNextToken = function (tokenId, errorRecoverySet, errorText) { + if (typeof errorText === "undefined") { errorText = null; } + this.currentToken = this.scanner.scan(); + this.checkCurrentToken(tokenId, errorRecoverySet, errorText); + }; + Parser.prototype.skip = function (errorRecoverySet) { + errorRecoverySet |= TypeScript.ErrorRecoverySet.EOF; + var ersTok = TypeScript.ErrorRecoverySet.None; + var tokenInfo = TypeScript.lookupToken(this.currentToken.tokenId); + if(tokenInfo != undefined) { + ersTok = tokenInfo.ers; + } + var pendingRightCurlies = 0; + while(((ersTok & errorRecoverySet) == TypeScript.ErrorRecoverySet.None) || (this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) && (pendingRightCurlies > 0)) { + if(this.currentToken.tokenId == TypeScript.TokenID.OpenBrace) { + pendingRightCurlies++; + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { + pendingRightCurlies--; + } + } + this.currentToken = this.scanner.scan(); + ersTok = TypeScript.ErrorRecoverySet.None; + tokenInfo = TypeScript.lookupToken(this.currentToken.tokenId); + if(tokenInfo != undefined) { + ersTok = tokenInfo.ers; + } + } + }; + Parser.prototype.checkCurrentToken = function (tokenId, errorRecoverySet, errorText) { + if (typeof errorText === "undefined") { errorText = null; } + if(this.currentToken.tokenId != tokenId) { + errorText = errorText == null ? ("Expected '" + TypeScript.tokenTable[tokenId].text + "'") : errorText; + this.reportParseError(errorText); + if(this.errorRecovery) { + this.skip(errorRecoverySet); + } + } else { + this.currentToken = this.scanner.scan(); + } + }; + Parser.prototype.pushDeclLists = function () { + this.staticsLists.push(new TypeScript.ASTList()); + this.varLists.push(new TypeScript.ASTList()); + this.scopeLists.push(new TypeScript.ASTList()); + }; + Parser.prototype.popDeclLists = function () { + this.staticsLists.pop(); + this.varLists.pop(); + this.scopeLists.pop(); + }; + Parser.prototype.topVarList = function () { + return this.varLists[this.varLists.length - 1]; + }; + Parser.prototype.topScopeList = function () { + return this.scopeLists[this.scopeLists.length - 1]; + }; + Parser.prototype.topStaticsList = function () { + return this.staticsLists[this.staticsLists.length - 1]; + }; + Parser.prototype.parseComment = function (comment) { + if(comment) { + var c = new TypeScript.Comment(comment.value, comment.isBlock, comment.endsLine); + c.minChar = comment.startPos; + c.limChar = comment.startPos + comment.value.length; + var lineCol = { + line: -1, + col: -1 + }; + this.getSourceLineCol(lineCol, c.minChar); + c.minLine = lineCol.line; + this.getSourceLineCol(lineCol, c.limChar); + c.limLine = lineCol.line; + if(!comment.isBlock && comment.value.length > 3 && comment.value.substring(0, 3) == "///") { + var dependencyPath = TypeScript.getAdditionalDependencyPath(comment.value); + if(dependencyPath) { + this.amdDependencies.push(dependencyPath); + } + if(TypeScript.getImplicitImport(comment.value)) { + this.hasTopLevelImportOrExport = true; + } + } + return c; + } else { + return null; + } + }; + Parser.prototype.parseCommentsInner = function (comments) { + if(comments) { + var commentASTs = new Array(); + for(var i = 0; i < comments.length; i++) { + commentASTs.push(this.parseComment(comments[i])); + } + return commentASTs; + } else { + return null; + } + }; + Parser.prototype.parseComments = function () { + var comments = this.scanner.getComments(); + return this.parseCommentsInner(comments); + }; + Parser.prototype.parseCommentsForLine = function (line) { + var comments = this.scanner.getCommentsForLine(line); + return this.parseCommentsInner(comments); + }; + Parser.prototype.combineComments = function (comment1, comment2) { + if(comment1 == null) { + return comment2; + } else { + if(comment2 == null) { + return comment1; + } else { + return comment1.concat(comment2); + } + } + }; + Parser.prototype.parseEnumDecl = function (errorRecoverySet, modifiers) { + var leftCurlyCount = this.scanner.leftCurlyCount; + var rightCurlyCount = this.scanner.rightCurlyCount; + var name = null; + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + name = TypeScript.Identifier.fromToken(this.currentToken); + name.minChar = this.scanner.startPos; + name.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + } else { + this.reportParseError("Enum declaration requires identifier"); + if(this.errorRecovery) { + name = new TypeScript.MissingIdentifier(); + name.minChar = this.scanner.startPos; + name.limChar = this.scanner.startPos; + name.flags |= TypeScript.ASTFlags.Error; + } + } + var membersMinChar = this.scanner.startPos; + this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.ID); + this.pushDeclLists(); + var members = new TypeScript.ASTList(); + members.minChar = membersMinChar; + var mapDecl = new TypeScript.VarDecl(new TypeScript.Identifier("_map"), 0); + mapDecl.varFlags |= TypeScript.VarFlags.Exported; + mapDecl.varFlags |= TypeScript.VarFlags.Private; + mapDecl.varFlags |= (TypeScript.VarFlags.Property | TypeScript.VarFlags.Public); + mapDecl.init = new TypeScript.UnaryExpression(TypeScript.NodeType.ArrayLit, null); + members.append(mapDecl); + var lastValue = null; + for(; ; ) { + var minChar = this.scanner.startPos; + var limChar; + var memberName = null; + var memberValue = null; + var preComments = null; + var postComments = null; + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToIDName(this.currentToken)) { + memberName = TypeScript.Identifier.fromToken(this.currentToken); + memberName.minChar = this.scanner.startPos; + memberName.limChar = this.scanner.pos; + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { + break; + } else { + this.reportParseError("Expected identifer of enum member"); + if(this.errorRecovery) { + memberName = new TypeScript.MissingIdentifier(); + memberName.minChar = this.scanner.startPos; + memberName.limChar = this.scanner.startPos; + memberName.flags |= TypeScript.ASTFlags.Error; + } + } + } + limChar = this.scanner.pos; + preComments = this.parseComments(); + this.currentToken = this.scanner.scan(); + postComments = this.parseComments(); + if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { + this.currentToken = this.scanner.scan(); + memberValue = this.parseExpr(errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); + lastValue = memberValue; + limChar = memberValue.limChar; + } else { + if(lastValue == null) { + memberValue = new TypeScript.NumberLiteral(0); + lastValue = memberValue; + } else { + memberValue = new TypeScript.NumberLiteral(lastValue.value + 1); + lastValue = memberValue; + } + var map = new TypeScript.BinaryExpression(TypeScript.NodeType.Asg, new TypeScript.BinaryExpression(TypeScript.NodeType.Index, new TypeScript.Identifier("_map"), memberValue), new TypeScript.StringLiteral('"' + memberName.actualText + '"')); + members.append(map); + } + var member = new TypeScript.VarDecl(memberName, this.nestingLevel); + member.minChar = minChar; + member.limChar = limChar; + member.init = memberValue; + member.typeExpr = new TypeScript.TypeReference(this.createRef(name.actualText, name.hasEscapeSequence, -1), 0); + member.varFlags |= (TypeScript.VarFlags.Readonly | TypeScript.VarFlags.Property); + if(memberValue.nodeType == TypeScript.NodeType.NumberLit) { + member.varFlags |= TypeScript.VarFlags.Constant; + } + member.preComments = preComments; + members.append(member); + member.postComments = postComments; + member.varFlags |= TypeScript.VarFlags.Exported; + if(this.currentToken.tokenId == TypeScript.TokenID.Comma) { + this.currentToken = this.scanner.scan(); + member.postComments = this.combineComments(member.postComments, this.parseCommentsForLine(this.scanner.prevLine)); + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || (TypeScript.convertTokToIDName(this.currentToken))) { + continue; + } + } + break; + } + var endingToken = new TypeScript.ASTSpan(); + endingToken.minChar = this.scanner.startPos; + endingToken.limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); + members.limChar = this.scanner.lastTokenLimChar(); + var modDecl = new TypeScript.ModuleDeclaration(name, members, this.topVarList(), this.topScopeList(), endingToken); + modDecl.modFlags |= TypeScript.ModuleFlags.IsEnum; + this.popDeclLists(); + modDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; + modDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; + return modDecl; + }; + Parser.prototype.parseDottedName = function (enclosedList) { + this.currentToken = this.scanner.scan(); + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + var id = TypeScript.Identifier.fromToken(this.currentToken); + id.preComments = this.parseComments(); + enclosedList[enclosedList.length] = id; + id.minChar = this.scanner.startPos; + id.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.Dot) { + this.parseDottedName(enclosedList); + } + } else { + this.reportParseError("need identifier after '.'"); + } + }; + Parser.prototype.isValidImportPath = function (importPath) { + importPath = TypeScript.stripQuotes(importPath); + if(!importPath || importPath.indexOf(':') != -1 || importPath.indexOf('\\') != -1 || importPath.charAt(0) == '/') { + return false; + } + return true; + }; + Parser.prototype.parseImportDeclaration = function (errorRecoverySet, modifiers) { + var name = null; + var alias = null; + var importDecl = null; + var minChar = this.scanner.startPos; + var isDynamicImport = false; + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + name = TypeScript.Identifier.fromToken(this.currentToken); + } else { + this.reportParseError("Expected identifer after 'import'"); + name = new TypeScript.MissingIdentifier(); + } + name.minChar = this.scanner.startPos; + name.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + this.checkCurrentToken(TypeScript.TokenID.Equals, errorRecoverySet | TypeScript.ErrorRecoverySet.ID); + var aliasPreComments = this.parseComments(); + var limChar; + if(this.currentToken.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + if(this.currentToken.tokenId == TypeScript.TokenID.Module) { + limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.StringLiteral || this.currentToken.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + if(this.currentToken.tokenId == TypeScript.TokenID.StringLiteral) { + if(this.topLevel) { + this.hasTopLevelImportOrExport = true; + } else { + if(!this.allowImportDeclaration) { + this.reportParseError("Import declaration of external module is permitted only in global or top level dynamic modules"); + } + } + var aliasText = this.currentToken.getText(); + alias = TypeScript.Identifier.fromToken(this.currentToken); + alias.minChar = this.scanner.startPos; + alias.limChar = this.scanner.pos; + if(!this.isValidImportPath((alias).text)) { + this.reportParseError("Invalid import path"); + } + isDynamicImport = true; + this.currentToken = this.scanner.scan(); + alias.preComments = aliasPreComments; + } else { + alias = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.Assignment, true, TypeContext.NoTypes); + alias.preComments = aliasPreComments; + } + } + limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ID); + if(alias) { + alias.postComments = this.parseComments(); + } + } + } else { + alias = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.Assignment, true, TypeContext.NoTypes); + limChar = this.scanner.pos; + } + } else { + this.reportParseError("Expected module name"); + alias = new TypeScript.MissingIdentifier(); + alias.minChar = this.scanner.startPos; + if(this.currentToken.tokenId == TypeScript.TokenID.Semicolon) { + alias.limChar = this.scanner.startPos; + } else { + alias.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + } + alias.flags |= TypeScript.ASTFlags.Error; + limChar = alias.limChar; + } + importDecl = new TypeScript.ImportDeclaration(name, alias); + importDecl.isDynamicImport = isDynamicImport; + importDecl.minChar = minChar; + importDecl.limChar = limChar; + return importDecl; + }; + Parser.prototype.parseModuleDecl = function (errorRecoverySet, modifiers, preComments) { + var leftCurlyCount = this.scanner.leftCurlyCount; + var rightCurlyCount = this.scanner.rightCurlyCount; + var svAmbient = this.ambientModule; + var svTopLevel = this.topLevel; + this.topLevel = false; + if(this.parsingDeclareFile || svAmbient || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + this.ambientModule = true; + } + this.currentToken = this.scanner.scan(); + var name = null; + var enclosedList = null; + this.pushDeclLists(); + var minChar = this.scanner.startPos; + var isDynamicMod = false; + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || (this.currentToken.tokenId == TypeScript.TokenID.StringLiteral) || (!TypeScript.isPrimitiveTypeToken(this.currentToken) && TypeScript.convertTokToID(this.currentToken, this.strictMode))) { + var nameText = this.currentToken.getText(); + if(this.currentToken.tokenId == TypeScript.TokenID.StringLiteral) { + isDynamicMod = true; + if(!this.ambientModule) { + this.reportParseError("Only ambient dynamic modules may have string literal names"); + } + if(!svTopLevel) { + this.reportParseError("Dynamic modules may not be nested within other modules"); + } + } + name = TypeScript.Identifier.fromToken(this.currentToken); + name.minChar = this.scanner.startPos; + name.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.OpenBrace) { + this.reportParseError("Module name missing"); + name = new TypeScript.Identifier(""); + name.minChar = minChar; + name.limChar = minChar; + } + } + if(this.currentToken.tokenId == TypeScript.TokenID.Dot) { + enclosedList = new Array(); + this.parseDottedName(enclosedList); + } + if(name == null) { + name = new TypeScript.MissingIdentifier(); + } + var moduleBody = new TypeScript.ASTList(); + var bodyMinChar = this.scanner.startPos; + this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.ID); + if(svTopLevel && isDynamicMod) { + this.allowImportDeclaration = true; + } else { + this.allowImportDeclaration = false; + } + this.parseStatementList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, moduleBody, true, true, TypeScript.AllowedElements.Global, modifiers); + moduleBody.minChar = bodyMinChar; + moduleBody.limChar = this.scanner.pos; + var endingToken = new TypeScript.ASTSpan(); + endingToken.minChar = this.scanner.startPos; + endingToken.limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); + var limChar = this.scanner.lastTokenLimChar(); + var moduleDecl; + this.allowImportDeclaration = svTopLevel; + if(enclosedList && (enclosedList.length > 0)) { + var len = enclosedList.length; + var innerName = enclosedList[len - 1]; + var innerDecl = new TypeScript.ModuleDeclaration(innerName, moduleBody, this.topVarList(), this.topScopeList(), endingToken); + innerDecl.preComments = preComments; + if(this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + innerDecl.modFlags |= TypeScript.ModuleFlags.Ambient; + } + innerDecl.modFlags |= TypeScript.ModuleFlags.Exported; + innerDecl.minChar = minChar; + innerDecl.limChar = limChar; + this.popDeclLists(); + var outerModBod; + for(var i = len - 2; i >= 0; i--) { + outerModBod = new TypeScript.ASTList(); + outerModBod.append(innerDecl); + innerName = enclosedList[i]; + innerDecl = new TypeScript.ModuleDeclaration(innerName, outerModBod, new TypeScript.ASTList(), new TypeScript.ASTList(), endingToken); + outerModBod.minChar = innerDecl.minChar = minChar; + outerModBod.limChar = innerDecl.limChar = limChar; + if(this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + innerDecl.modFlags |= TypeScript.ModuleFlags.Ambient; + } + innerDecl.modFlags |= TypeScript.ModuleFlags.Exported; + } + outerModBod = new TypeScript.ASTList(); + outerModBod.append(innerDecl); + outerModBod.minChar = minChar; + outerModBod.limChar = limChar; + moduleDecl = new TypeScript.ModuleDeclaration(name, outerModBod, new TypeScript.ASTList(), new TypeScript.ASTList(), endingToken); + } else { + moduleDecl = new TypeScript.ModuleDeclaration(name, moduleBody, this.topVarList(), this.topScopeList(), endingToken); + moduleDecl.preComments = preComments; + this.popDeclLists(); + } + if(this.parsingDeclareFile || svAmbient || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + moduleDecl.modFlags |= TypeScript.ModuleFlags.Ambient; + } + if(svAmbient || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { + moduleDecl.modFlags |= TypeScript.ModuleFlags.Exported; + } + if(isDynamicMod) { + moduleDecl.modFlags |= TypeScript.ModuleFlags.IsDynamic; + } + this.ambientModule = svAmbient; + this.topLevel = svTopLevel; + moduleDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; + moduleDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; + moduleDecl.limChar = moduleBody.limChar; + return moduleDecl; + }; + Parser.prototype.parseTypeReferenceTail = function (errorRecoverySet, minChar, term) { + var result = new TypeScript.TypeReference(term, 0); + result.minChar = minChar; + while(this.currentToken.tokenId == TypeScript.TokenID.OpenBracket) { + this.currentToken = this.scanner.scan(); + result.arrayCount++; + this.checkCurrentToken(TypeScript.TokenID.CloseBracket, errorRecoverySet | TypeScript.ErrorRecoverySet.LBrack); + } + result.limChar = this.scanner.lastTokenLimChar(); + return result; + }; + Parser.prototype.parseNamedType = function (errorRecoverySet, minChar, term, tail) { + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.Dot) { + var curpos = this.scanner.pos; + this.currentToken = this.scanner.scan(); + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || ((!this.errorRecovery || !this.scanner.lastTokenHadNewline()) && TypeScript.convertTokToID(this.currentToken, this.strictMode))) { + var op2 = TypeScript.Identifier.fromToken(this.currentToken); + op2.minChar = this.scanner.startPos; + op2.limChar = this.scanner.pos; + var dotNode = new TypeScript.BinaryExpression(TypeScript.NodeType.Dot, term, op2); + dotNode.minChar = term.minChar; + dotNode.limChar = op2.limChar; + return this.parseNamedType(errorRecoverySet, minChar, dotNode, tail); + } else { + this.reportParseError("need identifier after '.'"); + if(this.errorRecovery) { + term.flags |= TypeScript.ASTFlags.DotLHS; + term.limChar = this.scanner.lastTokenLimChar(); + return term; + } else { + var eop2 = new TypeScript.MissingIdentifier(); + eop2.minChar = this.scanner.pos; + eop2.limChar = this.scanner.pos; + var edotNode = new TypeScript.BinaryExpression(TypeScript.NodeType.Dot, term, eop2); + edotNode.flags |= TypeScript.ASTFlags.Error; + edotNode.minChar = term.minChar; + edotNode.limChar = eop2.limChar; + return this.parseNamedType(errorRecoverySet, minChar, edotNode, tail); + } + } + } else { + if(tail) { + return this.parseTypeReferenceTail(errorRecoverySet, minChar, term); + } else { + return term; + } + } + }; + Parser.prototype.parseTypeReference = function (errorRecoverySet, allowVoid) { + var minChar = this.scanner.startPos; + var isConstructorMember = false; + switch(this.currentToken.tokenId) { + case TypeScript.TokenID.Void: { + if(!allowVoid) { + this.reportParseError("void not a valid type in this context"); + } + + } + case TypeScript.TokenID.Any: + case TypeScript.TokenID.Number: + case TypeScript.TokenID.Bool: + case TypeScript.TokenID.String: { + var text = TypeScript.tokenTable[this.currentToken.tokenId].text; + var predefinedIdentifier = new TypeScript.Identifier(text); + predefinedIdentifier.minChar = minChar; + predefinedIdentifier.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + return this.parseTypeReferenceTail(errorRecoverySet, minChar, predefinedIdentifier); + } + + case TypeScript.TokenID.Identifier: { + var ident = this.createRef(this.currentToken.getText(), (this.currentToken).hasEscapeSequence, minChar); + ident.limChar = this.scanner.pos; + return this.parseNamedType(errorRecoverySet, minChar, ident, true); + + } + case TypeScript.TokenID.OpenBrace: { + return this.parseObjectType(minChar, errorRecoverySet); + + } + case TypeScript.TokenID.New: { + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId != TypeScript.TokenID.OpenParen) { + this.reportParseError("Expected '('"); + } else { + isConstructorMember = true; + } + + } + case TypeScript.TokenID.OpenParen: { + var formals = new TypeScript.ASTList(); + var variableArgList = this.parseFormalParameterList(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, formals, false, true, false, false, false, false, null, true); + this.checkCurrentToken(TypeScript.TokenID.EqualsGreaterThan, errorRecoverySet); + var returnType = this.parseTypeReference(errorRecoverySet, true); + var funcDecl = new TypeScript.FuncDecl(null, null, false, formals, null, null, null, TypeScript.NodeType.FuncDecl); + funcDecl.returnTypeAnnotation = returnType; + funcDecl.variableArgList = variableArgList; + funcDecl.fncFlags |= TypeScript.FncFlags.Signature; + if(isConstructorMember) { + funcDecl.fncFlags |= TypeScript.FncFlags.ConstructMember; + funcDecl.hint = "_construct"; + funcDecl.classDecl = null; + } + funcDecl.minChar = minChar; + return this.parseTypeReferenceTail(errorRecoverySet, minChar, funcDecl); + } + + default: { + this.reportParseError("Expected type name"); + var etr = new TypeScript.TypeReference(null, 0); + etr.flags |= TypeScript.ASTFlags.Error; + etr.minChar = this.scanner.pos; + etr.limChar = this.scanner.pos; + return etr; + + } + } + }; + Parser.prototype.parseObjectType = function (minChar, errorRecoverySet) { + this.currentToken = this.scanner.scan(); + var members = new TypeScript.ASTList(); + members.minChar = minChar; + var prevInInterfaceDecl = this.inInterfaceDecl; + this.inInterfaceDecl = true; + this.parseTypeMemberList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, members); + this.inInterfaceDecl = prevInInterfaceDecl; + this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); + var interfaceDecl = new TypeScript.InterfaceDeclaration(this.anonId, members, null, null); + interfaceDecl.minChar = minChar; + interfaceDecl.limChar = members.limChar; + return this.parseTypeReferenceTail(errorRecoverySet, minChar, interfaceDecl); + }; + Parser.prototype.parseFunctionBlock = function (errorRecoverySet, allowedElements, parentModifiers, bod, bodMinChar) { + this.state = ParseState.StartStatementList; + this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); + var savedInFunction = this.inFunction; + this.inFunction = true; + this.parseStatementList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly | TypeScript.ErrorRecoverySet.StmtStart, bod, true, false, allowedElements, parentModifiers); + bod.minChar = bodMinChar; + bod.limChar = this.scanner.pos; + this.inFunction = savedInFunction; + var ec = new TypeScript.EndCode(); + ec.minChar = bod.limChar; + ec.limChar = ec.minChar; + bod.append(ec); + }; + Parser.prototype.parseFunctionStatements = function (errorRecoverySet, name, isConstructor, isMethod, args, allowedElements, minChar, requiresSignature, parentModifiers) { + this.pushDeclLists(); + var svStmtStack = this.statementInfoStack; + this.resetStmtStack(); + var bod = null; + var wasShorthand = false; + var isAnonLambda = false; + var limChar; + if(requiresSignature) { + limChar = this.scanner.pos; + if(this.currentToken.tokenId === TypeScript.TokenID.OpenBrace) { + this.reportParseError("Function declarations are not permitted within interfaces, ambient modules or classes"); + bod = new TypeScript.ASTList(); + var bodMinChar = this.scanner.startPos; + this.parseFunctionBlock(errorRecoverySet, allowedElements, parentModifiers, bod, bodMinChar); + this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); + if(this.currentToken.tokenId === TypeScript.TokenID.Semicolon) { + this.currentToken = this.scanner.scan(); + } + } else { + this.checkCurrentToken(TypeScript.TokenID.Semicolon, errorRecoverySet, "Expected ';'"); + } + } else { + bod = new TypeScript.ASTList(); + var bodMinChar = this.scanner.startPos; + if(this.currentToken.tokenId == TypeScript.TokenID.EqualsGreaterThan) { + if(isMethod) { + this.reportParseError("'=>' may not be used for class methods"); + } + wasShorthand = true; + this.currentToken = this.scanner.scan(); + } + if(wasShorthand && this.currentToken.tokenId != TypeScript.TokenID.OpenBrace) { + var retExpr = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.Assignment, true, TypeContext.NoTypes); + var retStmt = new TypeScript.ReturnStatement(); + retStmt.returnExpression = retExpr; + retStmt.minChar = retExpr.minChar; + retStmt.limChar = retExpr.limChar; + bod.minChar = bodMinChar; + bod.append(retStmt); + } else { + isAnonLambda = wasShorthand; + this.parseFunctionBlock(errorRecoverySet, allowedElements, parentModifiers, bod, bodMinChar); + } + limChar = this.scanner.pos; + } + var funcDecl = new TypeScript.FuncDecl(name, bod, isConstructor, args, this.topVarList(), this.topScopeList(), this.topStaticsList(), TypeScript.NodeType.FuncDecl); + this.popDeclLists(); + var scopeList = this.topScopeList(); + scopeList.append(funcDecl); + var staticFuncDecl = false; + if(!requiresSignature) { + if(!wasShorthand || isAnonLambda) { + funcDecl.endingToken = new TypeScript.ASTSpan(); + funcDecl.endingToken.minChar = this.scanner.startPos; + funcDecl.endingToken.limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); + if(isAnonLambda) { + funcDecl.fncFlags |= TypeScript.FncFlags.IsFatArrowFunction; + } + } else { + funcDecl.fncFlags |= TypeScript.FncFlags.IsFatArrowFunction; + funcDecl.endingToken = new TypeScript.ASTSpan(); + funcDecl.endingToken.minChar = bod.members[0].minChar; + funcDecl.endingToken.limChar = bod.members[0].limChar; + } + } + funcDecl.minChar = minChar; + funcDecl.limChar = limChar; + if(!requiresSignature) { + funcDecl.fncFlags |= TypeScript.FncFlags.Definition; + } + this.statementInfoStack = svStmtStack; + return funcDecl; + }; + Parser.prototype.transformAnonymousArgsIntoFormals = function (formals, argList) { + var _this = this; + var translateBinExOperand = function (operand) { + if(operand.nodeType == TypeScript.NodeType.Comma) { + return _this.transformAnonymousArgsIntoFormals(formals, operand); + } else { + if(operand.nodeType == TypeScript.NodeType.Name || operand.nodeType == TypeScript.NodeType.Asg) { + var opArg = operand.nodeType == TypeScript.NodeType.Asg ? (operand).operand1 : operand; + var arg = new TypeScript.ArgDecl(opArg); + arg.preComments = opArg.preComments; + arg.postComments = opArg.postComments; + arg.minChar = operand.minChar; + arg.limChar = operand.limChar; + if(TypeScript.hasFlag(opArg.flags, TypeScript.ASTFlags.PossibleOptionalParameter)) { + arg.isOptional = true; + } + if(operand.nodeType == TypeScript.NodeType.Asg) { + arg.init = (operand).operand2; + } + formals.append(arg); + return arg.isOptional || arg.init; + } else { + _this.reportParseError("Invalid lambda argument"); + } + } + return false; + }; + if(argList) { + if(argList.nodeType == TypeScript.NodeType.Comma) { + var commaList = argList; + if(commaList.operand1.isParenthesized) { + this.reportParseError("Invalid lambda argument", commaList.operand1.minChar, commaList.operand1.limChar); + } + if(commaList.operand2.isParenthesized) { + this.reportParseError("Invalid lambda argument", commaList.operand2.minChar, commaList.operand2.limChar); + } + var isOptional = translateBinExOperand(commaList.operand1); + isOptional = translateBinExOperand(commaList.operand2) || isOptional; + return isOptional; + } else { + return translateBinExOperand(argList); + } + } + }; + Parser.prototype.parseFormalParameterList = function (errorRecoverySet, formals, isClassConstr, isSig, isIndexer, isGetter, isSetter, isLambda, preProcessedLambdaArgs, expectClosingRParen) { + formals.minChar = this.scanner.startPos; + if(isIndexer) { + this.currentToken = this.scanner.scan(); + } else { + if(!isLambda) { + this.checkCurrentToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.RParen); + } + } + var sawEllipsis = false; + var firstArg = true; + var hasOptional = false; + var haveFirstArgID = false; + if(isLambda && preProcessedLambdaArgs && preProcessedLambdaArgs.nodeType != TypeScript.NodeType.EmptyExpr) { + hasOptional = this.transformAnonymousArgsIntoFormals(formals, preProcessedLambdaArgs); + haveFirstArgID = true; + } + while(true) { + var munchedArg = false; + var argFlags = TypeScript.VarFlags.None; + var argMinChar = this.scanner.startPos; + if(this.inferPropertiesFromThisAssignment && this.currentToken.tokenId == TypeScript.TokenID.This) { + if(!isClassConstr) { + this.reportParseError("Instance property declarations using 'this' may only be used in class constructors"); + } + this.currentToken = this.scanner.scan(); + argFlags |= (TypeScript.VarFlags.Public | TypeScript.VarFlags.Property); + if(this.currentClassDefinition) { + this.currentClassDefinition.varFlags |= TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor; + } + } + if(this.currentToken.tokenId == TypeScript.TokenID.Public) { + argFlags |= (TypeScript.VarFlags.Public | TypeScript.VarFlags.Property); + if(this.currentClassDefinition) { + this.currentClassDefinition.varFlags |= TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor; + } + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.Private) { + argFlags |= (TypeScript.VarFlags.Private | TypeScript.VarFlags.Property); + if(this.currentClassDefinition) { + this.currentClassDefinition.varFlags |= TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor; + } + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.Static && isClassConstr) { + this.reportParseError("Static properties can not be declared as parameter properties"); + this.currentToken = this.scanner.scan(); + } + } + } + if(argFlags != TypeScript.VarFlags.None) { + if(!isClassConstr) { + this.reportParseError("only constructor parameters can be properties"); + } + this.currentToken = this.scanner.scan(); + if(TypeScript.isModifier(this.currentToken)) { + this.reportParseError("Multiple modifiers may not be applied to parameters"); + this.currentToken = this.scanner.scan(); + } + if(this.inferPropertiesFromThisAssignment && this.currentToken.tokenId == TypeScript.TokenID.This) { + if(!isClassConstr) { + this.reportParseError("Instance property declarations using 'this' may only be used in class constructors"); + } + this.currentToken = this.scanner.scan(); + this.currentToken = this.scanner.scan(); + } + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.DotDotDot) { + sawEllipsis = true; + this.currentToken = this.scanner.scan(); + if(!(this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + this.reportParseError("'...' parameters require both a parameter name and an array type annotation to be specified"); + sawEllipsis = false; + } + } + } + var argId = null; + if(!haveFirstArgID && (this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + argId = TypeScript.Identifier.fromToken(this.currentToken); + argId.minChar = this.scanner.startPos; + argId.limChar = this.scanner.pos; + } + if(haveFirstArgID || argId) { + munchedArg = true; + var type = null; + var arg = null; + if(haveFirstArgID && formals.members.length) { + arg = formals.members[formals.members.length - 1]; + if(arg.isOptional) { + hasOptional = true; + } + } else { + arg = new TypeScript.ArgDecl(argId); + if(isGetter) { + this.reportParseError("Property getters may not take any arguments"); + } + if(isSetter && !firstArg) { + this.reportParseError("Property setters may only take one argument"); + } + arg.minChar = argMinChar; + arg.preComments = this.parseComments(); + this.currentToken = this.scanner.scan(); + } + if(this.currentToken.tokenId == TypeScript.TokenID.Question) { + arg.isOptional = true; + hasOptional = true; + this.currentToken = this.scanner.scan(); + } + if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { + this.currentToken = this.scanner.scan(); + type = this.parseTypeReference(errorRecoverySet, false); + } + if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { + if(isSig) { + this.reportParseError("Arguments in signatures may not have default values"); + } + hasOptional = true; + this.currentToken = this.scanner.scan(); + arg.init = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, false, TypeContext.NoTypes); + } + if(hasOptional && !arg.isOptionalArg() && !sawEllipsis) { + this.reportParseError("Optional parameters may only be followed by other optional parameters"); + } + if(sawEllipsis && arg.isOptionalArg()) { + this.reportParseError("Varargs may not be optional or have default parameters"); + } + if(sawEllipsis && !type) { + this.reportParseError("'...' parameters require both a parameter name and an array type annotation to be specified"); + } + arg.postComments = this.parseComments(); + arg.typeExpr = type; + arg.limChar = this.scanner.lastTokenLimChar(); + arg.varFlags |= argFlags; + if(!haveFirstArgID) { + formals.append(arg); + } else { + haveFirstArgID = false; + } + } + firstArg = false; + if(this.currentToken.tokenId == TypeScript.TokenID.Comma) { + if((munchedArg) && (!sawEllipsis)) { + this.currentToken = this.scanner.scan(); + continue; + } else { + this.reportParseError("Unexpected ',' in argument list"); + if(this.errorRecovery) { + this.currentToken = this.scanner.scan(); + continue; + } + } + } else { + break; + } + } + if(isIndexer) { + this.checkCurrentToken(TypeScript.TokenID.CloseBracket, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly | TypeScript.ErrorRecoverySet.SColon); + } else { + if(expectClosingRParen) { + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly | TypeScript.ErrorRecoverySet.SColon); + } + } + formals.limChar = this.scanner.lastTokenLimChar(); + return sawEllipsis; + }; + Parser.prototype.parseFncDecl = function (errorRecoverySet, isDecl, requiresSignature, isMethod, methodName, indexer, isStatic, markedAsAmbient, modifiers, lambdaArgContext, expectClosingRParen) { + var leftCurlyCount = this.scanner.leftCurlyCount; + var rightCurlyCount = this.scanner.rightCurlyCount; + var prevInConstr = this.parsingClassConstructorDefinition; + this.parsingClassConstructorDefinition = false; + var name = null; + var fnMin = this.scanner.startPos; + var minChar = this.scanner.pos; + var prevNestingLevel = this.nestingLevel; + var preComments = this.parseComments(); + var isLambda = !!lambdaArgContext; + this.nestingLevel = 0; + if((!this.style_funcInLoop) && this.inLoop()) { + this.reportParseStyleError("function declaration in loop"); + } + if(!isMethod && !isStatic && !indexer && !lambdaArgContext) { + this.currentToken = this.scanner.scan(); + this.state = ParseState.StartFncDecl; + if((this.currentToken.tokenId != TypeScript.TokenID.Identifier) && (!TypeScript.convertTokToID(this.currentToken, this.strictMode))) { + if(isDecl) { + this.reportParseError("Function declaration must include identifier"); + this.nestingLevel = prevNestingLevel; + return new TypeScript.IncompleteAST(fnMin, this.scanner.pos); + } + } else { + name = TypeScript.Identifier.fromToken(this.currentToken); + name.minChar = this.scanner.startPos; + name.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + } + } else { + if(methodName) { + name = methodName; + } + } + this.state = ParseState.FncDeclName; + var args = new TypeScript.ASTList(); + var variableArgList = false; + var isOverload = false; + var isGetter = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter); + var isSetter = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Setter); + if((this.currentToken.tokenId == TypeScript.TokenID.OpenParen) || (indexer && (this.currentToken.tokenId == TypeScript.TokenID.OpenBracket)) || (lambdaArgContext && (lambdaArgContext.preProcessedLambdaArgs || this.currentToken.tokenId == TypeScript.TokenID.DotDotDot))) { + variableArgList = this.parseFormalParameterList(errorRecoverySet, args, false, requiresSignature, indexer, isGetter, isSetter, isLambda, lambdaArgContext ? lambdaArgContext.preProcessedLambdaArgs : null, expectClosingRParen); + } + this.state = ParseState.FncDeclArgs; + var returnType = null; + if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { + this.currentToken = this.scanner.scan(); + if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Setter)) { + this.reportParseError("Property setters may not declare a return type"); + } + returnType = this.parseTypeReference(errorRecoverySet, true); + } + if(indexer && args.members.length == 0) { + this.reportParseError("Index signatures require a parameter type to be specified"); + } + this.state = ParseState.FncDeclReturnType; + if(isLambda && this.currentToken.tokenId != TypeScript.TokenID.EqualsGreaterThan) { + this.reportParseError("Expected '=>'"); + } + if(isDecl && !(this.parsingDeclareFile || markedAsAmbient) && (!isMethod || !(this.ambientModule || this.ambientClass || this.inInterfaceDecl)) && this.currentToken.tokenId == TypeScript.TokenID.Semicolon) { + isOverload = true; + isDecl = false; + requiresSignature = true; + } + var svInFncDecl = this.inFncDecl; + this.inFncDecl = true; + var funcDecl = this.parseFunctionStatements(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, name, false, isMethod, args, TypeScript.AllowedElements.None, minChar, requiresSignature, TypeScript.Modifiers.None); + this.inFncDecl = svInFncDecl; + funcDecl.variableArgList = variableArgList; + funcDecl.isOverload = isOverload; + if(!requiresSignature) { + funcDecl.fncFlags |= TypeScript.FncFlags.Definition; + } + if(isStatic) { + funcDecl.fncFlags |= TypeScript.FncFlags.Static; + } + if(requiresSignature) { + funcDecl.fncFlags |= TypeScript.FncFlags.Signature; + } + if(indexer) { + funcDecl.fncFlags |= TypeScript.FncFlags.IndexerMember; + } + funcDecl.returnTypeAnnotation = returnType; + if(isMethod) { + funcDecl.fncFlags |= TypeScript.FncFlags.Method; + funcDecl.fncFlags |= TypeScript.FncFlags.ClassPropertyMethodExported; + } + funcDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; + funcDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; + this.nestingLevel = prevNestingLevel; + this.parsingClassConstructorDefinition = prevInConstr; + funcDecl.preComments = preComments; + return funcDecl; + }; + Parser.prototype.convertToTypeReference = function (ast) { + var result; + switch(ast.nodeType) { + case TypeScript.NodeType.TypeRef: { + return ast; + + } + case TypeScript.NodeType.Name: { + result = new TypeScript.TypeReference(ast, 0); + result.minChar = ast.minChar; + result.limChar = ast.limChar; + return result; + + } + case TypeScript.NodeType.Index: { + var expr = ast; + result = this.convertToTypeReference(expr.operand1); + if(result) { + result.arrayCount++; + result.minChar = expr.minChar; + result.limChar = expr.limChar; + return result; + } else { + var etr = new TypeScript.AST(TypeScript.NodeType.Error); + return etr; + } + } + + } + return null; + }; + Parser.prototype.parseArgList = function (errorRecoverySet) { + var args = new TypeScript.ASTList(); + args.minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId !== TypeScript.TokenID.CloseParen) { + while(true) { + if(args.members.length > 65535) { + this.reportParseError("max number of args exceeded"); + break; + } + var arg = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); + args.append(arg); + if(this.currentToken.tokenId != TypeScript.TokenID.Comma) { + break; + } + this.currentToken = this.scanner.scan(); + } + } + args.limChar = this.scanner.pos; + return args; + }; + Parser.prototype.parseBaseList = function (extendsList, implementsList, errorRecoverySet, isClass) { + var keyword = true; + var currentList = extendsList; + for(; ; ) { + if(keyword) { + if(this.currentToken.tokenId === TypeScript.TokenID.Implements) { + currentList = implementsList; + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.Extends && !this.requiresExtendsBlock) { + this.requiresExtendsBlock = isClass; + } + } + this.currentToken = this.scanner.scan(); + keyword = false; + } + var baseName = null; + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + var minChar = this.scanner.startPos; + baseName = TypeScript.Identifier.fromToken(this.currentToken); + baseName.minChar = minChar; + baseName.limChar = this.scanner.pos; + baseName = this.parseNamedType(errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly, minChar, baseName, false); + } else { + this.reportParseError("Expected base name"); + if(this.errorRecovery) { + baseName = new TypeScript.MissingIdentifier(); + baseName.minChar = this.scanner.pos; + baseName.limChar = this.scanner.pos; + baseName.flags |= TypeScript.ASTFlags.Error; + } + } + if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { + if(isClass) { + this.reportParseError("Base classes may only be initialized via a 'super' call within the constructor body"); + } else { + this.reportParseError("Interfaces may not be extended with a call expression"); + } + } else { + currentList.append(baseName); + } + if(isClass && currentList == extendsList && extendsList.members.length > 1) { + this.reportParseError("A class may only extend one other class"); + } + if(this.currentToken.tokenId == TypeScript.TokenID.Comma) { + this.currentToken = this.scanner.scan(); + continue; + } else { + if((this.currentToken.tokenId == TypeScript.TokenID.Extends) || (this.currentToken.tokenId == TypeScript.TokenID.Implements)) { + if(this.currentToken.tokenId == TypeScript.TokenID.Extends && !this.requiresExtendsBlock) { + this.requiresExtendsBlock = isClass; + } + currentList = extendsList; + keyword = true; + continue; + } + } + break; + } + }; + Parser.prototype.parseClassDecl = function (errorRecoverySet, minChar, modifiers) { + var leftCurlyCount = this.scanner.leftCurlyCount; + var rightCurlyCount = this.scanner.rightCurlyCount; + if((modifiers & TypeScript.Modifiers.Readonly) != TypeScript.Modifiers.None) { + this.reportParseError("const modifier is implicit for class"); + } + if(this.parsingDeclareFile || this.ambientModule) { + modifiers |= TypeScript.Modifiers.Ambient; + modifiers |= TypeScript.Modifiers.Exported; + } + var classIsMarkedAsAmbient = this.parsingDeclareFile || (modifiers & TypeScript.Modifiers.Ambient) != TypeScript.Modifiers.None; + var svAmbientClass = this.ambientClass; + this.ambientClass = classIsMarkedAsAmbient; + this.currentToken = this.scanner.scan(); + var name = null; + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || (!TypeScript.isPrimitiveTypeToken(this.currentToken) && TypeScript.convertTokToID(this.currentToken, this.strictMode))) { + name = TypeScript.Identifier.fromToken(this.currentToken); + name.minChar = this.scanner.startPos; + name.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + } else { + this.reportParseError("class missing name"); + if(this.errorRecovery) { + name = new TypeScript.MissingIdentifier(); + name.minChar = this.scanner.pos; + name.limChar = this.scanner.pos; + name.flags |= TypeScript.ASTFlags.Error; + } + } + var extendsList = null; + var implementsList = null; + var requiresSignature = false; + if((this.currentToken.tokenId == TypeScript.TokenID.Extends) || (this.currentToken.tokenId == TypeScript.TokenID.Implements)) { + extendsList = new TypeScript.ASTList(); + implementsList = new TypeScript.ASTList(); + this.parseBaseList(extendsList, implementsList, errorRecoverySet, true); + } + var classDecl = new TypeScript.ClassDeclaration(name, new TypeScript.ASTList(), extendsList, implementsList); + this.currentClassDefinition = classDecl; + this.parseClassElements(classDecl, errorRecoverySet, modifiers); + if(this.ambientModule || this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { + classDecl.varFlags |= TypeScript.VarFlags.Exported; + } + if(this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + classDecl.varFlags |= TypeScript.VarFlags.Ambient; + } + classDecl.varFlags |= TypeScript.VarFlags.Class; + this.ambientClass = svAmbientClass; + classDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; + classDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; + return classDecl; + }; + Parser.prototype.parseClassElements = function (classDecl, errorRecoverySet, parentModifiers) { + var modifiers = parentModifiers; + var resetModifiers = false; + var membersMinChar = this.scanner.startPos; + this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet); + this.nestingLevel++; + var currentMemberMinChar = this.scanner.startPos; + var wasGetOrSetId = false; + while(!(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace || this.currentToken.tokenId == TypeScript.TokenID.EndOfFile)) { + var scanNext = true; + var publicOrPrivateFlags = TypeScript.Modifiers.Public | TypeScript.Modifiers.Private; + if(this.currentToken.tokenId == TypeScript.TokenID.Get) { + if(modifiers & TypeScript.Modifiers.Getter) { + this.reportParseError("Duplicate 'get' declaration in class body"); + } + if(modifiers & TypeScript.Modifiers.Setter) { + this.reportParseError("Getter already marked as a setter"); + } + modifiers |= TypeScript.Modifiers.Getter; + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.Set) { + if(modifiers & TypeScript.Modifiers.Setter) { + this.reportParseError("Duplicate 'set' declaration in class body"); + } + if(modifiers & TypeScript.Modifiers.Getter) { + this.reportParseError("Setter already marked as a getter"); + } + modifiers |= TypeScript.Modifiers.Setter; + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.Private) { + if(modifiers & publicOrPrivateFlags) { + this.reportParseError("Multiple modifiers may not be applied to class members"); + } + modifiers |= TypeScript.Modifiers.Private; + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.Public) { + if(modifiers & publicOrPrivateFlags) { + this.reportParseError("Multiple modifiers may not be applied to class members"); + } + modifiers |= TypeScript.Modifiers.Public; + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.Static) { + if(modifiers & TypeScript.Modifiers.Static) { + this.reportParseError("Multiple modifiers may not be applied to class members"); + } + modifiers |= TypeScript.Modifiers.Static; + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.Constructor) { + if(modifiers != parentModifiers) { + this.reportParseError("Constructors may not have modifiers"); + } + this.parseClassConstructorDeclaration(currentMemberMinChar, errorRecoverySet, modifiers); + scanNext = false; + resetModifiers = true; + } else { + if(wasGetOrSetId || this.currentToken.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToIDName(this.currentToken)) { + var idText = wasGetOrSetId ? ((modifiers & TypeScript.Modifiers.Getter) ? "get" : "set") : this.currentToken.getText(); + var id = wasGetOrSetId ? new TypeScript.Identifier(idText) : TypeScript.Identifier.fromToken(this.currentToken); + id.minChar = this.scanner.startPos; + id.limChar = this.scanner.pos; + if(wasGetOrSetId) { + modifiers = modifiers ^ ((modifiers & TypeScript.Modifiers.Getter) ? TypeScript.Modifiers.Getter : TypeScript.Modifiers.Setter); + wasGetOrSetId = false; + } else { + this.currentToken = this.scanner.scan(); + } + if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { + this.parseClassMemberFunctionDeclaration(id, currentMemberMinChar, errorRecoverySet, modifiers); + scanNext = false; + } else { + if(modifiers & TypeScript.Modifiers.Getter || modifiers & TypeScript.Modifiers.Setter) { + this.reportParseError("Property accessors must be functions"); + } + var varDecl = this.parseClassMemberVariableDeclaration(id, currentMemberMinChar, false, errorRecoverySet, modifiers); + if(varDecl.init && varDecl.init.nodeType == TypeScript.NodeType.FuncDecl) { + if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { + scanNext = false; + } + } else { + if(varDecl.init && varDecl.init.nodeType == TypeScript.NodeType.ObjectLit && this.currentToken.tokenId != TypeScript.TokenID.Semicolon) { + scanNext = false; + varDecl.init.flags |= TypeScript.ASTFlags.AutomaticSemicolon; + } else { + if(this.currentToken.tokenId != TypeScript.TokenID.Semicolon) { + this.reportParseError("Expected ';'"); + scanNext = false; + } + } + } + } + resetModifiers = true; + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.Super) { + this.reportParseError("Base class initializers must be the first statement in a class definition"); + } else { + if(!wasGetOrSetId && ((modifiers & TypeScript.Modifiers.Getter) || (modifiers & TypeScript.Modifiers.Setter)) && ((this.currentToken.tokenId == TypeScript.TokenID.OpenParen) || (this.currentToken.tokenId == TypeScript.TokenID.Equals) || (this.currentToken.tokenId == TypeScript.TokenID.Colon) || (this.currentToken.tokenId == TypeScript.TokenID.Semicolon))) { + wasGetOrSetId = true; + scanNext = false; + } else { + if(this.currentToken.tokenId != TypeScript.TokenID.Semicolon) { + this.reportParseError("Unexpected '" + this.currentToken.getText() + "' in class definition"); + resetModifiers = true; + } + } + } + } + } + } + } + } + } + } + if(scanNext) { + this.currentToken = this.scanner.scan(); + } + if(resetModifiers) { + modifiers = parentModifiers; + currentMemberMinChar = this.scanner.startPos; + resetModifiers = false; + } + } + var membersLimChar = this.scanner.pos; + if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { + classDecl.endingToken = new TypeScript.ASTSpan(); + classDecl.endingToken.minChar = this.scanner.startPos; + classDecl.endingToken.limChar = this.scanner.pos; + if(!this.currentClassDefinition.members.members.length) { + this.currentClassDefinition.preComments = this.parseComments(); + } + this.currentToken = this.scanner.scan(); + } + this.nestingLevel--; + this.currentClassDefinition.members.minChar = membersMinChar; + this.currentClassDefinition.members.limChar = membersLimChar; + this.currentClassDefinition.limChar = membersLimChar; + this.currentClassDefinition = null; + }; + Parser.prototype.parseClassConstructorDeclaration = function (minChar, errorRecoverySet, modifiers) { + this.parsingClassConstructorDefinition = true; + var isAmbient = this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient); + var args = new TypeScript.ASTList(); + var variableArgList = false; + var preComments = this.parseComments(); + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { + variableArgList = this.parseFormalParameterList(errorRecoverySet, args, true, isAmbient, false, false, false, false, null, true); + if(args.members.length > 0) { + var lastArg = args.members[args.members.length - 1]; + } + } + var requiresSignature = isAmbient || this.currentToken.tokenId == TypeScript.TokenID.Semicolon; + if(requiresSignature) { + for(var i = 0; i < args.members.length; i++) { + var arg = args.members[i]; + if(TypeScript.hasFlag(arg.varFlags, TypeScript.VarFlags.Property)) { + this.reportParseError("Overload or ambient signatures may not specify parameter properties", arg.minChar, arg.limChar); + } + } + } + if(!requiresSignature) { + this.currentClassDefinition.constructorNestingLevel = this.nestingLevel + 1; + } + var constructorFuncDecl = this.parseFunctionStatements(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, this.currentClassDefinition.name, true, false, args, TypeScript.AllowedElements.Properties, minChar, requiresSignature, modifiers); + constructorFuncDecl.preComments = preComments; + if(requiresSignature && !isAmbient) { + constructorFuncDecl.isOverload = true; + } + constructorFuncDecl.variableArgList = variableArgList; + this.currentClassDecl = null; + constructorFuncDecl.returnTypeAnnotation = this.convertToTypeReference(this.currentClassDefinition.name); + constructorFuncDecl.classDecl = this.currentClassDefinition; + if(isAmbient) { + constructorFuncDecl.fncFlags |= TypeScript.FncFlags.Ambient; + } + if(requiresSignature) { + constructorFuncDecl.fncFlags |= TypeScript.FncFlags.Signature; + } + if(this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { + constructorFuncDecl.fncFlags |= TypeScript.FncFlags.Exported; + } + if(this.currentClassDefinition.constructorDecl) { + if(!isAmbient && !this.currentClassDefinition.constructorDecl.isSignature() && !constructorFuncDecl.isSignature()) { + this.reportParseError("Duplicate constructor definition"); + } + } + if(isAmbient || !constructorFuncDecl.isSignature()) { + this.currentClassDefinition.constructorDecl = constructorFuncDecl; + } + constructorFuncDecl.fncFlags |= TypeScript.FncFlags.ClassMethod; + this.currentClassDefinition.members.members[this.currentClassDefinition.members.members.length] = constructorFuncDecl; + this.parsingClassConstructorDefinition = false; + return constructorFuncDecl; + }; + Parser.prototype.parseClassMemberVariableDeclaration = function (text, minChar, isDeclaredInConstructor, errorRecoverySet, modifiers) { + var varDecl = new TypeScript.VarDecl(text, this.nestingLevel); + varDecl.minChar = minChar; + var isStatic = false; + varDecl.preComments = this.parseComments(); + if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { + this.currentToken = this.scanner.scan(); + varDecl.typeExpr = this.parseTypeReference(errorRecoverySet | TypeScript.ErrorRecoverySet.Asg | TypeScript.ErrorRecoverySet.Comma, false); + if(varDecl.typeExpr && varDecl.typeExpr.nodeType == TypeScript.NodeType.TypeRef) { + var typeExpr = (varDecl.typeExpr); + if(typeExpr.term && typeExpr.term.nodeType == TypeScript.NodeType.FuncDecl) { + typeExpr.term.preComments = varDecl.preComments; + } + } + } + if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { + if(this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + this.reportParseError("context does not permit variable initializer"); + if(this.errorRecovery) { + this.skip(errorRecoverySet); + varDecl.flags |= TypeScript.ASTFlags.Error; + varDecl.limChar = this.scanner.lastTokenLimChar(); + return varDecl; + } + } + this.currentToken = this.scanner.scan(); + varDecl.init = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); + varDecl.limChar = varDecl.init.limChar; + if(!(modifiers & TypeScript.Modifiers.Static)) { + this.currentClassDefinition.varFlags |= TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor; + } + } else { + varDecl.limChar = this.scanner.pos; + } + if(modifiers & TypeScript.Modifiers.Static) { + varDecl.varFlags |= TypeScript.VarFlags.Static; + isStatic = true; + } + if((modifiers & TypeScript.Modifiers.Private) != TypeScript.Modifiers.None) { + varDecl.varFlags |= TypeScript.VarFlags.Private; + } else { + varDecl.varFlags |= TypeScript.VarFlags.Public; + } + varDecl.varFlags |= TypeScript.VarFlags.Property; + if(isDeclaredInConstructor) { + varDecl.varFlags |= TypeScript.VarFlags.ClassConstructorProperty; + } + if(!isDeclaredInConstructor && !isStatic) { + varDecl.varFlags |= TypeScript.VarFlags.ClassBodyProperty; + } + this.currentClassDefinition.knownMemberNames[text.actualText] = true; + if(!isDeclaredInConstructor) { + this.currentClassDefinition.members.members[this.currentClassDefinition.members.members.length] = varDecl; + } + varDecl.postComments = this.parseComments(); + return varDecl; + }; + Parser.prototype.parseClassMemberFunctionDeclaration = function (methodName, minChar, errorRecoverySet, modifiers) { + var wasAccessorID = this.prevIDTok != null; + var isAccessor = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter) || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Setter); + var isStatic = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Static); + var isAmbient = this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient); + errorRecoverySet |= TypeScript.ErrorRecoverySet.RParen; + if(isAccessor && (modifiers & TypeScript.Modifiers.Ambient)) { + this.reportParseError("Property accessors may not be declared in ambient classes"); + } + var ast = this.parseFncDecl(errorRecoverySet, true, isAmbient, true, methodName, false, isStatic, isAmbient, modifiers, null, true); + if(ast.nodeType == TypeScript.NodeType.Error) { + return ast; + } + var funcDecl = ast; + funcDecl.minChar = minChar; + if(funcDecl.bod !== null) { + funcDecl.limChar = funcDecl.bod.limChar; + } + if(modifiers & TypeScript.Modifiers.Private) { + funcDecl.fncFlags |= TypeScript.FncFlags.Private; + } else { + funcDecl.fncFlags |= TypeScript.FncFlags.Public; + } + if(isStatic) { + funcDecl.fncFlags |= TypeScript.FncFlags.Static; + } + if(isAccessor) { + if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter)) { + funcDecl.fncFlags |= TypeScript.FncFlags.GetAccessor; + funcDecl.hint = "get" + funcDecl.name.actualText; + } else { + funcDecl.fncFlags |= TypeScript.FncFlags.SetAccessor; + funcDecl.hint = "set" + funcDecl.name.actualText; + } + funcDecl.fncFlags |= TypeScript.FncFlags.IsFunctionExpression; + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("Property accessors are only available when targeting ES5 or greater", funcDecl.minChar, funcDecl.limChar); + } + } + funcDecl.fncFlags |= TypeScript.FncFlags.ClassMethod; + this.currentClassDefinition.knownMemberNames[methodName.actualText] = true; + this.currentClassDefinition.members.members[this.currentClassDefinition.members.members.length] = funcDecl; + return funcDecl; + }; + Parser.prototype.parseTypeMember = function (errorRecoverySet) { + var minChar = this.scanner.startPos; + var propertyDecl = this.parsePropertyDeclaration(errorRecoverySet, TypeScript.Modifiers.Public, true, false); + if(propertyDecl) { + propertyDecl.minChar = minChar; + if(propertyDecl.nodeType == TypeScript.NodeType.VarDecl) { + this.checkCurrentToken(TypeScript.TokenID.Semicolon, errorRecoverySet); + } + } + return propertyDecl; + }; + Parser.prototype.parseTypeMemberList = function (errorRecoverySet, members) { + errorRecoverySet |= TypeScript.ErrorRecoverySet.TypeScriptS; + while(true) { + switch(this.currentToken.tokenId) { + case TypeScript.TokenID.CloseBrace: + case TypeScript.TokenID.EndOfFile: { + members.limChar = this.scanner.pos; + return; + + } + } + var element = this.parseTypeMember(errorRecoverySet); + if(element) { + members.append(element); + } + } + }; + Parser.prototype.parseInterfaceDecl = function (errorRecoverySet, modifiers) { + var leftCurlyCount = this.scanner.leftCurlyCount; + var rightCurlyCount = this.scanner.rightCurlyCount; + this.currentToken = this.scanner.scan(); + var minChar = this.scanner.pos; + var name = null; + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || (!TypeScript.isPrimitiveTypeToken(this.currentToken) && TypeScript.convertTokToID(this.currentToken, this.strictMode))) { + name = TypeScript.Identifier.fromToken(this.currentToken); + name.minChar = this.scanner.startPos; + name.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + } else { + this.reportParseError("interface missing name"); + if(this.errorRecovery) { + name = new TypeScript.MissingIdentifier(); + name.minChar = this.scanner.pos; + name.limChar = this.scanner.pos; + name.flags |= TypeScript.ASTFlags.Error; + } + } + var extendsList = null; + var implementsList = null; + if(this.currentToken.tokenId === TypeScript.TokenID.Extends || this.currentToken.tokenId === TypeScript.TokenID.Implements) { + if(this.currentToken.tokenId === TypeScript.TokenID.Implements) { + this.reportParseError("Expected 'extends'"); + } + extendsList = new TypeScript.ASTList(); + implementsList = new TypeScript.ASTList(); + extendsList.minChar = this.scanner.startPos; + this.parseBaseList(extendsList, implementsList, errorRecoverySet, false); + } + var membersMinChar = this.scanner.startPos; + this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.TypeScriptS); + var members = new TypeScript.ASTList(); + members.minChar = membersMinChar; + var prevInInterfaceDecl = this.inInterfaceDecl; + this.inInterfaceDecl = true; + this.parseTypeMemberList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, members); + this.inInterfaceDecl = prevInInterfaceDecl; + this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); + var interfaceDecl = new TypeScript.InterfaceDeclaration(name, members, extendsList, null); + if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Private)) { + interfaceDecl.varFlags |= TypeScript.VarFlags.Private; + } + if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Public)) { + interfaceDecl.varFlags |= TypeScript.VarFlags.Public; + } + if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { + interfaceDecl.varFlags |= TypeScript.VarFlags.Exported; + } + interfaceDecl.limChar = members.limChar; + interfaceDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; + interfaceDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; + return interfaceDecl; + }; + Parser.prototype.makeVarDecl = function (id, nest) { + var varDecl = new TypeScript.VarDecl(id, nest); + var currentVarList = this.topVarList(); + if(currentVarList) { + currentVarList.append(varDecl); + } + return varDecl; + }; + Parser.prototype.parsePropertyDeclaration = function (errorRecoverySet, modifiers, requireSignature, isStatic) { + var text = null; + var minChar = this.scanner.startPos; + var nameLimChar = minChar; + var isNew = false; + var isIndexer = false; + var wasAccessorID = this.prevIDTok != null; + var isAccessor = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter) || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Setter); + if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + requireSignature = true; + } + if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen && !wasAccessorID) { + if(!requireSignature && !isStatic) { + this.reportParseError("Expected identifier in property declaration"); + if(this.errorRecovery) { + this.skip(errorRecoverySet); + text = new TypeScript.MissingIdentifier(); + } + } + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.New) { + if(requireSignature) { + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { + isNew = true; + } + } + if(!isNew) { + if(!requireSignature) { + this.currentToken = this.scanner.scan(); + } + text = new TypeScript.Identifier("new"); + text.minChar = this.scanner.pos - 3; + text.limChar = this.scanner.pos; + nameLimChar = this.scanner.pos; + } + } else { + if((this.currentToken.tokenId == TypeScript.TokenID.OpenBracket) && requireSignature) { + isIndexer = true; + text = new TypeScript.Identifier("__item"); + } else { + if((this.currentToken.tokenId != TypeScript.TokenID.Identifier) && (!TypeScript.convertTokToIDName(this.currentToken)) && !wasAccessorID) { + this.reportParseError("Expected identifier in property declaration"); + if(this.errorRecovery) { + var eminChar = this.scanner.startPos; + var curpos = this.scanner.pos; + this.skip(errorRecoverySet & (~TypeScript.ErrorRecoverySet.Comma)); + if(this.scanner.pos == curpos) { + this.currentToken = this.scanner.scan(); + } + var epd = new TypeScript.VarDecl(new TypeScript.MissingIdentifier(), this.nestingLevel); + epd.flags |= TypeScript.ASTFlags.Error; + epd.minChar = eminChar; + epd.limChar = this.scanner.lastTokenLimChar(); + return epd; + } + } else { + if(wasAccessorID) { + text = TypeScript.Identifier.fromToken(this.prevIDTok); + text.minChar = this.scanner.lastTokenLimChar() - 3; + text.limChar = this.scanner.lastTokenLimChar(); + nameLimChar = text.limChar; + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("Property accessors are only available when targeting ES5 or greater"); + } + if(this.currentToken.getText() == text.actualText && this.currentToken != this.prevIDTok) { + this.currentToken = this.scanner.scan(); + } + this.prevIDTok = null; + } else { + text = TypeScript.Identifier.fromToken(this.currentToken); + text.minChar = this.scanner.startPos; + text.limChar = this.scanner.pos; + nameLimChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + } + } + } + } + } + if(this.currentToken.tokenId == TypeScript.TokenID.Question) { + if(this.inInterfaceDecl && text) { + text.flags |= TypeScript.ASTFlags.OptionalName; + } else { + this.reportParseError("Optional properties may only be declared on interface or object types"); + } + this.currentToken = this.scanner.scan(); + } + if((this.currentToken.tokenId == TypeScript.TokenID.OpenParen) || (isIndexer && (this.currentToken.tokenId == TypeScript.TokenID.OpenBracket))) { + var ers = errorRecoverySet | TypeScript.ErrorRecoverySet.RParen; + if(isIndexer) { + ers = errorRecoverySet | TypeScript.ErrorRecoverySet.RBrack; + } + var ast = this.parseFncDecl(ers, true, requireSignature, !this.inFncDecl, text, isIndexer, isStatic, (this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)), modifiers, null, true); + var funcDecl; + if(ast.nodeType == TypeScript.NodeType.Error) { + return ast; + } else { + funcDecl = ast; + } + if(funcDecl.name) { + funcDecl.name.minChar = minChar; + funcDecl.name.limChar = nameLimChar; + } + if((modifiers & TypeScript.Modifiers.Public) != TypeScript.Modifiers.None) { + funcDecl.fncFlags |= TypeScript.FncFlags.Public; + } + if((modifiers & TypeScript.Modifiers.Private) != TypeScript.Modifiers.None) { + funcDecl.fncFlags |= TypeScript.FncFlags.Private; + } + if(isStatic) { + funcDecl.fncFlags |= TypeScript.FncFlags.Static; + } + if(this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + funcDecl.fncFlags |= TypeScript.FncFlags.Ambient; + } + if(isAccessor) { + if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter)) { + funcDecl.fncFlags |= TypeScript.FncFlags.GetAccessor; + funcDecl.hint = "get" + funcDecl.name.actualText; + } else { + funcDecl.fncFlags |= TypeScript.FncFlags.SetAccessor; + funcDecl.hint = "set" + funcDecl.name.actualText; + } + funcDecl.fncFlags |= TypeScript.FncFlags.IsFunctionExpression; + if(modifiers & TypeScript.Modifiers.Ambient) { + this.reportParseError("Property accessors may not be declared in ambient types"); + } + } + if(text == null) { + if(isNew) { + funcDecl.fncFlags |= TypeScript.FncFlags.ConstructMember; + funcDecl.hint = "_construct"; + funcDecl.classDecl = this.currentClassDecl; + } else { + funcDecl.hint = "_call"; + funcDecl.fncFlags |= TypeScript.FncFlags.CallMember; + } + } + return funcDecl; + } else { + var varDecl = new TypeScript.VarDecl(text, this.nestingLevel); + varDecl.preComments = this.parseComments(); + varDecl.minChar = minChar; + if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { + this.currentToken = this.scanner.scan(); + varDecl.typeExpr = this.parseTypeReference(errorRecoverySet | TypeScript.ErrorRecoverySet.Asg | TypeScript.ErrorRecoverySet.Comma, false); + if(varDecl.typeExpr && varDecl.typeExpr.nodeType == TypeScript.NodeType.TypeRef) { + var typeExpr = (varDecl.typeExpr); + if(typeExpr.term && typeExpr.term.nodeType == TypeScript.NodeType.FuncDecl) { + typeExpr.term.preComments = varDecl.preComments; + } + } + } + if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { + if(requireSignature) { + this.reportParseError("context does not permit variable initializer"); + if(this.errorRecovery) { + this.skip(errorRecoverySet); + varDecl.flags |= TypeScript.ASTFlags.Error; + varDecl.limChar = this.scanner.lastTokenLimChar(); + return varDecl; + } + } + this.currentToken = this.scanner.scan(); + varDecl.init = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); + varDecl.limChar = varDecl.init.limChar; + if(varDecl.init.nodeType == TypeScript.NodeType.FuncDecl) { + var funcDecl = varDecl.init; + funcDecl.hint = varDecl.id.text; + funcDecl.boundToProperty = varDecl; + } else { + if(isAccessor) { + this.reportParseError("Accessors may only be functions"); + } + } + } else { + varDecl.limChar = this.scanner.pos; + } + if((modifiers & TypeScript.Modifiers.Readonly) != TypeScript.Modifiers.None) { + varDecl.varFlags |= TypeScript.VarFlags.Readonly; + } + if(isStatic) { + varDecl.varFlags |= TypeScript.VarFlags.Static; + } + if((modifiers & TypeScript.Modifiers.Public) != TypeScript.Modifiers.None) { + varDecl.varFlags |= TypeScript.VarFlags.Public; + } + if((modifiers & TypeScript.Modifiers.Private) != TypeScript.Modifiers.None) { + varDecl.varFlags |= TypeScript.VarFlags.Private; + } + varDecl.varFlags |= TypeScript.VarFlags.Property; + return varDecl; + } + }; + Parser.prototype.parseVariableDeclaration = function (errorRecoverySet, modifiers, allowIn, isStatic) { + var isConst = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Readonly); + var minChar = this.scanner.startPos; + var varDecl = null; + var declList = null; + var multivar = false; + this.currentToken = this.scanner.scan(); + var varDeclPreComments = this.parseComments(); + while(true) { + if((this.currentToken.tokenId != TypeScript.TokenID.Identifier) && (!TypeScript.convertTokToID(this.currentToken, this.strictMode))) { + this.reportParseError("Expected identifier in variable declaration"); + if(this.errorRecovery) { + varDecl = new TypeScript.VarDecl(new TypeScript.MissingIdentifier(), this.nestingLevel); + varDecl.minChar = minChar; + this.skip(errorRecoverySet); + varDecl.flags |= TypeScript.ASTFlags.Error; + varDecl.limChar = this.scanner.lastTokenLimChar(); + return varDecl; + } + } + var varDeclName = TypeScript.Identifier.fromToken(this.currentToken); + if(this.strictMode && (varDeclName.text == "eval")) { + this.reportParseError("'eval' may not name a variable in strict mode"); + } + varDecl = this.makeVarDecl(varDeclName, this.nestingLevel); + varDecl.id.minChar = this.scanner.startPos; + varDecl.id.limChar = this.scanner.pos; + varDecl.preComments = varDeclPreComments; + if(isStatic) { + varDecl.varFlags |= TypeScript.VarFlags.Static; + } + if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Readonly)) { + varDecl.varFlags |= TypeScript.VarFlags.Readonly; + } + if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + varDecl.varFlags |= TypeScript.VarFlags.Ambient; + } + if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { + varDecl.varFlags |= TypeScript.VarFlags.Exported; + } + varDecl.minChar = minChar; + if(declList) { + declList.append(varDecl); + } + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { + this.currentToken = this.scanner.scan(); + var prevInFncDecl = this.inFncDecl; + this.inFncDecl = false; + varDecl.typeExpr = this.parseTypeReference(errorRecoverySet | TypeScript.ErrorRecoverySet.Asg | TypeScript.ErrorRecoverySet.Comma, false); + this.inFncDecl = prevInFncDecl; + } + if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { + if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Ambient)) { + this.reportParseError("Ambient variable can not have an initializer"); + } + this.currentToken = this.scanner.scan(); + varDecl.init = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, allowIn, TypeContext.NoTypes); + varDecl.limChar = varDecl.init.limChar; + if(varDecl.init.nodeType == TypeScript.NodeType.FuncDecl) { + var funcDecl = varDecl.init; + funcDecl.hint = varDecl.id.actualText; + } + } else { + if(isConst) { + this.reportParseError("const declaration requires initializer"); + } + varDecl.limChar = this.scanner.pos; + } + varDecl.postComments = this.parseCommentsForLine(this.scanner.line); + if(this.currentToken.tokenId != TypeScript.TokenID.Comma) { + if(declList) { + declList.limChar = varDecl.limChar; + return declList; + } else { + return varDecl; + } + } + if(!multivar) { + declList = new TypeScript.ASTList(); + declList.minChar = varDecl.minChar; + declList.append(varDecl); + multivar = true; + } + this.currentToken = this.scanner.scan(); + minChar = this.scanner.startPos; + } + }; + Parser.prototype.parseMemberList = function (errorRecoverySet) { + var elements = new TypeScript.ASTList(); + if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { + return elements; + } + var idHint = null; + var memberName = null; + var memberExpr = null; + var member = null; + var minChar = this.scanner.startPos; + var isSet = false; + var skippedTokenForGetSetId = false; + var getSetTok = null; + var getSetStartPos = 0; + var getSetPos = 0; + for(; ; ) { + var accessorPattern = false; + if(this.currentToken.tokenId == TypeScript.TokenID.Get || this.currentToken.tokenId == TypeScript.TokenID.Set) { + isSet = this.currentToken.tokenId == TypeScript.TokenID.Set; + getSetTok = this.currentToken; + getSetStartPos = this.scanner.startPos; + getSetPos = this.scanner.pos; + this.currentToken = this.scanner.scan(); + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToIDName(this.currentToken)) { + idHint = isSet ? "set" : "get"; + idHint = idHint + this.currentToken.getText(); + memberName = TypeScript.Identifier.fromToken(this.currentToken); + memberName.minChar = this.scanner.startPos; + accessorPattern = true; + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("Property accessors are only available when targeting ES5 or greater"); + } + } else { + if(this.currentToken.tokenId != TypeScript.TokenID.Colon) { + this.reportParseError("Expected identifier, string or number as accessor name"); + } else { + skippedTokenForGetSetId = true; + memberName = TypeScript.Identifier.fromToken(getSetTok); + memberName.minChar = getSetStartPos; + memberName.limChar = getSetPos; + } + } + } else { + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToIDName(this.currentToken)) { + idHint = this.currentToken.getText(); + memberName = TypeScript.Identifier.fromToken(this.currentToken); + memberName.minChar = this.scanner.startPos; + memberName.limChar = this.scanner.pos; + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.StringLiteral) { + idHint = this.currentToken.getText(); + memberName = new TypeScript.StringLiteral(idHint); + memberName.minChar = this.scanner.startPos; + memberName.limChar = this.scanner.pos; + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.NumberLiteral) { + var ntok = this.currentToken; + idHint = ntok.value.toString(); + memberName = new TypeScript.StringLiteral(idHint); + memberName.minChar = this.scanner.startPos; + memberName.limChar = this.scanner.pos; + } else { + this.reportParseError("Expected identifier, string or number as member name"); + if(this.errorRecovery) { + memberName = new TypeScript.MissingIdentifier(); + memberName.minChar = this.scanner.startPos; + memberName.flags |= TypeScript.ASTFlags.Error; + this.skip(errorRecoverySet | TypeScript.ErrorRecoverySet.Comma); + memberName.limChar = this.scanner.lastTokenLimChar(); + } + } + } + } + } + if(!skippedTokenForGetSetId) { + this.currentToken = this.scanner.scan(); + } else { + skippedTokenForGetSetId = false; + } + if(this.currentToken.tokenId == TypeScript.TokenID.Question) { + memberName.flags |= TypeScript.ASTFlags.OptionalName; + this.currentToken = this.scanner.scan(); + } + if(accessorPattern) { + var args = new TypeScript.ASTList(); + this.parseFormalParameterList(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, args, false, true, false, !isSet, isSet, false, null, true); + var funcDecl = this.parseFunctionStatements(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, memberName, false, true, args, TypeScript.AllowedElements.None, this.scanner.startPos, false, TypeScript.Modifiers.None); + if(isSet && funcDecl.returnTypeAnnotation) { + this.reportParseError("Property setters may not declare a return type"); + } + funcDecl.fncFlags |= isSet ? TypeScript.FncFlags.SetAccessor : TypeScript.FncFlags.GetAccessor; + funcDecl.fncFlags |= TypeScript.FncFlags.IsFunctionExpression; + funcDecl.hint = idHint; + memberExpr = funcDecl; + member = new TypeScript.BinaryExpression(TypeScript.NodeType.Member, memberName, memberExpr); + member.minChar = memberName.minChar; + if(memberExpr.nodeType == TypeScript.NodeType.FuncDecl) { + var funcDecl = memberExpr; + funcDecl.hint = idHint; + } + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { + this.currentToken = this.scanner.scan(); + memberExpr = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); + if(memberExpr.nodeType == TypeScript.NodeType.TypeRef) { + this.reportParseError("Expected 'new' on array declaration in member definition"); + } + member = new TypeScript.BinaryExpression(TypeScript.NodeType.Member, memberName, memberExpr); + member.minChar = memberName.minChar; + if(memberExpr.nodeType == TypeScript.NodeType.FuncDecl) { + var funcDecl = memberExpr; + funcDecl.hint = idHint; + } + } else { + this.reportParseError("Expected ':' in member definition"); + if(this.errorRecovery) { + this.skip(errorRecoverySet); + elements.flags |= TypeScript.ASTFlags.Error; + elements.minChar = minChar; + elements.limChar = this.scanner.lastTokenLimChar(); + return elements; + } + } + } + idHint = null; + elements.append(member); + member.limChar = this.scanner.lastTokenLimChar(); + if(this.currentToken.tokenId != TypeScript.TokenID.Comma) { + break; + } else { + this.currentToken = this.scanner.scan(); + } + if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { + break; + } + } + if(member) { + elements.limChar = member.limChar; + } + elements.minChar = minChar; + return elements; + }; + Parser.prototype.parseArrayList = function (errorRecoverySet) { + var elements = null; + if(this.currentToken.tokenId == TypeScript.TokenID.CloseBracket) { + return elements; + } else { + elements = new TypeScript.ASTList(); + elements.minChar = this.scanner.startPos; + } + var arg; + for(; ; ) { + if((this.currentToken.tokenId == TypeScript.TokenID.Comma) || (this.currentToken.tokenId == TypeScript.TokenID.CloseBracket)) { + arg = new TypeScript.AST(TypeScript.NodeType.EmptyExpr); + } else { + arg = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); + } + elements.append(arg); + if(this.currentToken.tokenId != TypeScript.TokenID.Comma) { + break; + } + this.currentToken = this.scanner.scan(); + } + elements.limChar = this.scanner.lastTokenLimChar(); + return elements; + }; + Parser.prototype.parseArrayLiteral = function (errorRecoverySet) { + var arrayLiteral = null; + arrayLiteral = new TypeScript.UnaryExpression(TypeScript.NodeType.ArrayLit, this.parseArrayList(errorRecoverySet)); + return arrayLiteral; + }; + Parser.prototype.parseTerm = function (errorRecoverySet, allowCall, typeContext, inCast) { + var ast = null; + var sawId = false; + var inNew = false; + var minChar = this.scanner.startPos; + var limChar = this.scanner.pos; + var parseAsLambda = false; + var expectlambdaRParen = false; + switch(this.currentToken.tokenId) { + case TypeScript.TokenID.Number: + case TypeScript.TokenID.Bool: + case TypeScript.TokenID.Any: + case TypeScript.TokenID.String: { + var tid = new TypeScript.Identifier(TypeScript.tokenTable[this.currentToken.tokenId].text); + if(TypeScript.hasFlag(typeContext, TypeContext.Primitive)) { + ast = new TypeScript.TypeReference(tid, 0); + sawId = true; + } else { + ast = tid; + sawId = true; + } + ast.minChar = minChar; + this.currentToken = this.scanner.scan(); + limChar = this.scanner.lastTokenLimChar(); + break; + + } + case TypeScript.TokenID.This: { + ast = new TypeScript.AST(TypeScript.NodeType.This); + ast.minChar = minChar; + this.currentToken = this.scanner.scan(); + limChar = this.scanner.lastTokenLimChar(); + break; + + } + case TypeScript.TokenID.Super: { + ast = new TypeScript.AST(TypeScript.NodeType.Super); + ast.minChar = minChar; + this.currentToken = this.scanner.scan(); + limChar = this.scanner.lastTokenLimChar(); + break; + + } + case TypeScript.TokenID.True: { + ast = new TypeScript.AST(TypeScript.NodeType.True); + this.currentToken = this.scanner.scan(); + ast.minChar = minChar; + break; + + } + case TypeScript.TokenID.False: { + ast = new TypeScript.AST(TypeScript.NodeType.False); + this.currentToken = this.scanner.scan(); + ast.minChar = minChar; + break; + + } + case TypeScript.TokenID.Null: { + ast = new TypeScript.AST(TypeScript.NodeType.Null); + this.currentToken = this.scanner.scan(); + ast.minChar = minChar; + break; + + } + case TypeScript.TokenID.New: { + minChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + var target = this.parseTerm(errorRecoverySet, false, TypeContext.AllSimpleTypes, inCast); + if(target.nodeType == TypeScript.NodeType.Error || (target.nodeType == TypeScript.NodeType.Index && (target).operand1.nodeType == TypeScript.NodeType.TypeRef)) { + this.reportParseError("Cannot invoke 'new' on this expression"); + } else { + ast = new TypeScript.CallExpression(TypeScript.NodeType.New, target, null); + ast.minChar = minChar; + limChar = this.scanner.lastTokenLimChar(); + inNew = true; + } + break; + + } + case TypeScript.TokenID.Function: { + minChar = this.scanner.pos; + ast = this.parseFncDecl(errorRecoverySet, false, false, false, null, false, false, false, TypeScript.Modifiers.None, null, true); + (ast).fncFlags |= TypeScript.FncFlags.IsFunctionExpression; + ast.minChar = minChar; + limChar = this.scanner.lastTokenLimChar(); + ast.limChar = limChar; + break; + + } + } + if(ast == null) { + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + var idText = this.currentToken.getText(); + ast = this.createRef(idText, (this.currentToken).hasEscapeSequence, minChar); + sawId = true; + ast.minChar = minChar; + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.Question) { + ast.flags |= TypeScript.ASTFlags.PossibleOptionalParameter; + } + limChar = this.scanner.lastTokenLimChar(); + } + } + if(inCast) { + this.checkCurrentToken(TypeScript.TokenID.GreaterThan, errorRecoverySet); + } + if(ast == null) { + switch(this.currentToken.tokenId) { + case TypeScript.TokenID.OpenParen: { + minChar = this.scanner.pos; + var prevTokId = this.scanner.previousToken().tokenId; + this.currentToken = this.scanner.scan(); + var couldBeLambda = prevTokId == TypeScript.TokenID.OpenParen || prevTokId == TypeScript.TokenID.Comma || prevTokId == TypeScript.TokenID.EqualsEquals || prevTokId == TypeScript.TokenID.Colon; + if(couldBeLambda && this.currentToken.tokenId == TypeScript.TokenID.CloseParen) { + parseAsLambda = true; + expectlambdaRParen = false; + this.currentToken = this.scanner.scan(); + } else { + if(couldBeLambda && this.currentToken.tokenId == TypeScript.TokenID.DotDotDot) { + parseAsLambda = true; + expectlambdaRParen = true; + } else { + ast = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes, couldBeLambda); + limChar = this.scanner.lastTokenLimChar(); + parseAsLambda = couldBeLambda && (ast.nodeType == TypeScript.NodeType.Name || ast.nodeType == TypeScript.NodeType.Comma) && (this.currentToken.tokenId == TypeScript.TokenID.Colon || this.currentToken.tokenId == TypeScript.TokenID.Question); + expectlambdaRParen = true; + } + } + if((ast && !parseAsLambda)) { + if(TypeScript.hasFlag(ast.flags, TypeScript.ASTFlags.SkipNextRParen)) { + ast.flags = ast.flags & (~(TypeScript.ASTFlags.SkipNextRParen)); + break; + } + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet); + ast.isParenthesized = true; + } + break; + + } + case TypeScript.TokenID.NumberLiteral: { + var numTok = this.currentToken; + this.currentToken = this.scanner.scan(); + ast = new TypeScript.NumberLiteral(numTok.value, numTok.hasEmptyFraction); + ast.minChar = minChar; + limChar = this.scanner.lastTokenLimChar(); + break; + } + + case TypeScript.TokenID.StringLiteral: { + ast = new TypeScript.StringLiteral(this.currentToken.getText()); + this.currentToken = this.scanner.scan(); + ast.minChar = minChar; + limChar = this.scanner.lastTokenLimChar(); + break; + + } + case TypeScript.TokenID.RegularExpressionLiteral: { + var rtok = this.currentToken; + ast = new TypeScript.RegexLiteral(rtok.regex); + this.currentToken = this.scanner.scan(); + ast.minChar = minChar; + limChar = this.scanner.lastTokenLimChar(); + break; + } + + case TypeScript.TokenID.OpenBracket: { + minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + ast = this.parseArrayLiteral(TypeScript.ErrorRecoverySet.RBrack | errorRecoverySet); + ast.minChar = minChar; + limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseBracket, errorRecoverySet); + break; + + } + case TypeScript.TokenID.OpenBrace: { + minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + var members = this.parseMemberList(TypeScript.ErrorRecoverySet.RCurly | errorRecoverySet); + this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); + ast = new TypeScript.UnaryExpression(TypeScript.NodeType.ObjectLit, members); + ast.minChar = minChar; + limChar = this.scanner.lastTokenLimChar(); + members.minChar = minChar; + members.limChar = limChar; + break; + + } + case TypeScript.TokenID.LessThan: { + minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + var term = this.parseTypeReference(TypeScript.ErrorRecoverySet.BinOp, false); + this.checkCurrentToken(TypeScript.TokenID.GreaterThan, errorRecoverySet); + ast = new TypeScript.UnaryExpression(TypeScript.NodeType.TypeAssertion, this.parseExpr(errorRecoverySet, TypeScript.OperatorPrecedence.Unary, false, TypeContext.NoTypes)); + (ast).castTerm = term; + break; + + } + default: { + if(this.prevExpr && TypeScript.hasFlag(this.prevExpr.flags, TypeScript.ASTFlags.PossibleOptionalParameter)) { + parseAsLambda = true; + ast = this.prevExpr; + } else { + this.reportParseError("Check format of expression term"); + if(this.errorRecovery) { + var ident = new TypeScript.MissingIdentifier(); + ident.minChar = minChar; + ident.flags |= TypeScript.ASTFlags.Error; + this.skip(errorRecoverySet | TypeScript.ErrorRecoverySet.Postfix); + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + ident.setText(this.currentToken.getText(), (this.currentToken).hasEscapeSequence); + this.currentToken = this.scanner.scan(); + limChar = this.scanner.lastTokenLimChar(); + } else { + limChar = this.scanner.lastTokenLimChar(); + } + ast = ident; + } + } + + } + } + } + if(parseAsLambda) { + if(this.currentToken.tokenId == TypeScript.TokenID.Colon || this.currentToken.tokenId == TypeScript.TokenID.Comma || this.currentToken.tokenId == TypeScript.TokenID.CloseParen || this.currentToken.tokenId == TypeScript.TokenID.DotDotDot) { + ast = this.parseLambdaExpr(errorRecoverySet, ast, true, expectlambdaRParen); + ast.minChar = minChar; + limChar = this.scanner.lastTokenLimChar(); + ast.limChar = limChar; + } else { + if(ast) { + ast.isParenthesized = true; + } + } + } + if(sawId && (typeContext != TypeContext.NoTypes)) { + typeContext |= TypeContext.ArraySuffix; + } + var postFix = this.parsePostfixOperators(errorRecoverySet, ast, allowCall, inNew, typeContext, minChar, limChar); + if(postFix) { + if(sawId && (postFix.nodeType == TypeScript.NodeType.Index)) { + var binExpr = postFix; + if(binExpr.operand2 == null) { + postFix = this.convertToTypeReference(postFix); + } + } + postFix.minChar = minChar; + postFix.limChar = TypeScript.max(postFix.limChar, this.scanner.lastTokenLimChar()); + return postFix; + } else { + return new TypeScript.AST(TypeScript.NodeType.Error); + } + }; + Parser.prototype.parseLambdaExpr = function (errorRecoverySet, lambdaArgs, skipNextRParen, expectClosingRParen) { + var ast = this.parseFncDecl(errorRecoverySet, false, false, false, null, false, false, false, TypeScript.Modifiers.None, { + preProcessedLambdaArgs: lambdaArgs + }, expectClosingRParen); + (ast).fncFlags |= TypeScript.FncFlags.IsFunctionExpression; + (ast).fncFlags |= TypeScript.FncFlags.IsFatArrowFunction; + if(!skipNextRParen) { + ast.flags |= TypeScript.ASTFlags.SkipNextRParen; + } + ast.limChar = this.scanner.lastTokenLimChar(); + ; ; + return ast; + }; + Parser.prototype.parseExpr = function (errorRecoverySet, minPrecedence, allowIn, typeContext, possiblyInLambda) { + if (typeof possiblyInLambda === "undefined") { possiblyInLambda = false; } + var ast = null; + var tokenInfo = TypeScript.lookupToken(this.currentToken.tokenId); + var canAssign = true; + var idHint = null; + var minChar = this.scanner.startPos; + var preComments = this.parseComments(); + var exprIsAnonLambda = false; + if((tokenInfo != undefined) && (tokenInfo.unopNodeType != TypeScript.NodeType.None)) { + canAssign = false; + this.currentToken = this.scanner.scan(); + var tempExpr = this.parseExpr(TypeScript.ErrorRecoverySet.BinOp | errorRecoverySet, tokenInfo.unopPrecedence, allowIn, TypeContext.NoTypes); + if((tokenInfo.unopNodeType == TypeScript.NodeType.Pos) && (tempExpr.nodeType == TypeScript.NodeType.NumberLit)) { + ast = tempExpr; + } else { + if((tokenInfo.unopNodeType == TypeScript.NodeType.Neg) && (tempExpr.nodeType == TypeScript.NodeType.NumberLit)) { + var numLit = tempExpr; + numLit.value = (-numLit.value); + if(numLit.value == 0) { + numLit.isNegativeZero = true; + } + ast = tempExpr; + } else { + ast = new TypeScript.UnaryExpression(tokenInfo.unopNodeType, tempExpr); + ast.limChar = tempExpr.limChar; + } + } + ast.minChar = minChar; + } else { + ast = this.parseTerm(TypeScript.ErrorRecoverySet.BinOp | TypeScript.ErrorRecoverySet.AddOp | errorRecoverySet, true, typeContext, false); + var id; + var temp; + if(ast.nodeType == TypeScript.NodeType.Name) { + id = ast; + idHint = id.actualText; + } else { + if(ast.nodeType == TypeScript.NodeType.Dot) { + var subsumedExpr = false; + if(this.inferPropertiesFromThisAssignment && (this.currentToken.tokenId == TypeScript.TokenID.Colon || this.currentToken.tokenId == TypeScript.TokenID.Equals) && this.parsingClassConstructorDefinition && this.nestingLevel == this.currentClassDefinition.constructorNestingLevel && (ast).operand1.nodeType == TypeScript.NodeType.This) { + if((ast).operand2.nodeType == TypeScript.NodeType.Name) { + var op2ID = ((ast).operand2); + if(!this.currentClassDefinition.knownMemberNames[op2ID.actualText]) { + ast = this.parseClassMemberVariableDeclaration(op2ID, ast.minChar, true, errorRecoverySet, TypeScript.Modifiers.Public); + subsumedExpr = true; + } + } + } + if(!subsumedExpr) { + temp = ast; + while(temp.nodeType == TypeScript.NodeType.Dot) { + var binExpr = temp; + temp = binExpr.operand2; + } + if(temp.nodeType == TypeScript.NodeType.Name) { + id = temp; + idHint = id.actualText; + } + } + } + } + if((!this.scanner.lastTokenHadNewline()) && ((this.currentToken.tokenId == TypeScript.TokenID.PlusPlus) || (this.currentToken.tokenId == TypeScript.TokenID.MinusMinus))) { + canAssign = false; + var operand = ast; + ast = new TypeScript.UnaryExpression((this.currentToken.tokenId == TypeScript.TokenID.PlusPlus) ? TypeScript.NodeType.IncPost : TypeScript.NodeType.DecPost, operand); + ast.limChar = this.scanner.pos; + ast.minChar = operand.minChar; + this.currentToken = this.scanner.scan(); + } + } + for(; ; ) { + tokenInfo = TypeScript.lookupToken(this.currentToken.tokenId); + if((tokenInfo == undefined) || (tokenInfo.binopNodeType == TypeScript.NodeType.None)) { + break; + } + if((!allowIn) && (tokenInfo.binopNodeType == TypeScript.NodeType.In)) { + break; + } + if(tokenInfo.binopPrecedence == TypeScript.OperatorPrecedence.Assignment) { + if(tokenInfo.binopPrecedence < minPrecedence) { + break; + } + if(!canAssign) { + this.reportParseError("illegal assignment"); + } + } else { + if(tokenInfo.binopPrecedence <= minPrecedence) { + break; + } + } + if(possiblyInLambda && this.currentToken.tokenId == TypeScript.TokenID.Comma && this.scanner.getLookAheadToken().tokenId == TypeScript.TokenID.DotDotDot) { + exprIsAnonLambda = true; + canAssign = false; + ast = this.parseLambdaExpr(errorRecoverySet, ast, false, true); + break; + } + this.currentToken = this.scanner.scan(); + canAssign = false; + if(tokenInfo.binopNodeType == TypeScript.NodeType.ConditionalExpression) { + if(possiblyInLambda && (this.currentToken.tokenId == TypeScript.TokenID.Equals || this.currentToken.tokenId == TypeScript.TokenID.Colon || this.currentToken.tokenId == TypeScript.TokenID.CloseParen || this.currentToken.tokenId == TypeScript.TokenID.Comma)) { + exprIsAnonLambda = true; + canAssign = true; + } else { + this.prevExpr = ast; + var whenTrue = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.Colon, TypeScript.OperatorPrecedence.Assignment, allowIn, TypeContext.NoTypes); + this.prevExpr = null; + this.checkCurrentToken(TypeScript.TokenID.Colon, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); + var whenFalse = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.BinOp, TypeScript.OperatorPrecedence.Assignment, allowIn, TypeContext.NoTypes); + ast = new TypeScript.ConditionalExpression(ast, whenTrue, whenFalse); + } + } else { + var tc = TypeContext.NoTypes; + var binExpr2; + binExpr2 = new TypeScript.BinaryExpression(tokenInfo.binopNodeType, ast, this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.BinOp, tokenInfo.binopPrecedence, allowIn, TypeContext.NoTypes, possiblyInLambda)); + if(binExpr2.operand2.nodeType == TypeScript.NodeType.FuncDecl) { + var funcDecl = binExpr2.operand2; + funcDecl.hint = idHint; + } + binExpr2.minChar = ast.minChar; + binExpr2.limChar = this.scanner.lastTokenLimChar(); + idHint = null; + ast = binExpr2; + } + } + if(canAssign) { + ast.flags |= TypeScript.ASTFlags.Writeable; + } + if(!exprIsAnonLambda) { + ast.minChar = minChar; + ast.limChar = TypeScript.max(ast.limChar, this.scanner.lastTokenLimChar()); + ast.preComments = preComments; + ast.postComments = this.parseCommentsForLine(this.scanner.line); + } + return ast; + }; + Parser.prototype.parsePostfixOperators = function (errorRecoverySet, ast, allowCall, inNew, typeContext, lhsMinChar, lhsLimChar) { + var count = 0; + if(!ast) { + ast = new TypeScript.AST(TypeScript.NodeType.EmptyExpr); + ast.isParenthesized = true; + } + ast.minChar = lhsMinChar; + ast.limChar = lhsLimChar; + for(; ; ) { + switch(this.currentToken.tokenId) { + case TypeScript.TokenID.OpenParen: { + if(inNew) { + var callExpr = ast; + callExpr.arguments = this.parseArgList(errorRecoverySet); + inNew = false; + } else { + if(!allowCall) { + return ast; + } + ast = new TypeScript.CallExpression(TypeScript.NodeType.Call, ast, this.parseArgList(errorRecoverySet)); + ast.minChar = lhsMinChar; + } + ast.limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet); + break; + + } + case TypeScript.TokenID.OpenBracket: { + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.CloseBracket) { + if(TypeScript.hasFlag(typeContext, TypeContext.ArraySuffix)) { + this.currentToken = this.scanner.scan(); + if(ast.nodeType == TypeScript.NodeType.TypeRef) { + var typeRef = ast; + typeRef.arrayCount++; + } else { + ast = new TypeScript.BinaryExpression(TypeScript.NodeType.Index, ast, null); + } + ast.limChar = this.scanner.pos; + break; + } + } + ast = new TypeScript.BinaryExpression(TypeScript.NodeType.Index, ast, this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RBrack, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes)); + ast.minChar = lhsMinChar; + ast.limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseBracket, errorRecoverySet); + break; + + } + case TypeScript.TokenID.Dot: { + var name = null; + var curpos = this.scanner.pos; + this.currentToken = this.scanner.scan(); + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || ((!this.errorRecovery || !this.scanner.lastTokenHadNewline()) && TypeScript.convertTokToIDName(this.currentToken))) { + ast.flags |= TypeScript.ASTFlags.DotLHS; + name = this.createRef(this.currentToken.getText(), (this.currentToken).hasEscapeSequence, this.scanner.startPos); + name.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + } else { + this.reportParseError("Expected identifier following dot"); + if(this.errorRecovery) { + this.skip(errorRecoverySet); + ast.flags |= (TypeScript.ASTFlags.Error | TypeScript.ASTFlags.DotLHS); + return ast; + } else { + name = new TypeScript.MissingIdentifier(); + } + } + ast = new TypeScript.BinaryExpression(TypeScript.NodeType.Dot, ast, name); + ast.minChar = lhsMinChar; + ast.limChar = this.scanner.lastTokenLimChar(); + break; + } + + case TypeScript.TokenID.EqualsGreaterThan: { + ast = this.parseFncDecl(errorRecoverySet, false, false, false, null, false, false, false, TypeScript.Modifiers.None, { + preProcessedLambdaArgs: ast + }, false); + (ast).fncFlags |= TypeScript.FncFlags.IsFunctionExpression; + ast.minChar = lhsMinChar; + ast.limChar = this.scanner.lastTokenLimChar(); + break; + + } + default: { + return ast; + + } + } + } + }; + Parser.prototype.parseTry = function (tryNode, errorRecoverySet, parentModifiers) { + var minChar = this.scanner.startPos; + var preComments = this.parseComments(); + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId != TypeScript.TokenID.OpenBrace) { + this.reportParseError("Expected '{'"); + if(this.errorRecovery) { + var etryNode = tryNode; + etryNode.minChar = minChar; + etryNode.limChar = this.scanner.lastTokenLimChar(); + etryNode.flags |= TypeScript.ASTFlags.Error; + return etryNode; + } + } + tryNode.body = this.parseStatement(errorRecoverySet, TypeScript.AllowedElements.None, parentModifiers); + tryNode.minChar = minChar; + tryNode.limChar = tryNode.body.limChar; + tryNode.preComments = preComments; + tryNode.postComments = this.parseComments(); + return tryNode; + }; + Parser.prototype.parseCatch = function (errorRecoverySet, parentModifiers) { + var catchMinChar = this.scanner.startPos; + var preComments = this.parseComments(); + this.currentToken = this.scanner.scan(); + this.checkCurrentToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); + if((this.currentToken.tokenId != TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + this.reportParseError("Expected identifier in catch header"); + if(this.errorRecovery) { + this.skip(errorRecoverySet); + var ecatch = new TypeScript.Catch(new TypeScript.VarDecl(new TypeScript.MissingIdentifier(), this.nestingLevel), new TypeScript.Statement(TypeScript.NodeType.Empty)); + ecatch.statement.minChar = catchMinChar; + ecatch.statement.limChar = this.scanner.pos; + ecatch.minChar = this.scanner.startPos; + ecatch.limChar = this.scanner.pos; + ecatch.flags |= TypeScript.ASTFlags.Error; + return ecatch; + } + } + var param = new TypeScript.VarDecl(TypeScript.Identifier.fromToken(this.currentToken), this.nestingLevel); + param.id.minChar = this.scanner.startPos; + param.id.limChar = this.scanner.pos; + param.minChar = param.id.minChar; + param.limChar = param.id.limChar; + this.currentToken = this.scanner.scan(); + var statementPos = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); + if(this.currentToken.tokenId != TypeScript.TokenID.OpenBrace) { + this.reportParseError("Expected '{' to start catch body"); + if(this.errorRecovery) { + this.skip(errorRecoverySet); + var ecatch = new TypeScript.Catch(new TypeScript.VarDecl(new TypeScript.MissingIdentifier(), this.nestingLevel), new TypeScript.Statement(TypeScript.NodeType.Empty)); + ecatch.statement.minChar = catchMinChar; + ecatch.statement.limChar = statementPos; + ecatch.minChar = this.scanner.startPos; + ecatch.limChar = this.scanner.pos; + ecatch.flags |= TypeScript.ASTFlags.Error; + return ecatch; + } + } + var catchStmt = this.parseStatement(errorRecoverySet, TypeScript.AllowedElements.None, parentModifiers); + var catchNode = new TypeScript.Catch(param, catchStmt); + catchNode.statement.minChar = catchMinChar; + catchNode.statement.limChar = statementPos; + catchNode.minChar = catchMinChar; + catchNode.limChar = catchStmt.limChar; + catchNode.preComments = preComments; + catchNode.postComments = this.parseComments(); + return catchNode; + }; + Parser.prototype.parseFinally = function (errorRecoverySet, parentModifiers) { + var finMinChar = this.scanner.startPos; + var preComments = this.parseComments(); + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId != TypeScript.TokenID.OpenBrace) { + this.reportParseError("Expected '{' to start body of finally statement"); + if(this.errorRecovery) { + this.skip(errorRecoverySet); + var efin = new TypeScript.Finally(new TypeScript.Statement(TypeScript.NodeType.Empty)); + efin.flags |= TypeScript.ASTFlags.Error; + efin.minChar = this.scanner.startPos; + efin.limChar = this.scanner.pos; + return efin; + } + } + var finBody = this.parseStatement(errorRecoverySet, TypeScript.AllowedElements.None, parentModifiers); + var fin = new TypeScript.Finally(finBody); + fin.minChar = finMinChar; + fin.limChar = fin.body.limChar; + fin.preComments = preComments; + fin.postComments = this.parseComments(); + return fin; + }; + Parser.prototype.parseTryCatchFinally = function (errorRecoverySet, parentModifiers, labelList) { + var tryPart = new TypeScript.Try(null); + var tryMinChar = this.scanner.startPos; + this.pushStmt(tryPart, labelList); + this.parseTry(tryPart, errorRecoverySet | TypeScript.ErrorRecoverySet.Catch, parentModifiers); + this.popStmt(); + var tc = null; + var tf = null; + if(this.currentToken.tokenId == TypeScript.TokenID.Catch) { + var catchPart = this.parseCatch(errorRecoverySet | TypeScript.ErrorRecoverySet.Catch, parentModifiers); + tc = new TypeScript.TryCatch(tryPart, catchPart); + tc.minChar = tryPart.minChar; + tc.limChar = catchPart.limChar; + } + if(this.currentToken.tokenId != TypeScript.TokenID.Finally) { + if(tc == null) { + this.reportParseError("try with neither catch nor finally"); + if(this.errorRecovery) { + var etf = new TypeScript.TryFinally(tryPart, new TypeScript.Finally(new TypeScript.AST(TypeScript.NodeType.Empty))); + etf.flags |= TypeScript.ASTFlags.Error; + etf.minChar = this.scanner.startPos; + etf.limChar = this.scanner.pos; + return etf; + } + return new TypeScript.TryFinally(tryPart, new TypeScript.Finally(new TypeScript.AST(TypeScript.NodeType.Empty))); + } else { + return tc; + } + } else { + if(tc) { + tryPart = tc; + } + var finallyPart = this.parseFinally(errorRecoverySet, parentModifiers); + tf = new TypeScript.TryFinally(tryPart, finallyPart); + tf.minChar = tryMinChar; + tf.limChar = finallyPart.limChar; + return tf; + } + }; + Parser.prototype.parseStatement = function (errorRecoverySet, allowedElements, parentModifiers) { + var ast = null; + var labelList = null; + var astList = null; + var temp; + var modifiers = TypeScript.Modifiers.None; + var minChar = this.scanner.startPos; + var forInOk = false; + var needTerminator = false; + var fnOrVar = null; + var preComments = this.parseComments(); + this.state = ParseState.StartStatement; + function isAmbient() { + return TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient) || TypeScript.hasFlag(parentModifiers, TypeScript.Modifiers.Ambient); + } + function mayNotBeExported() { + if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { + this.reportError("Statement may not be exported"); + } + } + for(; ; ) { + switch(this.currentToken.tokenId) { + case TypeScript.TokenID.EndOfFile: { + ast = new TypeScript.AST(TypeScript.NodeType.Error); + ast.minChar = minChar; + ast.limChar = this.scanner.pos; + break; + + } + case TypeScript.TokenID.Function: { + if(this.parsingDeclareFile || isAmbient() || this.ambientModule) { + this.currentToken = this.scanner.scan(); + fnOrVar = this.parsePropertyDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, modifiers, true, false); + if(fnOrVar.nodeType == TypeScript.NodeType.VarDecl) { + this.reportParseError("function keyword can only introduce function declaration"); + } else { + if((fnOrVar.nodeType == TypeScript.NodeType.FuncDecl) && ((fnOrVar).fncFlags , TypeScript.FncFlags.IsFatArrowFunction)) { + needTerminator = true; + } + } + ast = fnOrVar; + if(this.parsingDeclareFile || this.ambientModule && ast.nodeType == TypeScript.NodeType.FuncDecl) { + (ast).fncFlags |= TypeScript.FncFlags.Exported; + } + } else { + ast = this.parseFncDecl(errorRecoverySet, true, false, false, null, false, false, isAmbient(), modifiers, null, true); + if(TypeScript.hasFlag((ast).fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { + needTerminator = true; + } + if(this.ambientModule) { + this.reportParseError("function declaration not permitted within ambient module"); + } + if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { + (ast).fncFlags |= TypeScript.FncFlags.Exported; + } + } + break; + + } + case TypeScript.TokenID.Module: { + if((allowedElements & TypeScript.AllowedElements.ModuleDeclarations) == TypeScript.AllowedElements.None) { + this.reportParseError("module not allowed in this context"); + this.currentToken = this.scanner.scan(); + ast = new TypeScript.AST(TypeScript.NodeType.Error); + ast.minChar = minChar; + ast.limChar = this.scanner.lastTokenLimChar(); + } else { + ast = this.parseModuleDecl(errorRecoverySet, modifiers, preComments); + preComments = null; + } + break; + + } + case TypeScript.TokenID.Import: { + if((allowedElements & TypeScript.AllowedElements.ModuleDeclarations) == TypeScript.AllowedElements.None) { + this.reportParseError("module not allowed in this context"); + this.currentToken = this.scanner.scan(); + ast = new TypeScript.AST(TypeScript.NodeType.Error); + ast.minChar = minChar; + ast.limChar = this.scanner.lastTokenLimChar(); + } else { + if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { + this.reportParseError("export keyword not permitted on import declaration"); + } + ast = this.parseImportDeclaration(errorRecoverySet, modifiers); + needTerminator = true; + } + break; + + } + case TypeScript.TokenID.Export: { + if((allowedElements & TypeScript.AllowedElements.ModuleDeclarations) == TypeScript.AllowedElements.None) { + this.reportParseError("'export' statements are only allowed at the global and module levels"); + this.currentToken = this.scanner.scan(); + ast = new TypeScript.AST(TypeScript.NodeType.Error); + ast.minChar = minChar; + ast.limChar = this.scanner.lastTokenLimChar(); + } + if(this.topLevel) { + this.hasTopLevelImportOrExport = true; + } + modifiers |= TypeScript.Modifiers.Exported; + this.currentToken = this.scanner.scan(); + break; + + } + case TypeScript.TokenID.Private: { + modifiers |= TypeScript.Modifiers.Private; + this.currentToken = this.scanner.scan(); + if(this.parsingClassConstructorDefinition) { + if(!this.inferPropertiesFromThisAssignment) { + this.reportParseError("Property declarations are not permitted within constructor bodies"); + } + minChar = this.scanner.pos; + if(this.inferPropertiesFromThisAssignment && (this.currentToken.tokenId != TypeScript.TokenID.This || (this.currentToken = this.scanner.scan()).tokenId != TypeScript.TokenID.Dot)) { + this.reportParseError("Expected 'this.' for property declaration"); + this.currentToken = this.scanner.scan(); + ast = new TypeScript.AST(TypeScript.NodeType.Error); + ast.minChar = minChar; + ast.limChar = this.scanner.lastTokenLimChar(); + } else { + this.currentToken = this.scanner.scan(); + var id = TypeScript.Identifier.fromToken(this.currentToken); + id.minChar = this.scanner.startPos; + id.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + ast = this.parseClassMemberVariableDeclaration(id, minChar, this.parsingClassConstructorDefinition, errorRecoverySet, modifiers); + } + } else { + if(this.currentToken.tokenId != TypeScript.TokenID.Interface) { + if(this.currentToken.tokenId == TypeScript.TokenID.Get) { + this.prevIDTok = this.currentToken; + this.currentToken = this.scanner.scan(); + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("Property accessors are only available when targeting ES5 or greater"); + } + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + modifiers |= TypeScript.Modifiers.Getter; + this.prevIDTok = null; + } + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.Set) { + this.prevIDTok = this.currentToken; + this.currentToken = this.scanner.scan(); + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("Property accessors are only available when targeting ES5 or greater"); + } + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + modifiers |= TypeScript.Modifiers.Setter; + this.prevIDTok = null; + } + } + } + fnOrVar = this.parsePropertyDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, modifiers, isAmbient(), false); + if((fnOrVar.nodeType == TypeScript.NodeType.VarDecl) || ((fnOrVar.nodeType == TypeScript.NodeType.FuncDecl) && (TypeScript.hasFlag((fnOrVar).fncFlags, TypeScript.FncFlags.IsFatArrowFunction)))) { + needTerminator = true; + } + ast = fnOrVar; + } + } + break; + + } + case TypeScript.TokenID.Public: { + if(this.parsingClassConstructorDefinition) { + if(!this.inferPropertiesFromThisAssignment) { + this.reportParseError("Property declarations are not permitted within constructor bodies"); + } + this.currentToken = this.scanner.scan(); + minChar = this.scanner.pos; + modifiers |= TypeScript.Modifiers.Public; + if(this.inferPropertiesFromThisAssignment && (this.currentToken.tokenId != TypeScript.TokenID.This || (this.currentToken = this.scanner.scan()).tokenId != TypeScript.TokenID.Dot)) { + this.reportParseError("Expected 'this.' for property declaration"); + this.currentToken = this.scanner.scan(); + ast = new TypeScript.AST(TypeScript.NodeType.Error); + ast.minChar = minChar; + ast.limChar = this.scanner.lastTokenLimChar(); + } else { + this.currentToken = this.scanner.scan(); + var id = TypeScript.Identifier.fromToken(this.currentToken); + id.minChar = this.scanner.startPos; + id.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + ast = this.parseClassMemberVariableDeclaration(id, minChar, this.parsingClassConstructorDefinition, errorRecoverySet, modifiers); + } + } else { + if((allowedElements & TypeScript.AllowedElements.Properties) == TypeScript.AllowedElements.None) { + this.reportParseError("'property' statements are only allowed within classes"); + this.currentToken = this.scanner.scan(); + ast = new TypeScript.AST(TypeScript.NodeType.Error); + ast.minChar = minChar; + ast.limChar = this.scanner.lastTokenLimChar(); + } else { + modifiers |= TypeScript.Modifiers.Public; + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.Get) { + this.prevIDTok = this.currentToken; + this.currentToken = this.scanner.scan(); + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("Property accessors are only available when targeting ES5 or greater"); + } + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + modifiers |= TypeScript.Modifiers.Getter; + this.prevIDTok = null; + } + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.Set) { + this.prevIDTok = this.currentToken; + this.currentToken = this.scanner.scan(); + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("Property accessors are only available when targeting ES5 or greater"); + } + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + modifiers |= TypeScript.Modifiers.Setter; + this.prevIDTok = null; + } + } + } + fnOrVar = this.parsePropertyDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, modifiers, isAmbient(), false); + if((fnOrVar.nodeType == TypeScript.NodeType.VarDecl) || ((fnOrVar.nodeType == TypeScript.NodeType.FuncDecl) && TypeScript.hasFlag((fnOrVar).fncFlags, TypeScript.FncFlags.IsFatArrowFunction))) { + needTerminator = true; + } + ast = fnOrVar; + } + } + break; + + } + case TypeScript.TokenID.Declare: { + if(!(allowedElements & TypeScript.AllowedElements.AmbientDeclarations)) { + this.reportParseError("Ambient declarations are only allowed at the top-level or module scopes"); + } + if(!this.parsingDeclareFile && TypeScript.hasFlag(parentModifiers, TypeScript.Modifiers.Ambient)) { + this.reportParseError("Duplicate ambient declaration in this context. (Is the enclosing module or class already ambient?)"); + } + modifiers |= TypeScript.Modifiers.Ambient; + this.currentToken = this.scanner.scan(); + break; + + } + case TypeScript.TokenID.Class: { + if((allowedElements & TypeScript.AllowedElements.ClassDeclarations) == TypeScript.AllowedElements.None) { + this.reportParseError("class not allowed in this context"); + this.currentToken = this.scanner.scan(); + ast = new TypeScript.AST(TypeScript.NodeType.Error); + ast.minChar = minChar; + ast.limChar = this.scanner.lastTokenLimChar(); + } else { + ast = this.parseClassDecl(errorRecoverySet, minChar, modifiers); + } + break; + + } + case TypeScript.TokenID.Interface: { + if((allowedElements & TypeScript.AllowedElements.InterfaceDeclarations) == TypeScript.AllowedElements.None) { + this.reportParseError("interface not allowed in this context"); + this.currentToken = this.scanner.scan(); + ast = new TypeScript.AST(TypeScript.NodeType.Error); + ast.minChar = minChar; + ast.limChar = this.scanner.lastTokenLimChar(); + } else { + ast = this.parseInterfaceDecl(errorRecoverySet, modifiers); + } + break; + + } + case TypeScript.TokenID.Var: { + var declAst = this.parseVariableDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart, modifiers, true, false); + if(declAst.nodeType == TypeScript.NodeType.VarDecl) { + ast = declAst; + } else { + ast = new TypeScript.Block(declAst, false); + } + needTerminator = true; + break; + + } + case TypeScript.TokenID.Static: { + if(this.currentClassDecl == null) { + this.reportParseError("Statics may only be class members"); + } + mayNotBeExported(); + modifiers |= TypeScript.Modifiers.Public; + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.Get) { + this.prevIDTok = this.currentToken; + this.currentToken = this.scanner.scan(); + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("Property accessors are only available when targeting ES5 or greater"); + } + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + modifiers |= TypeScript.Modifiers.Getter; + this.prevIDTok = null; + } + } else { + if(this.currentToken.tokenId == TypeScript.TokenID.Set) { + this.currentToken = this.scanner.scan(); + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("Property accessors are only available when targeting ES5 or greater"); + } + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + modifiers |= TypeScript.Modifiers.Setter; + } + } + } + if(isAmbient()) { + modifiers |= TypeScript.Modifiers.Ambient; + } + fnOrVar = this.parsePropertyDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, modifiers, this.parsingDeclareFile || (modifiers & TypeScript.Modifiers.Ambient) != TypeScript.Modifiers.None, true); + var staticsList = this.topStaticsList(); + if(staticsList && fnOrVar.nodeType == TypeScript.NodeType.VarDecl) { + staticsList.append(fnOrVar); + } + if(fnOrVar.nodeType == TypeScript.NodeType.VarDecl || ((fnOrVar.nodeType == TypeScript.NodeType.FuncDecl) && TypeScript.hasFlag((fnOrVar).fncFlags, TypeScript.FncFlags.IsFatArrowFunction))) { + needTerminator = true; + } + ast = fnOrVar; + break; + + } + case TypeScript.TokenID.For: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("syntax error: for statement does not take modifiers"); + } + minChar = this.scanner.startPos; + this.checkNextToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart | TypeScript.ErrorRecoverySet.Var); + this.state = ParseState.ForInit; + forInOk = true; + switch(this.currentToken.tokenId) { + case TypeScript.TokenID.Var: { + temp = this.parseVariableDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon | TypeScript.ErrorRecoverySet.In, TypeScript.Modifiers.None, false, false); + break; + + } + case TypeScript.TokenID.Semicolon: { + temp = null; + this.state = ParseState.ForCondStart; + break; + + } + default: { + temp = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon | TypeScript.ErrorRecoverySet.In, TypeScript.OperatorPrecedence.None, false, TypeContext.NoTypes); + break; + + } + } + this.state = ParseState.ForInitAfterVar; + if(this.currentToken.tokenId == TypeScript.TokenID.In) { + if((temp == null) || (!forInOk)) { + this.reportParseError("malformed for statement"); + if(this.errorRecovery) { + this.skip(errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); + ast = new TypeScript.AST(TypeScript.NodeType.Empty); + ast.flags |= TypeScript.ASTFlags.Error; + } + } else { + this.currentToken = this.scanner.scan(); + var forInStmt = new TypeScript.ForInStatement(temp, this.parseExpr(TypeScript.ErrorRecoverySet.RParen | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, false, TypeContext.NoTypes)); + forInStmt.limChar = this.scanner.pos; + forInStmt.statement.minChar = minChar; + forInStmt.statement.limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseParen, TypeScript.ErrorRecoverySet.StmtStart | errorRecoverySet); + this.pushStmt(forInStmt, labelList); + forInStmt.body = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); + this.popStmt(); + forInStmt.minChar = minChar; + ast = forInStmt; + } + } else { + var forStmt = new TypeScript.ForStatement(temp); + forStmt.minChar = minChar; + this.checkCurrentToken(TypeScript.TokenID.Semicolon, errorRecoverySet); + if(this.currentToken.tokenId == TypeScript.TokenID.Semicolon) { + forStmt.cond = null; + } else { + forStmt.cond = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); + if(this.currentToken.tokenId != TypeScript.TokenID.Semicolon) { + this.skip(errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); + ast = forStmt; + ast.flags |= TypeScript.ASTFlags.Error; + } + } + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.CloseParen) { + forStmt.incr = null; + } else { + forStmt.incr = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); + } + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly); + this.pushStmt(forStmt, labelList); + forStmt.body = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); + this.popStmt(); + forStmt.limChar = forStmt.body.limChar; + ast = forStmt; + } + break; + + } + case TypeScript.TokenID.With: { + { + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("'with' statements are only available in ES5 codegen mode or better"); + } + if(this.strictMode) { + this.reportParseError("'with' statements are not available in strict mode"); + } + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("'with' statement does not take modifiers"); + } + minChar = this.scanner.startPos; + this.checkNextToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart | TypeScript.ErrorRecoverySet.Var); + var expr = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.Colon, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly); + var withStmt = new TypeScript.WithStatement(expr); + withStmt.body = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); + withStmt.minChar = minChar; + withStmt.limChar = withStmt.body.limChar; + ast = withStmt; + } + break; + + } + case TypeScript.TokenID.Switch: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("'switch' statement does not take modifiers"); + } + this.checkNextToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); + var switchStmt = new TypeScript.SwitchStatement(this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes)); + switchStmt.statement.minChar = minChar; + switchStmt.statement.limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly); + var caseListMinChar = this.scanner.startPos; + this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.SCase); + switchStmt.defaultCase = null; + switchStmt.caseList = new TypeScript.ASTList(); + var caseStmt = null; + this.pushStmt(switchStmt, labelList); + for(; ; ) { + if((this.currentToken.tokenId == TypeScript.TokenID.Case) || (this.currentToken.tokenId == TypeScript.TokenID.Default)) { + var isDefault = (this.currentToken.tokenId == TypeScript.TokenID.Default); + caseStmt = new TypeScript.CaseStatement(); + caseStmt.minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + if(isDefault) { + switchStmt.defaultCase = caseStmt; + } else { + caseStmt.expr = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.Colon, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); + } + this.checkCurrentToken(TypeScript.TokenID.Colon, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); + caseStmt.body = new TypeScript.ASTList(); + this.parseStatementList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, caseStmt.body, false, true, allowedElements, modifiers); + caseStmt.limChar = caseStmt.body.limChar; + switchStmt.caseList.append(caseStmt); + } else { + break; + } + } + switchStmt.caseList.minChar = caseListMinChar; + switchStmt.caseList.limChar = this.scanner.pos; + switchStmt.limChar = switchStmt.caseList.limChar; + this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); + this.popStmt(); + ast = switchStmt; + break; + } + + case TypeScript.TokenID.While: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("'while' statement does not take modifiers"); + } + minChar = this.scanner.startPos; + this.checkNextToken(TypeScript.TokenID.OpenParen, TypeScript.ErrorRecoverySet.ExprStart | errorRecoverySet); + var whileStmt = new TypeScript.WhileStatement(this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes)); + whileStmt.minChar = minChar; + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); + this.pushStmt(whileStmt, labelList); + whileStmt.body = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); + whileStmt.limChar = whileStmt.body.limChar; + this.popStmt(); + ast = whileStmt; + break; + } + + case TypeScript.TokenID.Do: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("'do' statement does not take modifiers"); + } + minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + var doStmt = new TypeScript.DoWhileStatement(); + doStmt.minChar = minChar; + this.pushStmt(doStmt, labelList); + doStmt.body = this.parseStatement(errorRecoverySet | TypeScript.ErrorRecoverySet.While, allowedElements, parentModifiers); + this.popStmt(); + doStmt.whileAST = new TypeScript.Identifier("while"); + doStmt.whileAST.minChar = this.scanner.startPos; + this.checkCurrentToken(TypeScript.TokenID.While, errorRecoverySet | TypeScript.ErrorRecoverySet.LParen); + doStmt.whileAST.limChar = doStmt.whileAST.minChar + 5; + this.checkCurrentToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); + doStmt.cond = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); + doStmt.limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet); + ast = doStmt; + if(this.currentToken.tokenId == TypeScript.TokenID.Semicolon) { + this.currentToken = this.scanner.scan(); + } + break; + } + + case TypeScript.TokenID.If: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("if statement does not take modifiers"); + } + minChar = this.scanner.startPos; + this.checkNextToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); + var ifStmt = new TypeScript.IfStatement(this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.LParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes)); + ifStmt.minChar = minChar; + ifStmt.statement.minChar = minChar; + ifStmt.statement.limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); + this.pushStmt(ifStmt, labelList); + ifStmt.thenBod = this.parseStatement(TypeScript.ErrorRecoverySet.Else | errorRecoverySet, allowedElements, parentModifiers); + ifStmt.limChar = ifStmt.thenBod.limChar; + if(this.currentToken.tokenId == TypeScript.TokenID.Else) { + this.currentToken = this.scanner.scan(); + ifStmt.elseBod = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); + ifStmt.limChar = ifStmt.elseBod.limChar; + } + this.popStmt(); + ast = ifStmt; + break; + } + + case TypeScript.TokenID.Try: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("try statement does not take modifiers"); + } + minChar = this.scanner.startPos; + ast = this.parseTryCatchFinally(errorRecoverySet, parentModifiers, labelList); + break; + } + + case TypeScript.TokenID.OpenBrace: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("block does not take modifiers"); + } + minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + var block = new TypeScript.Block(new TypeScript.ASTList(), true); + this.pushStmt(block, labelList); + this.parseStatementList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, block.statements, false, false, TypeScript.AllowedElements.None, modifiers); + this.popStmt(); + block.statements.minChar = minChar; + block.statements.limChar = this.scanner.pos; + block.minChar = block.statements.minChar; + block.limChar = block.statements.limChar; + this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); + ast = block; + break; + } + + case TypeScript.TokenID.Semicolon: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("modifier can not appear here"); + } + ast = new TypeScript.AST(TypeScript.NodeType.Empty); + this.currentToken = this.scanner.scan(); + break; + + } + case TypeScript.TokenID.Break: + case TypeScript.TokenID.Continue: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("modifiers can not appear before jump statement"); + } + var jump = new TypeScript.Jump((this.currentToken.tokenId == TypeScript.TokenID.Break) ? TypeScript.NodeType.Break : TypeScript.NodeType.Continue); + this.currentToken = this.scanner.scan(); + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) && (!this.scanner.lastTokenHadNewline())) { + jump.target = this.currentToken.getText(); + this.currentToken = this.scanner.scan(); + } + this.resolveJumpTarget(jump); + ast = jump; + needTerminator = true; + break; + } + + case TypeScript.TokenID.Return: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("modifiers can not appear before return statement"); + } + if(!this.inFunction) { + this.reportParseError("return statement outside of function body"); + } + minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + var retStmt = new TypeScript.ReturnStatement(); + retStmt.minChar = minChar; + if((this.currentToken.tokenId != TypeScript.TokenID.Semicolon) && (this.currentToken.tokenId != TypeScript.TokenID.CloseBrace) && (!(this.scanner.lastTokenHadNewline()))) { + retStmt.returnExpression = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); + } + needTerminator = true; + retStmt.limChar = this.scanner.lastTokenLimChar(); + ast = retStmt; + break; + } + + case TypeScript.TokenID.Throw: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("modifiers can not appear before a throw statement"); + } + minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + if((this.currentToken.tokenId != TypeScript.TokenID.Semicolon) && (this.currentToken.tokenId != TypeScript.TokenID.CloseBrace) && (!(this.scanner.lastTokenHadNewline()))) { + temp = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); + } else { + this.reportParseError("throw with no target"); + temp = null; + } + ast = new TypeScript.UnaryExpression(TypeScript.NodeType.Throw, temp); + ast.limChar = this.scanner.lastTokenLimChar(); + needTerminator = true; + break; + + } + case TypeScript.TokenID.Enum: { + this.currentToken = this.scanner.scan(); + ast = this.parseEnumDecl(errorRecoverySet, modifiers); + ast.minChar = minChar; + ast.limChar = this.scanner.lastTokenLimChar(); + if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + (ast).modFlags |= TypeScript.ModuleFlags.Ambient; + } + if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { + (ast).modFlags |= TypeScript.ModuleFlags.Exported; + } + break; + + } + case TypeScript.TokenID.Debugger: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("modifiers can not appear before debugger statement"); + } + minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + var debuggerStmt = new TypeScript.DebuggerStatement(); + debuggerStmt.minChar = minChar; + needTerminator = true; + debuggerStmt.limChar = this.scanner.lastTokenLimChar(); + ast = debuggerStmt; + break; + + } + default: { + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("modifiers can not appear before an expression statement or label"); + } + minChar = this.scanner.startPos; + var svPos = this.scanner.pos; + temp = this.parseExpr(TypeScript.ErrorRecoverySet.Colon | TypeScript.ErrorRecoverySet.StmtStart | errorRecoverySet, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); + if(this.scanner.pos == svPos) { + this.currentToken = this.scanner.scan(); + ast = temp; + } else { + if((this.currentToken.tokenId == TypeScript.TokenID.Colon) && (!this.scanner.lastTokenHadNewline()) && temp && (temp.nodeType == TypeScript.NodeType.Name)) { + if(labelList == null) { + labelList = new TypeScript.ASTList(); + } + labelList.append(new TypeScript.Label(temp)); + this.currentToken = this.scanner.scan(); + } else { + ast = temp; + needTerminator = true; + } + } + + } + } + if(ast) { + break; + } + } + if(needTerminator) { + switch(this.currentToken.tokenId) { + case TypeScript.TokenID.Semicolon: { + this.currentToken = this.scanner.scan(); + ast.flags |= TypeScript.ASTFlags.ExplicitSemicolon; + break; + + } + case TypeScript.TokenID.EndOfFile: { + ast.limChar = this.scanner.pos; + + } + case TypeScript.TokenID.CloseBrace: { + ast.flags |= TypeScript.ASTFlags.AutomaticSemicolon; + if(this.style_requireSemi) { + this.reportParseStyleError("no automatic semicolon"); + } + break; + + } + default: { + if(!this.scanner.lastTokenHadNewline()) { + this.reportParseError("Expected ';'"); + } else { + ast.flags |= TypeScript.ASTFlags.AutomaticSemicolon; + if(this.style_requireSemi) { + this.reportParseStyleError("no automatic semicolon"); + } + } + break; + + } + } + } + if(labelList) { + ast = new TypeScript.LabeledStatement(labelList, ast); + } + ast.minChar = minChar; + ast.limChar = TypeScript.max(ast.limChar, this.scanner.lastTokenLimChar()); + if(preComments) { + ast.preComments = preComments; + } + if(this.ambientModule && (!this.okAmbientModuleMember(ast))) { + this.reportParseError("statement not permitted within ambient module"); + } + ast.flags |= TypeScript.ASTFlags.IsStatement; + return ast; + }; + Parser.prototype.okAmbientModuleMember = function (ast) { + var nt = ast.nodeType; + return (nt == TypeScript.NodeType.ClassDeclaration) || (nt == TypeScript.NodeType.ImportDeclaration) || (nt == TypeScript.NodeType.InterfaceDeclaration) || (nt == TypeScript.NodeType.ModuleDeclaration) || (nt == TypeScript.NodeType.Empty) || (nt == TypeScript.NodeType.VarDecl) || ((nt == TypeScript.NodeType.Block) && !(ast).isStatementBlock) || ((nt == TypeScript.NodeType.FuncDecl) && ((ast).isMethod())); + }; + Parser.prototype.parseStatementList = function (errorRecoverySet, statements, sourceElms, noLeadingCase, allowedElements, parentModifiers) { + var directivePrologue = sourceElms; + statements.minChar = this.scanner.startPos; + var limChar = this.scanner.pos; + var innerStmts = (allowedElements & TypeScript.AllowedElements.ModuleDeclarations) == TypeScript.AllowedElements.None; + var classNope = (allowedElements & TypeScript.AllowedElements.ClassDeclarations) == TypeScript.AllowedElements.None; + errorRecoverySet |= TypeScript.ErrorRecoverySet.TypeScriptS | TypeScript.ErrorRecoverySet.RCurly; + this.state = ParseState.StartStatementList; + var oldStrictMode = this.strictMode; + this.nestingLevel++; + for(; ; ) { + if((this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) || (noLeadingCase && ((this.currentToken.tokenId == TypeScript.TokenID.Case) || (this.currentToken.tokenId == TypeScript.TokenID.Default))) || (innerStmts && (this.currentToken.tokenId == TypeScript.TokenID.Export)) || (classNope && (this.currentToken.tokenId == TypeScript.TokenID.Class)) || (this.currentToken.tokenId == TypeScript.TokenID.EndOfFile)) { + this.state = ParseState.EndStmtList; + statements.limChar = limChar; + if(statements.members.length == 0) { + statements.preComments = this.parseComments(); + } else { + statements.postComments = this.parseComments(); + } + this.strictMode = oldStrictMode; + this.nestingLevel--; + return; + } + var stmt = this.parseStatement(errorRecoverySet & (~(TypeScript.ErrorRecoverySet.Else | TypeScript.ErrorRecoverySet.RParen | TypeScript.ErrorRecoverySet.Catch | TypeScript.ErrorRecoverySet.Colon)), allowedElements, parentModifiers); + if(stmt) { + stmt.postComments = this.combineComments(stmt.postComments, this.parseCommentsForLine(this.scanner.prevLine)); + statements.append(stmt); + limChar = stmt.limChar; + if(directivePrologue) { + if(stmt.nodeType == TypeScript.NodeType.QString) { + var qstring = stmt; + if(qstring.text == "\"use strict\"") { + statements.flags |= TypeScript.ASTFlags.StrictMode; + this.strictMode = true; + } else { + directivePrologue = false; + } + } else { + directivePrologue = false; + } + } + } + } + }; + Parser.prototype.quickParse = function (sourceText, filename, unitIndex) { + var svGenTarget = TypeScript.moduleGenTarget; + try { + TypeScript.moduleGenTarget = TypeScript.ModuleGenTarget.Local; + var script = this.parse(sourceText, filename, unitIndex, TypeScript.AllowedElements.QuickParse); + return new QuickParseResult(script, this.scanner.lexState); + }finally { + TypeScript.moduleGenTarget = svGenTarget; + } + }; + Parser.prototype.parse = function (sourceText, filename, unitIndex, allowedElements) { + if (typeof allowedElements === "undefined") { allowedElements = TypeScript.AllowedElements.Global; } + var _this = this; + this.ambientModule = false; + this.topLevel = true; + this.hasTopLevelImportOrExport = false; + this.requiresExtendsBlock = false; + this.fname = filename; + this.currentUnitIndex = unitIndex; + this.amdDependencies = []; + this.scanner.resetComments(); + this.scanner.setErrorHandler(function (message) { + return _this.reportParseError(message); + }); + this.scanner.setSourceText(sourceText, TypeScript.LexMode.File); + var leftCurlyCount = this.scanner.leftCurlyCount; + var rightCurlyCount = this.scanner.rightCurlyCount; + var minChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + this.pushDeclLists(); + var bod = new TypeScript.ASTList(); + bod.minChar = minChar; + this.state = ParseState.StartScript; + this.parsingDeclareFile = TypeScript.isDSTRFile(filename) || TypeScript.isDTSFile(filename); + while(true) { + this.parseStatementList(TypeScript.ErrorRecoverySet.EOF | TypeScript.ErrorRecoverySet.Func, bod, true, false, allowedElements, TypeScript.Modifiers.None); + if(this.currentToken.tokenId === TypeScript.TokenID.EndOfFile) { + break; + } + var badToken = TypeScript.tokenTable[this.currentToken.tokenId]; + this.reportParseError("Unexpected statement block terminator '" + badToken.text + "'"); + this.currentToken = this.scanner.scan(); + } + this.state = ParseState.EndScript; + bod.limChar = this.scanner.pos; + var topLevelMod = null; + if(TypeScript.moduleGenTarget != TypeScript.ModuleGenTarget.Local && this.hasTopLevelImportOrExport) { + var correctedFileName = TypeScript.switchToForwardSlashes(filename); + var id = new TypeScript.Identifier(correctedFileName); + topLevelMod = new TypeScript.ModuleDeclaration(id, bod, this.topVarList(), this.topScopeList(), null); + topLevelMod.modFlags |= TypeScript.ModuleFlags.IsDynamic; + topLevelMod.modFlags |= TypeScript.ModuleFlags.IsWholeFile; + topLevelMod.modFlags |= TypeScript.ModuleFlags.Exported; + if(this.parsingDeclareFile) { + topLevelMod.modFlags |= TypeScript.ModuleFlags.Ambient; + } + topLevelMod.minChar = minChar; + topLevelMod.limChar = this.scanner.pos; + topLevelMod.prettyName = TypeScript.getPrettyName(correctedFileName); + topLevelMod.containsUnicodeChar = this.scanner.seenUnicodeChar; + topLevelMod.containsUnicodeCharInComment = this.scanner.seenUnicodeCharInComment; + topLevelMod.amdDependencies = this.amdDependencies; + bod = new TypeScript.ASTList(); + bod.minChar = topLevelMod.minChar; + bod.limChar = topLevelMod.limChar; + bod.append(topLevelMod); + } + var script = new TypeScript.Script(this.topVarList(), this.topScopeList()); + script.bod = bod; + this.popDeclLists(); + script.minChar = minChar; + script.limChar = this.scanner.pos; + script.locationInfo = new TypeScript.LocationInfo(filename, this.scanner.lineMap, unitIndex); + script.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; + script.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; + script.isDeclareFile = this.parsingDeclareFile; + script.topLevelMod = topLevelMod; + script.containsUnicodeChar = this.scanner.seenUnicodeChar; + script.containsUnicodeCharInComment = this.scanner.seenUnicodeCharInComment; + script.requiresExtendsBlock = this.requiresExtendsBlock; + return script; + }; + return Parser; + })(); + TypeScript.Parser = Parser; + function quickParse(logger, scopeStartAST, sourceText, minChar, limChar, errorCapture) { + var fragment = sourceText.getText(minChar, limChar); + logger.log("Quick parse range (" + minChar + "," + limChar + "): \"" + TypeScript.stringToLiteral(fragment, 100) + "\""); + var quickParser = new Parser(); + quickParser.setErrorRecovery(null); + quickParser.errorCallback = errorCapture; + var quickClassDecl = new TypeScript.ClassDeclaration(null, null, null, null); + quickParser.currentClassDecl = quickClassDecl; + var result = quickParser.quickParse(new TypeScript.StringSourceText(fragment), "", 0); + return result; + } + TypeScript.quickParse = quickParse; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var PrintContext = (function () { + function PrintContext(outfile, parser) { + this.outfile = outfile; + this.parser = parser; + this.builder = ""; + this.indent1 = " "; + this.indentStrings = []; + this.indentAmt = 0; + } + PrintContext.prototype.increaseIndent = function () { + this.indentAmt++; + }; + PrintContext.prototype.decreaseIndent = function () { + this.indentAmt--; + }; + PrintContext.prototype.startLine = function () { + if(this.builder.length > 0) { + TypeScript.CompilerDiagnostics.Alert(this.builder); + } + var indentString = this.indentStrings[this.indentAmt]; + if(indentString === undefined) { + indentString = ""; + for(var i = 0; i < this.indentAmt; i++) { + indentString += this.indent1; + } + this.indentStrings[this.indentAmt] = indentString; + } + this.builder += indentString; + }; + PrintContext.prototype.write = function (s) { + this.builder += s; + }; + PrintContext.prototype.writeLine = function (s) { + this.builder += s; + this.outfile.WriteLine(this.builder); + this.builder = ""; + }; + return PrintContext; + })(); + TypeScript.PrintContext = PrintContext; + function prePrintAST(ast, parent, walker) { + var pc = walker.state; + ast.print(pc); + pc.increaseIndent(); + return ast; + } + TypeScript.prePrintAST = prePrintAST; + function postPrintAST(ast, parent, walker) { + var pc = walker.state; + pc.decreaseIndent(); + return ast; + } + TypeScript.postPrintAST = postPrintAST; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + TypeScript.LexEOF = (-1); + TypeScript.LexCodeNWL = 10; + TypeScript.LexCodeRET = 13; + TypeScript.LexCodeLS = 8232; + TypeScript.LexCodePS = 8233; + TypeScript.LexCodeTAB = 9; + TypeScript.LexCodeVTAB = 11; + TypeScript.LexCode_e = 'e'.charCodeAt(0); + TypeScript.LexCode_E = 'E'.charCodeAt(0); + TypeScript.LexCode_x = 'x'.charCodeAt(0); + TypeScript.LexCode_X = 'X'.charCodeAt(0); + TypeScript.LexCode_a = 'a'.charCodeAt(0); + TypeScript.LexCode_A = 'A'.charCodeAt(0); + TypeScript.LexCode_f = 'f'.charCodeAt(0); + TypeScript.LexCode_F = 'F'.charCodeAt(0); + TypeScript.LexCode_g = 'g'.charCodeAt(0); + TypeScript.LexCode_m = 'm'.charCodeAt(0); + TypeScript.LexCode_i = 'i'.charCodeAt(0); + TypeScript.LexCode_u = 'u'.charCodeAt(0); + TypeScript.LexCode_0 = '0'.charCodeAt(0); + TypeScript.LexCode_9 = '9'.charCodeAt(0); + TypeScript.LexCode_8 = '8'.charCodeAt(0); + TypeScript.LexCode_7 = '7'.charCodeAt(0); + TypeScript.LexCodeBSL = '\\'.charCodeAt(0); + TypeScript.LexCodeSHP = '#'.charCodeAt(0); + TypeScript.LexCodeBNG = '!'.charCodeAt(0); + TypeScript.LexCodeQUO = '"'.charCodeAt(0); + TypeScript.LexCodeAPO = '\''.charCodeAt(0); + TypeScript.LexCodePCT = '%'.charCodeAt(0); + TypeScript.LexCodeAMP = '&'.charCodeAt(0); + TypeScript.LexCodeLPR = '('.charCodeAt(0); + TypeScript.LexCodeRPR = ')'.charCodeAt(0); + TypeScript.LexCodePLS = '+'.charCodeAt(0); + TypeScript.LexCodeMIN = '-'.charCodeAt(0); + TypeScript.LexCodeMUL = '*'.charCodeAt(0); + TypeScript.LexCodeSLH = '/'.charCodeAt(0); + TypeScript.LexCodeXOR = '^'.charCodeAt(0); + TypeScript.LexCodeCMA = ','.charCodeAt(0); + TypeScript.LexCodeDOT = '.'.charCodeAt(0); + TypeScript.LexCodeLT = '<'.charCodeAt(0); + TypeScript.LexCodeEQ = '='.charCodeAt(0); + TypeScript.LexCodeGT = '>'.charCodeAt(0); + TypeScript.LexCodeQUE = '?'.charCodeAt(0); + TypeScript.LexCodeLBR = '['.charCodeAt(0); + TypeScript.LexCodeRBR = ']'.charCodeAt(0); + TypeScript.LexCodeUSC = '_'.charCodeAt(0); + TypeScript.LexCodeLC = '{'.charCodeAt(0); + TypeScript.LexCodeRC = '}'.charCodeAt(0); + TypeScript.LexCodeBAR = '|'.charCodeAt(0); + TypeScript.LexCodeTIL = '~'.charCodeAt(0); + TypeScript.LexCodeCOL = ':'.charCodeAt(0); + TypeScript.LexCodeSMC = ';'.charCodeAt(0); + TypeScript.LexCodeUnderscore = '_'.charCodeAt(0); + TypeScript.LexCodeDollar = '$'.charCodeAt(0); + TypeScript.LexCodeSpace = 32; + TypeScript.LexCodeAtSign = '@'.charCodeAt(0); + TypeScript.LexCodeASCIIChars = 128; + TypeScript.LexKeywordTable = undefined; + var autoToken = new Array(TypeScript.LexCodeASCIIChars); + var lexIdStartTable = new Array(TypeScript.LexCodeASCIIChars); + var unicodeES3IdStart = [ + 170, + 170, + 181, + 181, + 186, + 186, + 192, + 214, + 216, + 246, + 248, + 543, + 546, + 563, + 592, + 685, + 688, + 696, + 699, + 705, + 720, + 721, + 736, + 740, + 750, + 750, + 890, + 890, + 902, + 902, + 904, + 906, + 908, + 908, + 910, + 929, + 931, + 974, + 976, + 983, + 986, + 1011, + 1024, + 1153, + 1164, + 1220, + 1223, + 1224, + 1227, + 1228, + 1232, + 1269, + 1272, + 1273, + 1329, + 1366, + 1369, + 1369, + 1377, + 1415, + 1488, + 1514, + 1520, + 1522, + 1569, + 1594, + 1600, + 1610, + 1649, + 1747, + 1749, + 1749, + 1765, + 1766, + 1786, + 1788, + 1808, + 1808, + 1810, + 1836, + 1920, + 1957, + 2309, + 2361, + 2365, + 2365, + 2384, + 2384, + 2392, + 2401, + 2437, + 2444, + 2447, + 2448, + 2451, + 2472, + 2474, + 2480, + 2482, + 2482, + 2486, + 2489, + 2524, + 2525, + 2527, + 2529, + 2544, + 2545, + 2565, + 2570, + 2575, + 2576, + 2579, + 2600, + 2602, + 2608, + 2610, + 2611, + 2613, + 2614, + 2616, + 2617, + 2649, + 2652, + 2654, + 2654, + 2674, + 2676, + 2693, + 2699, + 2701, + 2701, + 2703, + 2705, + 2707, + 2728, + 2730, + 2736, + 2738, + 2739, + 2741, + 2745, + 2749, + 2749, + 2768, + 2768, + 2784, + 2784, + 2821, + 2828, + 2831, + 2832, + 2835, + 2856, + 2858, + 2864, + 2866, + 2867, + 2870, + 2873, + 2877, + 2877, + 2908, + 2909, + 2911, + 2913, + 2949, + 2954, + 2958, + 2960, + 2962, + 2965, + 2969, + 2970, + 2972, + 2972, + 2974, + 2975, + 2979, + 2980, + 2984, + 2986, + 2990, + 2997, + 2999, + 3001, + 3077, + 3084, + 3086, + 3088, + 3090, + 3112, + 3114, + 3123, + 3125, + 3129, + 3168, + 3169, + 3205, + 3212, + 3214, + 3216, + 3218, + 3240, + 3242, + 3251, + 3253, + 3257, + 3294, + 3294, + 3296, + 3297, + 3333, + 3340, + 3342, + 3344, + 3346, + 3368, + 3370, + 3385, + 3424, + 3425, + 3461, + 3478, + 3482, + 3505, + 3507, + 3515, + 3517, + 3517, + 3520, + 3526, + 3585, + 3632, + 3634, + 3635, + 3648, + 3654, + 3713, + 3714, + 3716, + 3716, + 3719, + 3720, + 3722, + 3722, + 3725, + 3725, + 3732, + 3735, + 3737, + 3743, + 3745, + 3747, + 3749, + 3749, + 3751, + 3751, + 3754, + 3755, + 3757, + 3760, + 3762, + 3763, + 3773, + 3773, + 3776, + 3780, + 3782, + 3782, + 3804, + 3805, + 3840, + 3840, + 3904, + 3911, + 3913, + 3946, + 3976, + 3979, + 4096, + 4129, + 4131, + 4135, + 4137, + 4138, + 4176, + 4181, + 4256, + 4293, + 4304, + 4342, + 4352, + 4441, + 4447, + 4514, + 4520, + 4601, + 4608, + 4614, + 4616, + 4678, + 4680, + 4680, + 4682, + 4685, + 4688, + 4694, + 4696, + 4696, + 4698, + 4701, + 4704, + 4742, + 4744, + 4744, + 4746, + 4749, + 4752, + 4782, + 4784, + 4784, + 4786, + 4789, + 4792, + 4798, + 4800, + 4800, + 4802, + 4805, + 4808, + 4814, + 4816, + 4822, + 4824, + 4846, + 4848, + 4878, + 4880, + 4880, + 4882, + 4885, + 4888, + 4894, + 4896, + 4934, + 4936, + 4954, + 5024, + 5108, + 5121, + 5740, + 5743, + 5750, + 5761, + 5786, + 5792, + 5866, + 6016, + 6067, + 6176, + 6263, + 6272, + 6312, + 7680, + 7835, + 7840, + 7929, + 7936, + 7957, + 7960, + 7965, + 7968, + 8005, + 8008, + 8013, + 8016, + 8023, + 8025, + 8025, + 8027, + 8027, + 8029, + 8029, + 8031, + 8061, + 8064, + 8116, + 8118, + 8124, + 8126, + 8126, + 8130, + 8132, + 8134, + 8140, + 8144, + 8147, + 8150, + 8155, + 8160, + 8172, + 8178, + 8180, + 8182, + 8188, + 8319, + 8319, + 8450, + 8450, + 8455, + 8455, + 8458, + 8467, + 8469, + 8469, + 8473, + 8477, + 8484, + 8484, + 8486, + 8486, + 8488, + 8488, + 8490, + 8493, + 8495, + 8497, + 8499, + 8505, + 8544, + 8579, + 12293, + 12295, + 12321, + 12329, + 12337, + 12341, + 12344, + 12346, + 12353, + 12436, + 12445, + 12446, + 12449, + 12538, + 12540, + 12542, + 12549, + 12588, + 12593, + 12686, + 12704, + 12727, + 13312, + 13312, + 19893, + 19893, + 19968, + 19968, + 40869, + 40869, + 40960, + 42124, + 44032, + 44032, + 55203, + 55203, + 63744, + 64045, + 64256, + 64262, + 64275, + 64279, + 64285, + 64285, + 64287, + 64296, + 64298, + 64310, + 64312, + 64316, + 64318, + 64318, + 64320, + 64321, + 64323, + 64324, + 64326, + 64433, + 64467, + 64829, + 64848, + 64911, + 64914, + 64967, + 65008, + 65019, + 65136, + 65138, + 65140, + 65140, + 65142, + 65276, + 65313, + 65338, + 65345, + 65370, + 65382, + 65470, + 65474, + 65479, + 65482, + 65487, + 65490, + 65495, + 65498, + 65500 + ]; + var unicodeES3IdCont = [ + 768, + 846, + 864, + 866, + 1155, + 1158, + 1425, + 1441, + 1443, + 1465, + 1467, + 1469, + 1471, + 1471, + 1473, + 1474, + 1476, + 1476, + 1611, + 1621, + 1632, + 1641, + 1648, + 1648, + 1750, + 1756, + 1759, + 1764, + 1767, + 1768, + 1770, + 1773, + 1776, + 1785, + 1809, + 1809, + 1840, + 1866, + 1958, + 1968, + 2305, + 2307, + 2364, + 2364, + 2366, + 2381, + 2385, + 2388, + 2402, + 2403, + 2406, + 2415, + 2433, + 2435, + 2492, + 2492, + 2494, + 2500, + 2503, + 2504, + 2507, + 2509, + 2519, + 2519, + 2530, + 2531, + 2534, + 2543, + 2562, + 2562, + 2620, + 2620, + 2622, + 2626, + 2631, + 2632, + 2635, + 2637, + 2662, + 2673, + 2689, + 2691, + 2748, + 2748, + 2750, + 2757, + 2759, + 2761, + 2763, + 2765, + 2790, + 2799, + 2817, + 2819, + 2876, + 2876, + 2878, + 2883, + 2887, + 2888, + 2891, + 2893, + 2902, + 2903, + 2918, + 2927, + 2946, + 2947, + 3006, + 3010, + 3014, + 3016, + 3018, + 3021, + 3031, + 3031, + 3047, + 3055, + 3073, + 3075, + 3134, + 3140, + 3142, + 3144, + 3146, + 3149, + 3157, + 3158, + 3174, + 3183, + 3202, + 3203, + 3262, + 3268, + 3270, + 3272, + 3274, + 3277, + 3285, + 3286, + 3302, + 3311, + 3330, + 3331, + 3390, + 3395, + 3398, + 3400, + 3402, + 3405, + 3415, + 3415, + 3430, + 3439, + 3458, + 3459, + 3530, + 3530, + 3535, + 3540, + 3542, + 3542, + 3544, + 3551, + 3570, + 3571, + 3633, + 3633, + 3636, + 3642, + 3655, + 3662, + 3664, + 3673, + 3761, + 3761, + 3764, + 3769, + 3771, + 3772, + 3784, + 3789, + 3792, + 3801, + 3864, + 3865, + 3872, + 3881, + 3893, + 3893, + 3895, + 3895, + 3897, + 3897, + 3902, + 3903, + 3953, + 3972, + 3974, + 3975, + 3984, + 3991, + 3993, + 4028, + 4038, + 4038, + 4140, + 4146, + 4150, + 4153, + 4160, + 4169, + 4182, + 4185, + 4969, + 4977, + 6068, + 6099, + 6112, + 6121, + 6160, + 6169, + 6313, + 6313, + 8255, + 8256, + 8400, + 8412, + 8417, + 8417, + 12330, + 12335, + 12441, + 12442, + 12539, + 12539, + 64286, + 64286, + 65056, + 65059, + 65075, + 65076, + 65101, + 65103, + 65296, + 65305, + 65343, + 65343, + 65381, + 65381 + ]; + var unicodeES5IdStart = [ + 170, + 170, + 181, + 181, + 186, + 186, + 192, + 214, + 216, + 246, + 248, + 705, + 710, + 721, + 736, + 740, + 748, + 748, + 750, + 750, + 880, + 884, + 886, + 887, + 890, + 893, + 902, + 902, + 904, + 906, + 908, + 908, + 910, + 929, + 931, + 1013, + 1015, + 1153, + 1162, + 1319, + 1329, + 1366, + 1369, + 1369, + 1377, + 1415, + 1488, + 1514, + 1520, + 1522, + 1568, + 1610, + 1646, + 1647, + 1649, + 1747, + 1749, + 1749, + 1765, + 1766, + 1774, + 1775, + 1786, + 1788, + 1791, + 1791, + 1808, + 1808, + 1810, + 1839, + 1869, + 1957, + 1969, + 1969, + 1994, + 2026, + 2036, + 2037, + 2042, + 2042, + 2048, + 2069, + 2074, + 2074, + 2084, + 2084, + 2088, + 2088, + 2112, + 2136, + 2208, + 2208, + 2210, + 2220, + 2308, + 2361, + 2365, + 2365, + 2384, + 2384, + 2392, + 2401, + 2417, + 2423, + 2425, + 2431, + 2437, + 2444, + 2447, + 2448, + 2451, + 2472, + 2474, + 2480, + 2482, + 2482, + 2486, + 2489, + 2493, + 2493, + 2510, + 2510, + 2524, + 2525, + 2527, + 2529, + 2544, + 2545, + 2565, + 2570, + 2575, + 2576, + 2579, + 2600, + 2602, + 2608, + 2610, + 2611, + 2613, + 2614, + 2616, + 2617, + 2649, + 2652, + 2654, + 2654, + 2674, + 2676, + 2693, + 2701, + 2703, + 2705, + 2707, + 2728, + 2730, + 2736, + 2738, + 2739, + 2741, + 2745, + 2749, + 2749, + 2768, + 2768, + 2784, + 2785, + 2821, + 2828, + 2831, + 2832, + 2835, + 2856, + 2858, + 2864, + 2866, + 2867, + 2869, + 2873, + 2877, + 2877, + 2908, + 2909, + 2911, + 2913, + 2929, + 2929, + 2947, + 2947, + 2949, + 2954, + 2958, + 2960, + 2962, + 2965, + 2969, + 2970, + 2972, + 2972, + 2974, + 2975, + 2979, + 2980, + 2984, + 2986, + 2990, + 3001, + 3024, + 3024, + 3077, + 3084, + 3086, + 3088, + 3090, + 3112, + 3114, + 3123, + 3125, + 3129, + 3133, + 3133, + 3160, + 3161, + 3168, + 3169, + 3205, + 3212, + 3214, + 3216, + 3218, + 3240, + 3242, + 3251, + 3253, + 3257, + 3261, + 3261, + 3294, + 3294, + 3296, + 3297, + 3313, + 3314, + 3333, + 3340, + 3342, + 3344, + 3346, + 3386, + 3389, + 3389, + 3406, + 3406, + 3424, + 3425, + 3450, + 3455, + 3461, + 3478, + 3482, + 3505, + 3507, + 3515, + 3517, + 3517, + 3520, + 3526, + 3585, + 3632, + 3634, + 3635, + 3648, + 3654, + 3713, + 3714, + 3716, + 3716, + 3719, + 3720, + 3722, + 3722, + 3725, + 3725, + 3732, + 3735, + 3737, + 3743, + 3745, + 3747, + 3749, + 3749, + 3751, + 3751, + 3754, + 3755, + 3757, + 3760, + 3762, + 3763, + 3773, + 3773, + 3776, + 3780, + 3782, + 3782, + 3804, + 3807, + 3840, + 3840, + 3904, + 3911, + 3913, + 3948, + 3976, + 3980, + 4096, + 4138, + 4159, + 4159, + 4176, + 4181, + 4186, + 4189, + 4193, + 4193, + 4197, + 4198, + 4206, + 4208, + 4213, + 4225, + 4238, + 4238, + 4256, + 4293, + 4295, + 4295, + 4301, + 4301, + 4304, + 4346, + 4348, + 4680, + 4682, + 4685, + 4688, + 4694, + 4696, + 4696, + 4698, + 4701, + 4704, + 4744, + 4746, + 4749, + 4752, + 4784, + 4786, + 4789, + 4792, + 4798, + 4800, + 4800, + 4802, + 4805, + 4808, + 4822, + 4824, + 4880, + 4882, + 4885, + 4888, + 4954, + 4992, + 5007, + 5024, + 5108, + 5121, + 5740, + 5743, + 5759, + 5761, + 5786, + 5792, + 5866, + 5870, + 5872, + 5888, + 5900, + 5902, + 5905, + 5920, + 5937, + 5952, + 5969, + 5984, + 5996, + 5998, + 6000, + 6016, + 6067, + 6103, + 6103, + 6108, + 6108, + 6176, + 6263, + 6272, + 6312, + 6314, + 6314, + 6320, + 6389, + 6400, + 6428, + 6480, + 6509, + 6512, + 6516, + 6528, + 6571, + 6593, + 6599, + 6656, + 6678, + 6688, + 6740, + 6823, + 6823, + 6917, + 6963, + 6981, + 6987, + 7043, + 7072, + 7086, + 7087, + 7098, + 7141, + 7168, + 7203, + 7245, + 7247, + 7258, + 7293, + 7401, + 7404, + 7406, + 7409, + 7413, + 7414, + 7424, + 7615, + 7680, + 7957, + 7960, + 7965, + 7968, + 8005, + 8008, + 8013, + 8016, + 8023, + 8025, + 8025, + 8027, + 8027, + 8029, + 8029, + 8031, + 8061, + 8064, + 8116, + 8118, + 8124, + 8126, + 8126, + 8130, + 8132, + 8134, + 8140, + 8144, + 8147, + 8150, + 8155, + 8160, + 8172, + 8178, + 8180, + 8182, + 8188, + 8305, + 8305, + 8319, + 8319, + 8336, + 8348, + 8450, + 8450, + 8455, + 8455, + 8458, + 8467, + 8469, + 8469, + 8473, + 8477, + 8484, + 8484, + 8486, + 8486, + 8488, + 8488, + 8490, + 8493, + 8495, + 8505, + 8508, + 8511, + 8517, + 8521, + 8526, + 8526, + 8544, + 8584, + 11264, + 11310, + 11312, + 11358, + 11360, + 11492, + 11499, + 11502, + 11506, + 11507, + 11520, + 11557, + 11559, + 11559, + 11565, + 11565, + 11568, + 11623, + 11631, + 11631, + 11648, + 11670, + 11680, + 11686, + 11688, + 11694, + 11696, + 11702, + 11704, + 11710, + 11712, + 11718, + 11720, + 11726, + 11728, + 11734, + 11736, + 11742, + 11823, + 11823, + 12293, + 12295, + 12321, + 12329, + 12337, + 12341, + 12344, + 12348, + 12353, + 12438, + 12445, + 12447, + 12449, + 12538, + 12540, + 12543, + 12549, + 12589, + 12593, + 12686, + 12704, + 12730, + 12784, + 12799, + 13312, + 13312, + 19893, + 19893, + 19968, + 19968, + 40908, + 40908, + 40960, + 42124, + 42192, + 42237, + 42240, + 42508, + 42512, + 42527, + 42538, + 42539, + 42560, + 42606, + 42623, + 42647, + 42656, + 42735, + 42775, + 42783, + 42786, + 42888, + 42891, + 42894, + 42896, + 42899, + 42912, + 42922, + 43000, + 43009, + 43011, + 43013, + 43015, + 43018, + 43020, + 43042, + 43072, + 43123, + 43138, + 43187, + 43250, + 43255, + 43259, + 43259, + 43274, + 43301, + 43312, + 43334, + 43360, + 43388, + 43396, + 43442, + 43471, + 43471, + 43520, + 43560, + 43584, + 43586, + 43588, + 43595, + 43616, + 43638, + 43642, + 43642, + 43648, + 43695, + 43697, + 43697, + 43701, + 43702, + 43705, + 43709, + 43712, + 43712, + 43714, + 43714, + 43739, + 43741, + 43744, + 43754, + 43762, + 43764, + 43777, + 43782, + 43785, + 43790, + 43793, + 43798, + 43808, + 43814, + 43816, + 43822, + 43968, + 44002, + 44032, + 44032, + 55203, + 55203, + 55216, + 55238, + 55243, + 55291, + 63744, + 64109, + 64112, + 64217, + 64256, + 64262, + 64275, + 64279, + 64285, + 64285, + 64287, + 64296, + 64298, + 64310, + 64312, + 64316, + 64318, + 64318, + 64320, + 64321, + 64323, + 64324, + 64326, + 64433, + 64467, + 64829, + 64848, + 64911, + 64914, + 64967, + 65008, + 65019, + 65136, + 65140, + 65142, + 65276, + 65313, + 65338, + 65345, + 65370, + 65382, + 65470, + 65474, + 65479, + 65482, + 65487, + 65490, + 65495, + 65498, + 65500 + ]; + var unicodeES5IdCont = [ + 768, + 879, + 1155, + 1159, + 1425, + 1469, + 1471, + 1471, + 1473, + 1474, + 1476, + 1477, + 1479, + 1479, + 1552, + 1562, + 1611, + 1641, + 1648, + 1648, + 1750, + 1756, + 1759, + 1764, + 1767, + 1768, + 1770, + 1773, + 1776, + 1785, + 1809, + 1809, + 1840, + 1866, + 1958, + 1968, + 1984, + 1993, + 2027, + 2035, + 2070, + 2073, + 2075, + 2083, + 2085, + 2087, + 2089, + 2093, + 2137, + 2139, + 2276, + 2302, + 2304, + 2307, + 2362, + 2364, + 2366, + 2383, + 2385, + 2391, + 2402, + 2403, + 2406, + 2415, + 2433, + 2435, + 2492, + 2492, + 2494, + 2500, + 2503, + 2504, + 2507, + 2509, + 2519, + 2519, + 2530, + 2531, + 2534, + 2543, + 2561, + 2563, + 2620, + 2620, + 2622, + 2626, + 2631, + 2632, + 2635, + 2637, + 2641, + 2641, + 2662, + 2673, + 2677, + 2677, + 2689, + 2691, + 2748, + 2748, + 2750, + 2757, + 2759, + 2761, + 2763, + 2765, + 2786, + 2787, + 2790, + 2799, + 2817, + 2819, + 2876, + 2876, + 2878, + 2884, + 2887, + 2888, + 2891, + 2893, + 2902, + 2903, + 2914, + 2915, + 2918, + 2927, + 2946, + 2946, + 3006, + 3010, + 3014, + 3016, + 3018, + 3021, + 3031, + 3031, + 3046, + 3055, + 3073, + 3075, + 3134, + 3140, + 3142, + 3144, + 3146, + 3149, + 3157, + 3158, + 3170, + 3171, + 3174, + 3183, + 3202, + 3203, + 3260, + 3260, + 3262, + 3268, + 3270, + 3272, + 3274, + 3277, + 3285, + 3286, + 3298, + 3299, + 3302, + 3311, + 3330, + 3331, + 3390, + 3396, + 3398, + 3400, + 3402, + 3405, + 3415, + 3415, + 3426, + 3427, + 3430, + 3439, + 3458, + 3459, + 3530, + 3530, + 3535, + 3540, + 3542, + 3542, + 3544, + 3551, + 3570, + 3571, + 3633, + 3633, + 3636, + 3642, + 3655, + 3662, + 3664, + 3673, + 3761, + 3761, + 3764, + 3769, + 3771, + 3772, + 3784, + 3789, + 3792, + 3801, + 3864, + 3865, + 3872, + 3881, + 3893, + 3893, + 3895, + 3895, + 3897, + 3897, + 3902, + 3903, + 3953, + 3972, + 3974, + 3975, + 3981, + 3991, + 3993, + 4028, + 4038, + 4038, + 4139, + 4158, + 4160, + 4169, + 4182, + 4185, + 4190, + 4192, + 4194, + 4196, + 4199, + 4205, + 4209, + 4212, + 4226, + 4237, + 4239, + 4253, + 4957, + 4959, + 5906, + 5908, + 5938, + 5940, + 5970, + 5971, + 6002, + 6003, + 6068, + 6099, + 6109, + 6109, + 6112, + 6121, + 6155, + 6157, + 6160, + 6169, + 6313, + 6313, + 6432, + 6443, + 6448, + 6459, + 6470, + 6479, + 6576, + 6592, + 6600, + 6601, + 6608, + 6617, + 6679, + 6683, + 6741, + 6750, + 6752, + 6780, + 6783, + 6793, + 6800, + 6809, + 6912, + 6916, + 6964, + 6980, + 6992, + 7001, + 7019, + 7027, + 7040, + 7042, + 7073, + 7085, + 7088, + 7097, + 7142, + 7155, + 7204, + 7223, + 7232, + 7241, + 7248, + 7257, + 7376, + 7378, + 7380, + 7400, + 7405, + 7405, + 7410, + 7412, + 7616, + 7654, + 7676, + 7679, + 8204, + 8205, + 8255, + 8256, + 8276, + 8276, + 8400, + 8412, + 8417, + 8417, + 8421, + 8432, + 11503, + 11505, + 11647, + 11647, + 11744, + 11775, + 12330, + 12335, + 12441, + 12442, + 42528, + 42537, + 42607, + 42607, + 42612, + 42621, + 42655, + 42655, + 42736, + 42737, + 43010, + 43010, + 43014, + 43014, + 43019, + 43019, + 43043, + 43047, + 43136, + 43137, + 43188, + 43204, + 43216, + 43225, + 43232, + 43249, + 43264, + 43273, + 43302, + 43309, + 43335, + 43347, + 43392, + 43395, + 43443, + 43456, + 43472, + 43481, + 43561, + 43574, + 43587, + 43587, + 43596, + 43597, + 43600, + 43609, + 43643, + 43643, + 43696, + 43696, + 43698, + 43700, + 43703, + 43704, + 43710, + 43711, + 43713, + 43713, + 43755, + 43759, + 43765, + 43766, + 44003, + 44010, + 44012, + 44013, + 44016, + 44025, + 64286, + 64286, + 65024, + 65039, + 65056, + 65062, + 65075, + 65076, + 65101, + 65103, + 65296, + 65305, + 65343, + 65343 + ]; + function LexLookUpUnicodeMap(code, map) { + var lo = 0; + var hi = map.length; + var mid; + while(lo + 1 < hi) { + mid = lo + (hi - lo) / 2; + mid -= mid % 2; + if(map[mid] <= code && code <= map[mid + 1]) { + return true; + } + if(code < map[mid]) { + hi = mid; + } else { + lo = mid + 2; + } + } + return false; + } + TypeScript.LexLookUpUnicodeMap = LexLookUpUnicodeMap; + function LexIsUnicodeDigit(code) { + if(TypeScript.codeGenTarget == TypeScript.CodeGenTarget.ES3) { + return LexLookUpUnicodeMap(code, unicodeES3IdCont); + } else { + return LexLookUpUnicodeMap(code, unicodeES5IdCont); + } + } + TypeScript.LexIsUnicodeDigit = LexIsUnicodeDigit; + function LexIsUnicodeIdStart(code) { + if(TypeScript.codeGenTarget == TypeScript.CodeGenTarget.ES3) { + return LexLookUpUnicodeMap(code, unicodeES3IdStart); + } else { + return LexLookUpUnicodeMap(code, unicodeES5IdStart); + } + } + TypeScript.LexIsUnicodeIdStart = LexIsUnicodeIdStart; + function LexInitialize() { + TypeScript.initializeStaticTokens(); + autoToken[TypeScript.LexCodeLPR] = TypeScript.staticTokens[TypeScript.TokenID.OpenParen]; + autoToken[TypeScript.LexCodeRPR] = TypeScript.staticTokens[TypeScript.TokenID.CloseParen]; + autoToken[TypeScript.LexCodeCMA] = TypeScript.staticTokens[TypeScript.TokenID.Comma]; + autoToken[TypeScript.LexCodeSMC] = TypeScript.staticTokens[TypeScript.TokenID.Semicolon]; + autoToken[TypeScript.LexCodeLBR] = TypeScript.staticTokens[TypeScript.TokenID.OpenBracket]; + autoToken[TypeScript.LexCodeRBR] = TypeScript.staticTokens[TypeScript.TokenID.CloseBracket]; + autoToken[TypeScript.LexCodeTIL] = TypeScript.staticTokens[TypeScript.TokenID.Tilde]; + autoToken[TypeScript.LexCodeQUE] = TypeScript.staticTokens[TypeScript.TokenID.Question]; + autoToken[TypeScript.LexCodeLC] = TypeScript.staticTokens[TypeScript.TokenID.OpenBrace]; + autoToken[TypeScript.LexCodeRC] = TypeScript.staticTokens[TypeScript.TokenID.CloseBrace]; + autoToken[TypeScript.LexCodeCOL] = TypeScript.staticTokens[TypeScript.TokenID.Colon]; + TypeScript.LexKeywordTable = new TypeScript.StringHashTable(); + for(var i in (TypeScript.TokenID)._map) { + if((i) <= TypeScript.TokenID.LimKeyword) { + TypeScript.LexKeywordTable.add((TypeScript.TokenID)._map[i].toLowerCase(), i); + } + } + for(var j = 0; j < TypeScript.LexCodeASCIIChars; j++) { + if(LexIsIdentifierStartChar(j)) { + lexIdStartTable[j] = true; + } else { + lexIdStartTable[j] = false; + } + } + } + TypeScript.LexInitialize = LexInitialize; + function LexAdjustIndent(code, indentAmt) { + if((code == TypeScript.LexCodeLBR) || (code == TypeScript.LexCodeLC) || (code == TypeScript.LexCodeLPR)) { + return indentAmt + 1; + } else { + if((code == TypeScript.LexCodeRBR) || (code == TypeScript.LexCodeRC) || (code == TypeScript.LexCodeRPR)) { + return indentAmt - 1; + } else { + return indentAmt; + } + } + } + TypeScript.LexAdjustIndent = LexAdjustIndent; + function LexIsIdentifierStartChar(code) { + return (((code >= 97) && (code <= 122)) || ((code >= 65) && (code <= 90)) || (code == TypeScript.LexCodeDollar) || (code == TypeScript.LexCodeUnderscore)); + } + TypeScript.LexIsIdentifierStartChar = LexIsIdentifierStartChar; + function LexIsDigit(code) { + return ((code >= 48) && (code <= 57)); + } + TypeScript.LexIsDigit = LexIsDigit; + function LexIsIdentifierChar(code) { + return lexIdStartTable[code] || LexIsDigit(code); + } + TypeScript.LexIsIdentifierChar = LexIsIdentifierChar; + function LexMatchingOpen(code) { + if(code == TypeScript.LexCodeRBR) { + return TypeScript.LexCodeLBR; + } else { + if(code == TypeScript.LexCodeRC) { + return TypeScript.LexCodeLC; + } else { + if(code == TypeScript.LexCodeRPR) { + return TypeScript.LexCodeLPR; + } else { + return 0; + } + } + } + } + TypeScript.LexMatchingOpen = LexMatchingOpen; + (function (NumberScanState) { + NumberScanState._map = []; + NumberScanState._map[0] = "Start"; + NumberScanState.Start = 0; + NumberScanState._map[1] = "InFraction"; + NumberScanState.InFraction = 1; + NumberScanState._map[2] = "InEmptyFraction"; + NumberScanState.InEmptyFraction = 2; + NumberScanState._map[3] = "InExponent"; + NumberScanState.InExponent = 3; + })(TypeScript.NumberScanState || (TypeScript.NumberScanState = {})); + var NumberScanState = TypeScript.NumberScanState; + (function (LexState) { + LexState._map = []; + LexState._map[0] = "Start"; + LexState.Start = 0; + LexState._map[1] = "InMultilineComment"; + LexState.InMultilineComment = 1; + LexState._map[2] = "InMultilineSingleQuoteString"; + LexState.InMultilineSingleQuoteString = 2; + LexState._map[3] = "InMultilineDoubleQuoteString"; + LexState.InMultilineDoubleQuoteString = 3; + })(TypeScript.LexState || (TypeScript.LexState = {})); + var LexState = TypeScript.LexState; + (function (LexMode) { + LexMode._map = []; + LexMode._map[0] = "Line"; + LexMode.Line = 0; + LexMode._map[1] = "File"; + LexMode.File = 1; + })(TypeScript.LexMode || (TypeScript.LexMode = {})); + var LexMode = TypeScript.LexMode; + (function (CommentStyle) { + CommentStyle._map = []; + CommentStyle._map[0] = "Line"; + CommentStyle.Line = 0; + CommentStyle._map[1] = "Block"; + CommentStyle.Block = 1; + })(TypeScript.CommentStyle || (TypeScript.CommentStyle = {})); + var CommentStyle = TypeScript.CommentStyle; + var StringSourceText = (function () { + function StringSourceText(text) { + this.text = text; + } + StringSourceText.prototype.getText = function (start, end) { + return this.text.substring(start, end); + }; + StringSourceText.prototype.getLength = function () { + return this.text.length; + }; + return StringSourceText; + })(); + TypeScript.StringSourceText = StringSourceText; + var SourceTextSegment = (function () { + function SourceTextSegment(segmentStart, segmentEnd, segment) { + this.segmentStart = segmentStart; + this.segmentEnd = segmentEnd; + this.segment = segment; + } + SourceTextSegment.prototype.charCodeAt = function (index) { + return this.segment.charCodeAt(index - this.segmentStart); + }; + SourceTextSegment.prototype.substring = function (start, end) { + return this.segment.substring(start - this.segmentStart, end - this.segmentStart); + }; + return SourceTextSegment; + })(); + TypeScript.SourceTextSegment = SourceTextSegment; + var AggerateSourceTextSegment = (function () { + function AggerateSourceTextSegment(seg1, seg2) { + this.seg1 = seg1; + this.seg2 = seg2; + } + AggerateSourceTextSegment.prototype.charCodeAt = function (index) { + if(this.seg1.segmentStart <= index && index < this.seg1.segmentEnd) { + return this.seg1.segment.charCodeAt(index - this.seg1.segmentStart); + } + return this.seg2.segment.charCodeAt(index - this.seg2.segmentStart); + }; + AggerateSourceTextSegment.prototype.substring = function (start, end) { + if(this.seg1.segmentStart <= start && end <= this.seg1.segmentEnd) { + return this.seg1.segment.substring(start - this.seg1.segmentStart, end - this.seg1.segmentStart); + } + return this.seg2.segment.substring(start - this.seg2.segmentStart) + this.seg1.segment.substring(0, end - this.seg1.segmentStart); + }; + return AggerateSourceTextSegment; + })(); + TypeScript.AggerateSourceTextSegment = AggerateSourceTextSegment; + var ScannerTextStream = (function () { + function ScannerTextStream(sourceText) { + this.sourceText = sourceText; + this.agg = new AggerateSourceTextSegment(ScannerTextStream.emptySegment, ScannerTextStream.emptySegment); + this.len = this.sourceText.getLength(); + } + ScannerTextStream.emptySegment = new SourceTextSegment(0, 0, ""); + ScannerTextStream.prototype.max = function (a, b) { + return a >= b ? a : b; + }; + ScannerTextStream.prototype.min = function (a, b) { + return a <= b ? a : b; + }; + ScannerTextStream.prototype.fetchSegment = function (start, end) { + if(this.agg.seg1.segmentStart <= start && end <= this.agg.seg1.segmentEnd) { + return this.agg.seg1; + } + if(this.agg.seg2.segmentStart <= start && end <= this.agg.seg1.segmentEnd) { + return this.agg; + } + var prev = this.agg.seg1; + var s = prev.segmentEnd; + var e = TypeScript.max(s + 512, end); + e = TypeScript.min(e, this.len); + var src = this.sourceText.getText(s, e); + var newSeg = new SourceTextSegment(s, e, src); + this.agg.seg2 = prev; + this.agg.seg1 = newSeg; + return this.agg; + }; + ScannerTextStream.prototype.charCodeAt = function (index) { + return this.fetchSegment(index, index + 1).charCodeAt(index); + }; + ScannerTextStream.prototype.substring = function (start, end) { + return this.fetchSegment(start, end).substring(start, end); + }; + return ScannerTextStream; + })(); + TypeScript.ScannerTextStream = ScannerTextStream; + var SavedTokens = (function () { + function SavedTokens() { + this.prevToken = null; + this.curSavedToken = null; + this.prevSavedToken = null; + this.prevToken = null; + this.currentToken = 0; + this.tokens = new Array(); + this.seenUnicodeChar = false; + this.seenUnicodeCharInComment = false; + this.prevLine = 1; + this.line = 1; + this.col = 0; + this.lexState = LexState.Start; + this.commentStack = new Array(); + this.lineMap = []; + } + SavedTokens.prototype.previousToken = function () { + return this.prevToken; + }; + SavedTokens.prototype.close = function () { + this.currentToken = 0; + }; + SavedTokens.prototype.addToken = function (tok, scanner) { + this.tokens[this.currentToken++] = new TypeScript.SavedToken(tok, scanner.startPos, scanner.pos); + }; + SavedTokens.prototype.scan = function () { + this.startLine = this.line; + this.startPos = this.col; + if(this.currentTokenIndex == this.currentTokens.length) { + if(this.line < this.lineMap.length) { + this.line++; + this.col = 0; + this.currentTokenIndex = 0; + this.currentTokens = this.tokensByLine[this.line]; + } else { + return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; + } + } + if(this.currentTokenIndex < this.currentTokens.length) { + this.prevToken = this.curSavedToken.tok; + this.prevSavedToken = this.curSavedToken; + this.curSavedToken = this.currentTokens[this.currentTokenIndex++]; + var curToken = this.curSavedToken.tok; + this.pos = this.curSavedToken.limChar; + this.col += (this.curSavedToken.limChar - this.curSavedToken.minChar); + this.startPos = this.curSavedToken.minChar; + this.prevLine = this.line; + return curToken; + } else { + return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; + } + }; + SavedTokens.prototype.syncToTok = function (offset) { + this.line = getLineNumberFromPosition(this.lineMap, offset); + this.currentTokenIndex = 0; + var tmpCol = offset - this.lineMap[this.line]; + while((this.lexStateByLine[this.line] == LexState.InMultilineComment) && (this.line > 0)) { + this.line--; + tmpCol = 0; + } + var lenMin1 = this.lineMap.length - 1; + this.currentTokens = this.tokensByLine[this.line]; + while((this.currentTokens.length == 0) && (this.line < lenMin1)) { + this.line++; + this.currentTokens = this.tokensByLine[this.line]; + tmpCol = 0; + } + if(this.line <= lenMin1) { + while((this.currentTokenIndex < this.currentTokens.length) && (tmpCol > this.currentTokens[this.currentTokenIndex].limChar)) { + this.currentTokenIndex++; + } + if(this.currentTokenIndex < this.currentTokens.length) { + this.col = this.currentTokens[this.currentTokenIndex].minChar; + return this.col + this.lineMap[this.line]; + } + } + return -1; + }; + SavedTokens.prototype.lastTokenLimChar = function () { + if(this.prevSavedToken !== null) { + return this.prevSavedToken.limChar; + } else { + return 0; + } + }; + SavedTokens.prototype.lastTokenHadNewline = function () { + return this.prevLine != this.startLine; + }; + SavedTokens.prototype.pushComment = function (comment) { + this.commentStack.push(comment); + }; + SavedTokens.prototype.getComments = function () { + var stack = this.commentStack; + this.commentStack = []; + return stack; + }; + SavedTokens.prototype.getCommentsForLine = function (line) { + var comments = null; + while((this.commentStack.length > 0) && (this.commentStack[0].line == line)) { + if(comments == null) { + comments = [ + this.commentStack.shift() + ]; + } else { + comments = comments.concat([ + this.commentStack.shift() + ]); + } + } + return comments; + }; + SavedTokens.prototype.resetComments = function () { + this.commentStack = []; + }; + SavedTokens.prototype.setSourceText = function (newSrc, textMode) { + }; + SavedTokens.prototype.setErrorHandler = function (reportError) { + }; + SavedTokens.prototype.getLookAheadToken = function () { + throw new Error("Invalid operation."); + }; + return SavedTokens; + })(); + TypeScript.SavedTokens = SavedTokens; + var Scanner = (function () { + function Scanner() { + this.prevLine = 1; + this.line = 1; + this.col = 0; + this.pos = 0; + this.startPos = 0; + this.len = 0; + this.lineMap = []; + this.ch = TypeScript.LexEOF; + this.lexState = LexState.Start; + this.mode = LexMode.File; + this.scanComments = true; + this.interveningWhitespace = false; + this.interveningWhitespacePos = 0; + this.leftCurlyCount = 0; + this.rightCurlyCount = 0; + this.commentStack = new Array(); + this.saveScan = null; + this.seenUnicodeChar = false; + this.seenUnicodeCharInComment = false; + this.prevTok = TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; + this.startCol = this.col; + this.startLine = this.line; + this.lineMap[1] = 0; + if(!TypeScript.LexKeywordTable) { + LexInitialize(); + } + } + Scanner.prototype.previousToken = function () { + return this.prevTok; + }; + Scanner.prototype.setSourceText = function (newSrc, textMode) { + this.mode = textMode; + this.scanComments = (this.mode === LexMode.Line); + this.pos = 0; + this.interveningWhitespacePos = 0; + this.startPos = 0; + this.line = 1; + this.col = 0; + this.startCol = this.col; + this.startLine = this.line; + this.len = 0; + this.src = newSrc.getText(0, newSrc.getLength()); + this.len = this.src.length; + this.lineMap = []; + this.lineMap[1] = 0; + this.commentStack = []; + this.leftCurlyCount = 0; + this.rightCurlyCount = 0; + this.seenUnicodeChar = false; + this.seenUnicodeCharInComment = false; + }; + Scanner.prototype.setErrorHandler = function (reportError) { + this.reportError = reportError; + }; + Scanner.prototype.setSaveScan = function (savedTokens) { + this.saveScan = savedTokens; + }; + Scanner.prototype.setText = function (newSrc, textMode) { + this.setSourceText(new StringSourceText(newSrc), textMode); + }; + Scanner.prototype.setScanComments = function (value) { + this.scanComments = value; + }; + Scanner.prototype.getLexState = function () { + return this.lexState; + }; + Scanner.prototype.tokenStart = function () { + this.startPos = this.pos; + this.startLine = this.line; + this.startCol = this.col; + this.interveningWhitespace = false; + }; + Scanner.prototype.peekChar = function () { + if(this.pos < this.len) { + return this.src.charCodeAt(this.pos); + } else { + return TypeScript.LexEOF; + } + }; + Scanner.prototype.peekCharAt = function (index) { + if(index < this.len) { + return this.src.charCodeAt(index); + } else { + return TypeScript.LexEOF; + } + }; + Scanner.prototype.IsHexDigit = function (c) { + return ((c >= TypeScript.LexCode_0) && (c <= TypeScript.LexCode_9)) || ((c >= TypeScript.LexCode_A) && (c <= TypeScript.LexCode_F)) || ((c >= TypeScript.LexCode_a) && (c <= TypeScript.LexCode_f)); + }; + Scanner.prototype.IsOctalDigit = function (c) { + return ((c >= TypeScript.LexCode_0) && (c <= TypeScript.LexCode_7)) || ((c >= TypeScript.LexCode_a) && (c <= TypeScript.LexCode_f)); + }; + Scanner.prototype.scanHexDigits = function () { + var atLeastOneDigit = false; + for(; ; ) { + if(this.IsHexDigit(this.ch)) { + this.nextChar(); + atLeastOneDigit = true; + } else { + if(atLeastOneDigit) { + return new TypeScript.NumberLiteralToken(parseInt(this.src.substring(this.startPos, this.pos))); + } else { + return null; + } + } + } + }; + Scanner.prototype.scanOctalDigits = function () { + var atLeastOneDigit = false; + for(; ; ) { + if(this.IsOctalDigit(this.ch)) { + this.nextChar(); + atLeastOneDigit = true; + } else { + if(atLeastOneDigit) { + return new TypeScript.NumberLiteralToken(parseInt(this.src.substring(this.startPos, this.pos))); + } else { + return null; + } + } + } + }; + Scanner.prototype.scanDecimalNumber = function (state) { + var atLeastOneDigit = false; + var svPos = this.pos; + var svCol = this.col; + for(; ; ) { + if(LexIsDigit(this.ch)) { + atLeastOneDigit = true; + if(this.ch != TypeScript.LexCode_0 && state == NumberScanState.InEmptyFraction) { + state = NumberScanState.InFraction; + } + this.nextChar(); + } else { + if(this.ch == TypeScript.LexCodeDOT) { + if(state == NumberScanState.Start) { + this.nextChar(); + state = NumberScanState.InEmptyFraction; + } else { + if(atLeastOneDigit) { + return new TypeScript.NumberLiteralToken(parseFloat(this.src.substring(this.startPos, this.pos)), state == NumberScanState.InEmptyFraction); + } else { + this.pos = svPos; + this.col = svCol; + return null; + } + } + } else { + if((this.ch == TypeScript.LexCode_e) || (this.ch == TypeScript.LexCode_E)) { + if(state == NumberScanState.Start) { + if(atLeastOneDigit) { + atLeastOneDigit = false; + this.nextChar(); + state = NumberScanState.InExponent; + } else { + this.pos = svPos; + this.col = svCol; + return null; + } + } else { + if(state == NumberScanState.InFraction || state == NumberScanState.InEmptyFraction) { + this.nextChar(); + state = NumberScanState.InExponent; + atLeastOneDigit = false; + } else { + if(atLeastOneDigit) { + return new TypeScript.NumberLiteralToken(parseFloat(this.src.substring(this.startPos, this.pos))); + } else { + this.pos = svPos; + this.col = svCol; + return null; + } + } + } + } else { + if((this.ch == TypeScript.LexCodePLS) || (this.ch == TypeScript.LexCodeMIN)) { + if(state == NumberScanState.InExponent) { + if(!atLeastOneDigit) { + this.nextChar(); + } else { + this.pos = svPos; + this.col = svCol; + return null; + } + } else { + if(state == NumberScanState.InEmptyFraction || state == NumberScanState.InFraction) { + return new TypeScript.NumberLiteralToken(parseFloat(this.src.substring(this.startPos, this.pos)), state == NumberScanState.InEmptyFraction); + } else { + if(!atLeastOneDigit) { + this.pos = svPos; + this.col = svCol; + return null; + } else { + return new TypeScript.NumberLiteralToken(parseFloat(this.src.substring(this.startPos, this.pos))); + } + } + } + } else { + if(!atLeastOneDigit) { + this.pos = svPos; + this.col = svCol; + return null; + } else { + return new TypeScript.NumberLiteralToken(parseFloat(this.src.substring(this.startPos, this.pos)), state == NumberScanState.InEmptyFraction); + } + } + } + } + } + } + }; + Scanner.prototype.scanNumber = function () { + if(this.peekChar() == TypeScript.LexCode_0) { + switch(this.peekCharAt(this.pos + 1)) { + case TypeScript.LexCode_x: + case TypeScript.LexCode_X: { + this.advanceChar(2); + return this.scanHexDigits(); + + } + case TypeScript.LexCode_8: + case TypeScript.LexCode_9: + case TypeScript.LexCodeDOT: { + return this.scanDecimalNumber(NumberScanState.Start); + + } + default: { + return this.scanOctalDigits(); + + } + } + } else { + return this.scanDecimalNumber(NumberScanState.Start); + } + }; + Scanner.prototype.scanFraction = function () { + return this.scanDecimalNumber(NumberScanState.InFraction); + }; + Scanner.prototype.newLine = function () { + this.col = 0; + if(this.mode == LexMode.File) { + this.line++; + this.lineMap[this.line] = this.pos + 1; + } + }; + Scanner.prototype.finishMultilineComment = function () { + var ch2; + this.lexState = LexState.InMultilineComment; + while(this.pos < this.len) { + if(this.ch == TypeScript.LexCodeMUL) { + ch2 = this.peekCharAt(this.pos + 1); + if(ch2 == TypeScript.LexCodeSLH) { + this.advanceChar(2); + if(this.mode == LexMode.File) { + this.tokenStart(); + } + this.lexState = LexState.Start; + return true; + } + } else { + if(this.ch == TypeScript.LexCodeNWL) { + this.newLine(); + if(this.mode == LexMode.Line) { + this.nextChar(); + return false; + } + } else { + if(this.ch >= TypeScript.LexCodeASCIIChars) { + this.seenUnicodeCharInComment = true; + } + } + } + this.nextChar(); + } + return false; + }; + Scanner.prototype.pushComment = function (comment) { + this.commentStack.push(comment); + }; + Scanner.prototype.getComments = function () { + var stack = this.commentStack; + this.commentStack = []; + return stack; + }; + Scanner.prototype.getCommentsForLine = function (line) { + var comments = null; + while((this.commentStack.length > 0) && (this.commentStack[0].line == line)) { + if(comments == null) { + comments = [ + this.commentStack.shift() + ]; + } else { + comments = comments.concat([ + this.commentStack.shift() + ]); + } + } + return comments; + }; + Scanner.prototype.resetComments = function () { + this.commentStack = []; + }; + Scanner.prototype.endsLine = function (c) { + return (c == TypeScript.LexCodeNWL) || (c == TypeScript.LexCodeRET) || (c == TypeScript.LexCodeLS) || (c == TypeScript.LexCodePS); + }; + Scanner.prototype.finishSinglelineComment = function () { + while(this.pos < this.len) { + if(this.endsLine(this.ch)) { + break; + } + if(this.ch >= TypeScript.LexCodeASCIIChars) { + this.seenUnicodeCharInComment = true; + } + this.nextChar(); + } + if(this.mode == LexMode.File) { + this.tokenStart(); + } + }; + Scanner.prototype.tokenText = function () { + return this.src.substring(this.startPos, this.pos); + }; + Scanner.prototype.findClosingSLH = function () { + var index = this.pos; + var ch2 = this.src.charCodeAt(index); + var prevCh = 0; + var liveEsc = false; + while(!this.endsLine(ch2) && (index < this.len)) { + if((ch2 == TypeScript.LexCodeSLH) && (!liveEsc)) { + return index; + } + prevCh = ch2; + index++; + if(liveEsc) { + liveEsc = false; + } else { + liveEsc = (prevCh == TypeScript.LexCodeBSL); + } + ch2 = this.src.charCodeAt(index); + } + return -1; + }; + Scanner.prototype.speculateRegex = function () { + if(TypeScript.noRegexTable[this.prevTok.tokenId] != undefined) { + return null; + } + var svPos = this.pos; + var svCol = this.col; + var index = this.findClosingSLH(); + if(index > 0) { + var pattern = this.src.substring(svPos, index); + var flags = ""; + this.pos = index + 1; + this.ch = this.peekChar(); + var flagsStart = this.pos; + while((this.ch == TypeScript.LexCode_i) || (this.ch == TypeScript.LexCode_g) || (this.ch == TypeScript.LexCode_m)) { + this.nextChar(); + } + if((this.pos - flagsStart) > 3) { + return null; + } else { + flags = this.src.substring(flagsStart, this.pos); + } + var regex = undefined; + try { + regex = new RegExp(pattern, flags); + } catch (regexException) { + } + if(regex) { + this.col = svCol + (this.pos - this.startPos); + return new TypeScript.RegularExpressionLiteralToken(regex); + } + } + this.pos = svPos; + this.col = svCol; + return null; + }; + Scanner.prototype.lastTokenHadNewline = function () { + return this.prevLine != this.startLine; + }; + Scanner.prototype.lastTokenLimChar = function () { + return this.interveningWhitespace ? this.interveningWhitespacePos : this.startPos; + }; + Scanner.prototype.advanceChar = function (amt) { + this.pos += amt; + this.col += amt; + this.ch = this.peekChar(); + }; + Scanner.prototype.nextChar = function () { + this.pos++; + this.col++; + this.ch = this.peekChar(); + }; + Scanner.prototype.getLookAheadToken = function () { + var prevLine = this.prevLine; + var line = this.line; + var col = this.col; + var pos = this.pos; + var startPos = this.startPos; + var startCol = this.startCol; + var startLine = this.startLine; + var ch = this.ch; + var prevTok = this.prevTok; + var lexState = this.lexState; + var interveningWhitespace = this.interveningWhitespace; + var interveningWhitespacePos = this.interveningWhitespacePos; + var leftCurlyCount = this.leftCurlyCount; + var rightCurlyCount = this.rightCurlyCount; + var seenUnicodeChar = this.seenUnicodeChar; + var seenUnicodeCharInComment = this.seenUnicodeCharInComment; + var commentStackLength = this.commentStack.length; + var lookAheadToken = this.scan(); + this.prevLine = prevLine; + this.line = line; + this.col = col; + this.pos = pos; + this.startPos = startPos; + this.startCol = startCol; + this.startLine = startLine; + this.ch = ch; + this.prevTok = prevTok; + this.lexState = lexState; + this.interveningWhitespace = interveningWhitespace; + this.interveningWhitespacePos = interveningWhitespacePos; + this.leftCurlyCount = leftCurlyCount; + this.rightCurlyCount = rightCurlyCount; + this.seenUnicodeChar = seenUnicodeChar; + this.seenUnicodeCharInComment = seenUnicodeCharInComment; + this.commentStack.length = commentStackLength; + return lookAheadToken; + }; + Scanner.prototype.scanInLine = function () { + if((this.lexState == LexState.InMultilineComment) && (this.scanComments)) { + this.ch = this.peekChar(); + var commentLine = this.line; + this.finishMultilineComment(); + if(this.startPos < this.pos) { + var commentText = this.src.substring(this.startPos, this.pos); + this.tokenStart(); + return new TypeScript.CommentToken(TypeScript.TokenID.Comment, commentText, true, this.startPos, commentLine, true); + } else { + return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; + } + } else { + if(this.lexState == LexState.InMultilineSingleQuoteString && this.pos < this.len) { + this.ch = TypeScript.LexCodeAPO; + this.lexState = LexState.Start; + return this.scanStringConstant(); + } else { + if(this.lexState == LexState.InMultilineDoubleQuoteString && this.pos < this.len) { + this.ch = TypeScript.LexCodeQUO; + this.lexState = LexState.Start; + return this.scanStringConstant(); + } + } + } + this.prevLine = this.line; + var prevTok = this.innerScan(); + if(prevTok.tokenId != TypeScript.TokenID.Whitespace) { + this.prevTok = prevTok; + } + return prevTok; + }; + Scanner.prototype.scan = function () { + this.prevLine = this.line; + this.prevTok = this.innerScan(); + if(this.saveScan) { + this.saveScan.addToken(this.prevTok, this); + } + return this.prevTok; + }; + Scanner.prototype.isValidUnicodeIdentifierChar = function () { + var valid = LexIsUnicodeIdStart(this.ch) || LexIsUnicodeDigit(this.ch); + this.seenUnicodeChar = this.seenUnicodeChar || valid; + return valid; + }; + Scanner.prototype.scanStringConstant = function () { + var endCode = this.ch; + this.nextChar(); + scanStringConstantLoop: +for(; ; ) { + switch(this.ch) { + case TypeScript.LexEOF: { + this.reportScannerError("Unterminated string constant"); + break scanStringConstantLoop; + + } + case TypeScript.LexCodeLS: + case TypeScript.LexCodePS: { + this.seenUnicodeChar = true; + + } + case TypeScript.LexCodeRET: + case TypeScript.LexCodeNWL: { + this.reportScannerError("Unterminated string constant"); + break scanStringConstantLoop; + + } + case TypeScript.LexCodeAPO: + case TypeScript.LexCodeQUO: { + if(this.ch == endCode) { + this.nextChar(); + break scanStringConstantLoop; + } + break; + + } + case TypeScript.LexCodeBSL: { + this.nextChar(); + switch(this.ch) { + case TypeScript.LexCodeAPO: + case TypeScript.LexCodeQUO: + case TypeScript.LexCodeBSL: { + this.nextChar(); + continue scanStringConstantLoop; + + } + case TypeScript.LexCodeLS: + case TypeScript.LexCodePS: { + this.seenUnicodeChar = true; + + } + case TypeScript.LexCodeRET: + case TypeScript.LexCodeNWL: { + if(this.ch == TypeScript.LexCodeRET && this.peekCharAt(this.pos + 1) == TypeScript.LexCodeNWL) { + this.nextChar(); + } + this.nextChar(); + this.newLine(); + if(this.mode == LexMode.Line) { + this.lexState = endCode == TypeScript.LexCodeAPO ? LexState.InMultilineSingleQuoteString : LexState.InMultilineDoubleQuoteString; + break scanStringConstantLoop; + } + break; + + } + case TypeScript.LexCode_x: + case TypeScript.LexCode_u: { + var expectedHexDigits = this.ch == TypeScript.LexCode_x ? 2 : 4; + this.nextChar(); + for(var i = 0; i < expectedHexDigits; i++) { + if(this.IsHexDigit(this.ch)) { + this.nextChar(); + } else { + this.reportScannerError("Invalid Unicode escape sequence"); + break; + } + } + continue scanStringConstantLoop; + + } + } + break; + + } + } + if(this.ch >= TypeScript.LexCodeASCIIChars) { + this.seenUnicodeChar = true; + } + this.nextChar(); + } + return new TypeScript.StringLiteralToken(this.src.substring(this.startPos, this.pos)); + }; + Scanner.prototype.scanIdentifier = function () { + var hasEscape = false; + var isFirstChar = (this.ch == TypeScript.LexCodeBSL); + var hasUnicode = false; + for(; ; ) { + while(lexIdStartTable[this.ch] || LexIsDigit(this.ch) || (this.ch >= TypeScript.LexCodeASCIIChars && this.isValidUnicodeIdentifierChar())) { + this.nextChar(); + } + if(this.ch == TypeScript.LexCodeBSL) { + this.nextChar(); + if(this.ch == TypeScript.LexCode_u) { + this.nextChar(); + for(var h = 0; h < 4; h++) { + if(this.IsHexDigit(this.ch)) { + this.nextChar(); + } else { + this.reportScannerError("Invalid Unicode escape sequence"); + return TypeScript.staticTokens[TypeScript.TokenID.Error]; + } + } + var hexChar = parseInt(this.src.substring(this.pos - 4, this.pos), 16); + if(lexIdStartTable[hexChar] || (!isFirstChar && LexIsDigit(hexChar)) || (hexChar >= TypeScript.LexCodeASCIIChars && (LexIsUnicodeIdStart(hexChar) || (!isFirstChar && LexIsUnicodeDigit(hexChar))))) { + } else { + this.reportScannerError("Invalid identifier character"); + return TypeScript.staticTokens[TypeScript.TokenID.Error]; + } + hasEscape = true; + isFirstChar = false; + continue; + } + this.reportScannerError("Invalid Unicode escape sequence"); + return TypeScript.staticTokens[TypeScript.TokenID.Error]; + } + break; + } + var id; + var text = this.src.substring(this.startPos, this.pos); + if(!hasEscape && (id = TypeScript.LexKeywordTable.lookup(text)) != null) { + return TypeScript.staticTokens[id]; + } else { + return new TypeScript.IdentifierToken(text, hasEscape); + } + }; + Scanner.prototype.innerScan = function () { + var rtok; + this.tokenStart(); + this.ch = this.peekChar(); + start: +while(this.pos < this.len) { + if(lexIdStartTable[this.ch] || this.ch == TypeScript.LexCodeBSL || (this.ch >= TypeScript.LexCodeASCIIChars && LexIsUnicodeIdStart(this.ch))) { + return this.scanIdentifier(); + } else { + if(this.ch == TypeScript.LexCodeSpace) { + if(!this.interveningWhitespace) { + this.interveningWhitespacePos = this.pos; + } + do { + this.nextChar(); + }while(this.ch == TypeScript.LexCodeSpace) + if(this.mode == LexMode.Line) { + var whitespaceText = this.src.substring(this.startPos, this.pos); + return new TypeScript.WhitespaceToken(TypeScript.TokenID.Whitespace, whitespaceText); + } else { + this.tokenStart(); + this.interveningWhitespace = true; + } + } else { + if(this.ch == TypeScript.LexCodeSLH) { + this.nextChar(); + var commentText; + if(this.ch == TypeScript.LexCodeSLH) { + if(!this.interveningWhitespace) { + this.interveningWhitespacePos = this.pos - 1; + } + var commentStartPos = this.pos - 1; + var commentStartLine = this.line; + this.finishSinglelineComment(); + var commentText = this.src.substring(commentStartPos, this.pos); + var commentToken = new TypeScript.CommentToken(TypeScript.TokenID.Comment, commentText, false, commentStartPos, commentStartLine, false); + if(this.scanComments) { + this.startPos = commentStartPos; + return commentToken; + } else { + this.pushComment(commentToken); + } + this.interveningWhitespace = true; + } else { + if(this.ch == TypeScript.LexCodeMUL) { + if(!this.interveningWhitespace) { + this.interveningWhitespacePos = this.pos - 1; + } + var commentStartPos = this.pos - 1; + var commentStartLine = this.line; + this.nextChar(); + this.finishMultilineComment(); + var commentText = this.src.substring(commentStartPos, this.pos); + var endsLine = this.endsLine(this.peekChar()); + var commentToken = new TypeScript.CommentToken(TypeScript.TokenID.Comment, commentText, true, commentStartPos, commentStartLine, endsLine); + if(this.scanComments) { + this.startPos = commentStartPos; + return commentToken; + } else { + this.pushComment(commentToken); + } + this.interveningWhitespace = true; + } else { + var regexTok = this.speculateRegex(); + if(regexTok) { + return regexTok; + } else { + if(this.peekCharAt(this.pos) == TypeScript.LexCodeEQ) { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.SlashEquals]; + } else { + return TypeScript.staticTokens[TypeScript.TokenID.Slash]; + } + } + } + } + } else { + if(this.ch == TypeScript.LexCodeSMC) { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Semicolon]; + } else { + if((this.ch == TypeScript.LexCodeAPO) || (this.ch == TypeScript.LexCodeQUO)) { + return this.scanStringConstant(); + } else { + if(autoToken[this.ch]) { + var atok = autoToken[this.ch]; + if(atok.tokenId == TypeScript.TokenID.OpenBrace) { + this.leftCurlyCount++; + } else { + if(atok.tokenId == TypeScript.TokenID.CloseBrace) { + this.rightCurlyCount++; + } + } + this.nextChar(); + return atok; + } else { + if((this.ch >= TypeScript.LexCode_0) && (this.ch <= TypeScript.LexCode_9)) { + rtok = this.scanNumber(); + if(rtok) { + return rtok; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Error]; + } + } else { + switch(this.ch) { + case TypeScript.LexCodeTAB: + case TypeScript.LexCodeVTAB: { + if(!this.interveningWhitespace) { + this.interveningWhitespacePos = this.pos; + } + if(this.mode == LexMode.Line) { + do { + this.nextChar(); + }while((this.ch == TypeScript.LexCodeSpace) || (this.ch == 9)) + var wsText = this.src.substring(this.startPos, this.pos); + return new TypeScript.WhitespaceToken(TypeScript.TokenID.Whitespace, wsText); + } else { + this.interveningWhitespace = true; + } + + } + case 255: + case 254: + case 239: + case 187: + case 191: + case TypeScript.LexCodeLS: + case TypeScript.LexCodePS: + case TypeScript.LexCodeNWL: + case TypeScript.LexCodeRET: { + if(this.ch == TypeScript.LexCodeNWL) { + this.newLine(); + if(this.mode == LexMode.Line) { + return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; + } + } + if(!this.interveningWhitespace) { + this.interveningWhitespacePos = this.pos; + } + this.nextChar(); + this.tokenStart(); + this.interveningWhitespace = true; + break; + + } + case TypeScript.LexCodeDOT: { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeDOT) { + if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeDOT) { + this.advanceChar(3); + return TypeScript.staticTokens[TypeScript.TokenID.DotDotDot]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Dot]; + } + } else { + this.nextChar(); + rtok = this.scanFraction(); + if(rtok) { + return rtok; + } else { + return TypeScript.staticTokens[TypeScript.TokenID.Dot]; + } + } + } + + case TypeScript.LexCodeEQ: { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeEQ) { + this.advanceChar(3); + return TypeScript.staticTokens[TypeScript.TokenID.EqualsEqualsEquals]; + } else { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.EqualsEquals]; + } + } else { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeGT) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.EqualsGreaterThan]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Equals]; + } + } + + } + case TypeScript.LexCodeBNG: { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeEQ) { + this.advanceChar(3); + return TypeScript.staticTokens[TypeScript.TokenID.ExclamationEqualsEquals]; + } else { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.ExclamationEquals]; + } + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Exclamation]; + } + + } + case TypeScript.LexCodePLS: { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.PlusEquals]; + } else { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodePLS) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.PlusPlus]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Plus]; + } + } + + } + case TypeScript.LexCodeMIN: { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.MinusEquals]; + } else { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeMIN) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.MinusMinus]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Minus]; + } + } + + } + case TypeScript.LexCodeMUL: { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.AsteriskEquals]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Asterisk]; + } + + } + case TypeScript.LexCodePCT: { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.PercentEquals]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Percent]; + } + + } + case TypeScript.LexCodeLT: { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeLT) { + if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeEQ) { + this.advanceChar(3); + return TypeScript.staticTokens[TypeScript.TokenID.LessThanLessThanEquals]; + } else { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.LessThanLessThan]; + } + } else { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.LessThanEquals]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.LessThan]; + } + } + + } + case TypeScript.LexCodeGT: { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeGT) { + if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeEQ) { + this.advanceChar(3); + return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanGreaterThanEquals]; + } else { + if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeGT) { + if(this.peekCharAt(this.pos + 3) == TypeScript.LexCodeEQ) { + this.advanceChar(4); + return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanGreaterThanGreaterThanEquals]; + } else { + this.advanceChar(3); + return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanGreaterThanGreaterThan]; + } + } else { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanGreaterThan]; + } + } + } else { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanEquals]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.GreaterThan]; + } + } + + } + case TypeScript.LexCodeXOR: { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.CaretEquals]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Caret]; + } + + } + case TypeScript.LexCodeBAR: { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.BarEquals]; + } else { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeBAR) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.BarBar]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Bar]; + } + } + + } + case TypeScript.LexCodeAMP: { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.AmpersandEquals]; + } else { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeAMP) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.AmpersandAmpersand]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.And]; + } + } + + } + default: { + this.reportScannerError("Invalid character"); + this.nextChar(); + continue start; + + } + } + } + } + } + } + } + } + } + } + return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; + }; + Scanner.prototype.reportScannerError = function (message) { + if(this.reportError) { + this.reportError(message); + } + }; + return Scanner; + })(); + TypeScript.Scanner = Scanner; + function convertTokToIDName(tok) { + return convertTokToIDBase(tok, true, false); + } + TypeScript.convertTokToIDName = convertTokToIDName; + function convertTokToID(tok, strictMode) { + return convertTokToIDBase(tok, false, strictMode); + } + TypeScript.convertTokToID = convertTokToID; + function convertTokToIDBase(tok, identifierName, strictMode) { + if(tok.tokenId <= TypeScript.TokenID.LimKeyword) { + var tokInfo = TypeScript.lookupToken(tok.tokenId); + if(tokInfo != undefined) { + var resFlags = TypeScript.Reservation.Javascript | TypeScript.Reservation.JavascriptFuture; + if(strictMode) { + resFlags |= TypeScript.Reservation.JavascriptFutureStrict; + } + if(identifierName || !TypeScript.hasFlag(tokInfo.reservation, resFlags)) { + return true; + } + } else { + return false; + } + } else { + return false; + } + } + function getLineNumberFromPosition(lineMap, position) { + if(position === -1) { + return 0; + } + var min = 0; + var max = lineMap.length - 1; + while(min < max) { + var med = (min + max) >> 1; + if(position < lineMap[med]) { + max = med - 1; + } else { + if(position < lineMap[med + 1]) { + min = max = med; + } else { + min = med + 1; + } + } + } + return min; + } + TypeScript.getLineNumberFromPosition = getLineNumberFromPosition; + function getSourceLineColFromMap(lineCol, minChar, lineMap) { + var line = getLineNumberFromPosition(lineMap, minChar); + if(line > 0) { + lineCol.line = line; + lineCol.col = (minChar - lineMap[line]); + } + } + TypeScript.getSourceLineColFromMap = getSourceLineColFromMap; + function getLineColumnFromPosition(script, position) { + var result = { + line: -1, + col: -1 + }; + getSourceLineColFromMap(result, position, script.locationInfo.lineMap); + if(result.col >= 0) { + result.col++; + } + return result; + } + TypeScript.getLineColumnFromPosition = getLineColumnFromPosition; + function getPositionFromLineColumn(script, line, column) { + return script.locationInfo.lineMap[line] + (column - 1); + } + TypeScript.getPositionFromLineColumn = getPositionFromLineColumn; + function isPrimitiveTypeToken(token) { + switch(token.tokenId) { + case TypeScript.TokenID.Any: + case TypeScript.TokenID.Bool: + case TypeScript.TokenID.Number: + case TypeScript.TokenID.String: { + return true; + + } + } + return false; + } + TypeScript.isPrimitiveTypeToken = isPrimitiveTypeToken; + function isModifier(token) { + switch(token.tokenId) { + case TypeScript.TokenID.Public: + case TypeScript.TokenID.Private: + case TypeScript.TokenID.Static: { + return true; + + } + } + return false; + } + TypeScript.isModifier = isModifier; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var AssignScopeContext = (function () { + function AssignScopeContext(scopeChain, typeFlow, modDeclChain) { + this.scopeChain = scopeChain; + this.typeFlow = typeFlow; + this.modDeclChain = modDeclChain; + } + return AssignScopeContext; + })(); + TypeScript.AssignScopeContext = AssignScopeContext; + function pushAssignScope(scope, context, type, classType, fnc) { + var chain = new TypeScript.ScopeChain(null, context.scopeChain, scope); + chain.thisType = type; + chain.classType = classType; + chain.fnc = fnc; + context.scopeChain = chain; + } + TypeScript.pushAssignScope = pushAssignScope; + function popAssignScope(context) { + context.scopeChain = context.scopeChain.previous; + } + TypeScript.popAssignScope = popAssignScope; + function instanceCompare(a, b) { + if(((a == null) || (!a.isInstanceProperty()))) { + return b; + } else { + return a; + } + } + TypeScript.instanceCompare = instanceCompare; + function instanceFilterStop(s) { + return s.isInstanceProperty(); + } + TypeScript.instanceFilterStop = instanceFilterStop; + var ScopeSearchFilter = (function () { + function ScopeSearchFilter(select, stop) { + this.select = select; + this.stop = stop; + this.result = null; + } + ScopeSearchFilter.prototype.reset = function () { + this.result = null; + }; + ScopeSearchFilter.prototype.update = function (b) { + this.result = this.select(this.result, b); + if(this.result) { + return this.stop(this.result); + } else { + return false; + } + }; + return ScopeSearchFilter; + })(); + TypeScript.ScopeSearchFilter = ScopeSearchFilter; + TypeScript.instanceFilter = new ScopeSearchFilter(instanceCompare, instanceFilterStop); + function preAssignModuleScopes(ast, context) { + var moduleDecl = ast; + var memberScope = null; + var aggScope = null; + if(moduleDecl.name && moduleDecl.mod) { + moduleDecl.name.sym = moduleDecl.mod.symbol; + } + var mod = moduleDecl.mod; + if(!mod) { + return; + } + memberScope = new TypeScript.SymbolTableScope(mod.members, mod.ambientMembers, mod.enclosedTypes, mod.ambientEnclosedTypes, mod.symbol); + mod.memberScope = memberScope; + context.modDeclChain.push(moduleDecl); + context.typeFlow.checker.currentModDecl = moduleDecl; + aggScope = new TypeScript.SymbolAggregateScope(mod.symbol); + aggScope.addParentScope(memberScope); + aggScope.addParentScope(context.scopeChain.scope); + pushAssignScope(aggScope, context, null, null, null); + mod.containedScope = aggScope; + if(mod.symbol) { + context.typeFlow.addLocalsFromScope(mod.containedScope, mod.symbol, moduleDecl.vars, mod.members.privateMembers, true); + } + } + TypeScript.preAssignModuleScopes = preAssignModuleScopes; + function preAssignClassScopes(ast, context) { + var classDecl = ast; + var memberScope = null; + var aggScope = null; + if(classDecl.name && classDecl.type) { + classDecl.name.sym = classDecl.type.symbol; + } + var classType = ast.type; + if(classType) { + var classSym = classType.symbol; + memberScope = context.typeFlow.checker.scopeOf(classType); + aggScope = new TypeScript.SymbolAggregateScope(classType.symbol); + aggScope.addParentScope(memberScope); + aggScope.addParentScope(context.scopeChain.scope); + classType.containedScope = aggScope; + classType.memberScope = memberScope; + var instanceType = classType.instanceType; + memberScope = context.typeFlow.checker.scopeOf(instanceType); + instanceType.memberScope = memberScope; + aggScope = new TypeScript.SymbolAggregateScope(instanceType.symbol); + aggScope.addParentScope(context.scopeChain.scope); + pushAssignScope(aggScope, context, instanceType, classType, null); + instanceType.containedScope = aggScope; + } else { + ast.type = context.typeFlow.anyType; + } + } + TypeScript.preAssignClassScopes = preAssignClassScopes; + function preAssignInterfaceScopes(ast, context) { + var interfaceDecl = ast; + var memberScope = null; + var aggScope = null; + if(interfaceDecl.name && interfaceDecl.type) { + interfaceDecl.name.sym = interfaceDecl.type.symbol; + } + var interfaceType = ast.type; + memberScope = context.typeFlow.checker.scopeOf(interfaceType); + interfaceType.memberScope = memberScope; + aggScope = new TypeScript.SymbolAggregateScope(interfaceType.symbol); + aggScope.addParentScope(memberScope); + aggScope.addParentScope(context.scopeChain.scope); + pushAssignScope(aggScope, context, null, null, null); + interfaceType.containedScope = aggScope; + } + TypeScript.preAssignInterfaceScopes = preAssignInterfaceScopes; + function preAssignWithScopes(ast, context) { + var withStmt = ast; + var withType = withStmt.type; + var members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + var ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + var withType = new TypeScript.Type(); + var withSymbol = new TypeScript.WithSymbol(withStmt.minChar, context.typeFlow.checker.locationInfo.unitIndex, withType); + withType.members = members; + withType.ambientMembers = ambientMembers; + withType.symbol = withSymbol; + withType.setHasImplementation(); + withStmt.type = withType; + var withScope = new TypeScript.SymbolScopeBuilder(withType.members, withType.ambientMembers, null, null, context.scopeChain.scope, withType.symbol); + pushAssignScope(withScope, context, null, null, null); + withType.containedScope = withScope; + } + TypeScript.preAssignWithScopes = preAssignWithScopes; + function preAssignFuncDeclScopes(ast, context) { + var funcDecl = ast; + var container = null; + var localContainer = null; + if(funcDecl.type) { + localContainer = ast.type.symbol; + } + var isStatic = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static); + var isInnerStatic = isStatic && context.scopeChain.fnc != null; + var parentScope = isInnerStatic ? context.scopeChain.fnc.type.memberScope : context.scopeChain.scope; + if(context.scopeChain.thisType && (!funcDecl.isConstructor || TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod))) { + var instType = context.scopeChain.thisType; + if(!(instType.typeFlags & TypeScript.TypeFlags.IsClass) && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { + if(!funcDecl.isMethod() || isStatic) { + parentScope = instType.constructorScope; + } else { + parentScope = instType.containedScope; + } + } else { + if(context.scopeChain.previous.scope.container && context.scopeChain.previous.scope.container.declAST && context.scopeChain.previous.scope.container.declAST.nodeType == TypeScript.NodeType.FuncDecl && (context.scopeChain.previous.scope.container.declAST).isConstructor) { + parentScope = instType.constructorScope; + } else { + if(isStatic && context.scopeChain.classType) { + parentScope = context.scopeChain.classType.containedScope; + } else { + parentScope = instType.containedScope; + } + } + } + container = instType.symbol; + } else { + if(funcDecl.isConstructor && context.scopeChain.thisType) { + container = context.scopeChain.thisType.symbol; + } + } + if(funcDecl.type == null || TypeScript.hasFlag(funcDecl.type.symbol.flags, TypeScript.SymbolFlags.TypeSetDuringScopeAssignment)) { + if(context.scopeChain.fnc && context.scopeChain.fnc.type) { + container = context.scopeChain.fnc.type.symbol; + } + var funcScope = null; + var outerFnc = context.scopeChain.fnc; + var nameText = funcDecl.name ? funcDecl.name.actualText : null; + var fgSym = null; + if(isStatic) { + if(outerFnc.type.members == null && container.getType().memberScope) { + outerFnc.type.members = ((container).type.memberScope).valueMembers; + } + funcScope = context.scopeChain.fnc.type.memberScope; + outerFnc.innerStaticFuncs[outerFnc.innerStaticFuncs.length] = funcDecl; + } else { + funcScope = context.scopeChain.scope; + } + if(nameText && nameText != "__missing" && !funcDecl.isAccessor()) { + if(isStatic) { + fgSym = funcScope.findLocal(nameText, false, false); + } else { + fgSym = funcScope.findLocal(nameText, false, false); + } + } + context.typeFlow.checker.createFunctionSignature(funcDecl, container, funcScope, fgSym, fgSym == null); + if(!funcDecl.accessorSymbol && (funcDecl.fncFlags & TypeScript.FncFlags.ClassMethod) && container && ((!fgSym || fgSym.declAST.nodeType != TypeScript.NodeType.FuncDecl) && funcDecl.isAccessor()) || (fgSym && fgSym.isAccessor())) { + funcDecl.accessorSymbol = context.typeFlow.checker.createAccessorSymbol(funcDecl, fgSym, container.getType(), (funcDecl.isMethod() && isStatic), true, funcScope, container); + } + funcDecl.type.symbol.flags |= TypeScript.SymbolFlags.TypeSetDuringScopeAssignment; + } + if(funcDecl.name && funcDecl.type) { + funcDecl.name.sym = funcDecl.type.symbol; + } + funcDecl.scopeType = funcDecl.type; + if(funcDecl.isOverload) { + return; + } + var funcTable = new TypeScript.StringHashTable(); + var funcMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(funcTable, new TypeScript.StringHashTable())); + var ambientFuncTable = new TypeScript.StringHashTable(); + var ambientFuncMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(ambientFuncTable, new TypeScript.StringHashTable())); + var funcStaticTable = new TypeScript.StringHashTable(); + var funcStaticMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(funcStaticTable, new TypeScript.StringHashTable())); + var ambientFuncStaticTable = new TypeScript.StringHashTable(); + var ambientFuncStaticMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(ambientFuncStaticTable, new TypeScript.StringHashTable())); + funcDecl.unitIndex = context.typeFlow.checker.locationInfo.unitIndex; + var locals = new TypeScript.SymbolScopeBuilder(funcMembers, ambientFuncMembers, null, null, parentScope, localContainer); + var statics = new TypeScript.SymbolScopeBuilder(funcStaticMembers, ambientFuncStaticMembers, null, null, parentScope, null); + if(funcDecl.isConstructor && context.scopeChain.thisType) { + context.scopeChain.thisType.constructorScope = locals; + } + funcDecl.symbols = funcTable; + if(!funcDecl.isSpecialFn()) { + var group = funcDecl.type; + var signature = funcDecl.signature; + if(!funcDecl.isConstructor) { + group.containedScope = locals; + locals.container = group.symbol; + group.memberScope = statics; + statics.container = group.symbol; + } + funcDecl.enclosingFnc = context.scopeChain.fnc; + group.enclosingType = isStatic ? context.scopeChain.classType : context.scopeChain.thisType; + var fgSym = ast.type.symbol; + if(((funcDecl.fncFlags & TypeScript.FncFlags.Signature) == TypeScript.FncFlags.None) && funcDecl.vars) { + context.typeFlow.addLocalsFromScope(locals, fgSym, funcDecl.vars, funcTable, false); + context.typeFlow.addLocalsFromScope(statics, fgSym, funcDecl.statics, funcStaticTable, false); + } + if(signature.parameters) { + var len = signature.parameters.length; + for(var i = 0; i < len; i++) { + var paramSym = signature.parameters[i]; + context.typeFlow.checker.resolveTypeLink(locals, paramSym.parameter.typeLink, true); + } + } + context.typeFlow.checker.resolveTypeLink(locals, signature.returnType, funcDecl.isSignature()); + } + if(!funcDecl.isConstructor || TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { + var thisType = (funcDecl.isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) ? context.scopeChain.thisType : null; + pushAssignScope(locals, context, thisType, null, funcDecl); + } + if(funcDecl.name && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFunctionExpression)) { + if(funcDecl.name.sym) { + funcTable.add(funcDecl.name.actualText, funcDecl.name.sym); + } + } + } + TypeScript.preAssignFuncDeclScopes = preAssignFuncDeclScopes; + function preAssignCatchScopes(ast, context) { + var catchBlock = ast; + if(catchBlock.param) { + var catchTable = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + var catchLocals = new TypeScript.SymbolScopeBuilder(catchTable, null, null, null, context.scopeChain.scope, context.scopeChain.scope.container); + catchBlock.containedScope = catchLocals; + pushAssignScope(catchLocals, context, context.scopeChain.thisType, context.scopeChain.classType, context.scopeChain.fnc); + } + } + TypeScript.preAssignCatchScopes = preAssignCatchScopes; + function preAssignScopes(ast, parent, walker) { + var context = walker.state; + var go = true; + if(ast) { + if(ast.nodeType == TypeScript.NodeType.List) { + var list = ast; + list.enclosingScope = context.scopeChain.scope; + } else { + if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { + preAssignModuleScopes(ast, context); + } else { + if(ast.nodeType == TypeScript.NodeType.ClassDeclaration) { + preAssignClassScopes(ast, context); + } else { + if(ast.nodeType == TypeScript.NodeType.InterfaceDeclaration) { + preAssignInterfaceScopes(ast, context); + } else { + if(ast.nodeType == TypeScript.NodeType.With) { + preAssignWithScopes(ast, context); + } else { + if(ast.nodeType == TypeScript.NodeType.FuncDecl) { + preAssignFuncDeclScopes(ast, context); + } else { + if(ast.nodeType == TypeScript.NodeType.Catch) { + preAssignCatchScopes(ast, context); + } else { + if(ast.nodeType == TypeScript.NodeType.TypeRef) { + go = false; + } + } + } + } + } + } + } + } + } + walker.options.goChildren = go; + return ast; + } + TypeScript.preAssignScopes = preAssignScopes; + function postAssignScopes(ast, parent, walker) { + var context = walker.state; + var go = true; + if(ast) { + if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { + var prevModDecl = ast; + popAssignScope(context); + context.modDeclChain.pop(); + if(context.modDeclChain.length >= 1) { + context.typeFlow.checker.currentModDecl = context.modDeclChain[context.modDeclChain.length - 1]; + } + } else { + if(ast.nodeType == TypeScript.NodeType.ClassDeclaration) { + popAssignScope(context); + } else { + if(ast.nodeType == TypeScript.NodeType.InterfaceDeclaration) { + popAssignScope(context); + } else { + if(ast.nodeType == TypeScript.NodeType.With) { + popAssignScope(context); + } else { + if(ast.nodeType == TypeScript.NodeType.FuncDecl) { + var funcDecl = ast; + if((!funcDecl.isConstructor || TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) && !funcDecl.isOverload) { + popAssignScope(context); + } + } else { + if(ast.nodeType == TypeScript.NodeType.Catch) { + var catchBlock = ast; + if(catchBlock.param) { + popAssignScope(context); + } + } else { + go = false; + } + } + } + } + } + } + } + walker.options.goChildren = go; + return ast; + } + TypeScript.postAssignScopes = postAssignScopes; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var TypeCollectionContext = (function () { + function TypeCollectionContext(scopeChain, checker) { + this.scopeChain = scopeChain; + this.checker = checker; + this.script = null; + } + return TypeCollectionContext; + })(); + TypeScript.TypeCollectionContext = TypeCollectionContext; + var MemberScopeContext = (function () { + function MemberScopeContext(flow, pos, matchFlag) { + this.flow = flow; + this.pos = pos; + this.matchFlag = matchFlag; + this.type = null; + this.ast = null; + this.options = new TypeScript.AstWalkOptions(); + } + return MemberScopeContext; + })(); + TypeScript.MemberScopeContext = MemberScopeContext; + var EnclosingScopeContext = (function () { + function EnclosingScopeContext(logger, script, text, pos, isMemberCompletion) { + this.logger = logger; + this.script = script; + this.text = text; + this.pos = pos; + this.isMemberCompletion = isMemberCompletion; + this.scopeGetter = null; + this.objectLiteralScopeGetter = null; + this.scopeStartAST = null; + this.skipNextFuncDeclForClass = false; + this.deepestModuleDecl = null; + this.enclosingClassDecl = null; + this.enclosingObjectLit = null; + this.publicsOnly = true; + this.useFullAst = false; + } + EnclosingScopeContext.prototype.getScope = function () { + return this.scopeGetter(); + }; + EnclosingScopeContext.prototype.getObjectLiteralScope = function () { + return this.objectLiteralScopeGetter(); + }; + EnclosingScopeContext.prototype.getScopeAST = function () { + return this.scopeStartAST; + }; + EnclosingScopeContext.prototype.getScopePosition = function () { + return this.scopeStartAST.minChar; + }; + EnclosingScopeContext.prototype.getScriptFragmentStartAST = function () { + return this.scopeStartAST; + }; + EnclosingScopeContext.prototype.getScriptFragmentPosition = function () { + return this.getScriptFragmentStartAST().minChar; + }; + EnclosingScopeContext.prototype.getScriptFragment = function () { + if(this.scriptFragment == null) { + var ast = this.getScriptFragmentStartAST(); + var minChar = ast.minChar; + var limChar = (this.isMemberCompletion ? this.pos : this.pos + 1); + this.scriptFragment = TypeScript.quickParse(this.logger, ast, this.text, minChar, limChar, null).Script; + } + return this.scriptFragment; + }; + return EnclosingScopeContext; + })(); + TypeScript.EnclosingScopeContext = EnclosingScopeContext; + function preFindMemberScope(ast, parent, walker) { + var memScope = walker.state; + if(TypeScript.hasFlag(ast.flags, memScope.matchFlag) && ((memScope.pos < 0) || (memScope.pos == ast.limChar))) { + memScope.ast = ast; + if((ast.type == null) && (memScope.pos >= 0)) { + memScope.flow.inScopeTypeCheck(ast, memScope.scope); + } + memScope.type = ast.type; + memScope.options.stopWalk(); + } + return ast; + } + TypeScript.preFindMemberScope = preFindMemberScope; + function pushTypeCollectionScope(container, valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, context, thisType, classType, moduleDecl) { + var builder = new TypeScript.SymbolScopeBuilder(valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, null, container); + var chain = new TypeScript.ScopeChain(container, context.scopeChain, builder); + chain.thisType = thisType; + chain.classType = classType; + chain.moduleDecl = moduleDecl; + context.scopeChain = chain; + } + TypeScript.pushTypeCollectionScope = pushTypeCollectionScope; + function popTypeCollectionScope(context) { + context.scopeChain = context.scopeChain.previous; + } + TypeScript.popTypeCollectionScope = popTypeCollectionScope; + function preFindEnclosingScope(ast, parent, walker) { + var context = walker.state; + var minChar = ast.minChar; + var limChar = ast.limChar; + if(ast.nodeType == TypeScript.NodeType.Script && context.pos > limChar) { + limChar = context.pos; + } + if((minChar <= context.pos) && (limChar >= context.pos)) { + switch(ast.nodeType) { + case TypeScript.NodeType.Script: { + var script = ast; + context.scopeGetter = function () { + return script.bod === null ? null : script.bod.enclosingScope; + }; + context.scopeStartAST = script; + break; + + } + case TypeScript.NodeType.ClassDeclaration: { + context.scopeGetter = function () { + return (ast.type === null || ast.type.instanceType.containedScope === null) ? null : ast.type.instanceType.containedScope; + }; + context.scopeStartAST = ast; + context.enclosingClassDecl = ast; + break; + + } + case TypeScript.NodeType.ObjectLit: { + var objectLit = ast; + if(objectLit.targetType) { + context.scopeGetter = function () { + return objectLit.targetType.containedScope; + }; + context.objectLiteralScopeGetter = function () { + return objectLit.targetType.memberScope; + }; + context.enclosingObjectLit = objectLit; + } + break; + + } + case TypeScript.NodeType.ModuleDeclaration: { + context.deepestModuleDecl = ast; + context.scopeGetter = function () { + return ast.type === null ? null : ast.type.containedScope; + }; + context.scopeStartAST = ast; + break; + + } + case TypeScript.NodeType.InterfaceDeclaration: { + context.scopeGetter = function () { + return (ast.type === null) ? null : ast.type.containedScope; + }; + context.scopeStartAST = ast; + break; + + } + case TypeScript.NodeType.FuncDecl: { + { + var funcDecl = ast; + if(context.skipNextFuncDeclForClass) { + context.skipNextFuncDeclForClass = false; + } else { + context.scopeGetter = function () { + if(funcDecl.isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { + if(ast.type && ast.type.enclosingType) { + return ast.type.enclosingType.constructorScope; + } + } + if(funcDecl.scopeType) { + return funcDecl.scopeType.containedScope; + } + if(funcDecl.type) { + return funcDecl.type.containedScope; + } + return null; + }; + context.scopeStartAST = ast; + } + } + break; + + } + } + walker.options.goChildren = true; + } else { + walker.options.goChildren = false; + } + return ast; + } + TypeScript.preFindEnclosingScope = preFindEnclosingScope; + function findEnclosingScopeAt(logger, script, text, pos, isMemberCompletion) { + var context = new EnclosingScopeContext(logger, script, text, pos, isMemberCompletion); + TypeScript.getAstWalkerFactory().walk(script, preFindEnclosingScope, null, null, context); + if(context.scopeStartAST === null) { + return null; + } + return context; + } + TypeScript.findEnclosingScopeAt = findEnclosingScopeAt; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Signature = (function () { + function Signature() { + this.hasVariableArgList = false; + this.parameters = null; + this.declAST = null; + this.typeCheckStatus = TypeScript.TypeCheckStatus.NotStarted; + this.nonOptionalParameterCount = 0; + } + Signature.prototype.specializeType = function (pattern, replacement, checker) { + var result = new Signature(); + if(this.hasVariableArgList) { + result.hasVariableArgList = true; + } + result.returnType = new TypeScript.TypeLink(); + if(this.returnType.type) { + result.returnType.type = this.returnType.type.specializeType(pattern, replacement, checker, false); + } else { + result.returnType.type = checker.anyType; + } + if(this.parameters) { + result.parameters = []; + for(var i = 0, len = this.parameters.length; i < len; i++) { + var oldSym = this.parameters[i]; + var paramDef = new TypeScript.ValueLocation(); + var paramSym = new TypeScript.ParameterSymbol(oldSym.name, oldSym.location, checker.locationInfo.unitIndex, paramDef); + paramSym.declAST = this.declAST; + paramDef.symbol = paramSym; + paramDef.typeLink = new TypeScript.TypeLink(); + result.parameters[i] = paramSym; + var oldType = oldSym.getType(); + if(oldType) { + paramDef.typeLink.type = oldType.specializeType(pattern, replacement, checker, false); + paramSym.declAST.type = paramDef.typeLink.type; + } else { + paramDef.typeLink.type = checker.anyType; + } + } + } + result.nonOptionalParameterCount = this.nonOptionalParameterCount; + result.declAST = this.declAST; + return result; + }; + Signature.prototype.toString = function () { + return this.toStringHelper(false, false, null); + }; + Signature.prototype.toStringHelper = function (shortform, brackets, scope) { + return this.toStringHelperEx(shortform, brackets, scope).toString(); + }; + Signature.prototype.toStringHelperEx = function (shortform, brackets, scope, prefix) { + if (typeof prefix === "undefined") { prefix = ""; } + var builder = new TypeScript.MemberNameArray(); + if(brackets) { + builder.prefix = prefix + "["; + } else { + builder.prefix = prefix + "("; + } + var paramLen = this.parameters.length; + var len = this.hasVariableArgList ? paramLen - 1 : paramLen; + for(var i = 0; i < len; i++) { + builder.add(TypeScript.MemberName.create(this.parameters[i].name + (this.parameters[i].isOptional() ? "?" : "") + ": ")); + builder.add(this.parameters[i].getType().getScopedTypeNameEx(scope)); + if(i < paramLen - 1) { + builder.add(TypeScript.MemberName.create(", ")); + } + } + if(this.hasVariableArgList) { + builder.add(TypeScript.MemberName.create("..." + this.parameters[i].name + ": ")); + builder.add(this.parameters[i].getType().getScopedTypeNameEx(scope)); + } + if(shortform) { + if(brackets) { + builder.add(TypeScript.MemberName.create("] => ")); + } else { + builder.add(TypeScript.MemberName.create(") => ")); + } + } else { + if(brackets) { + builder.add(TypeScript.MemberName.create("]: ")); + } else { + builder.add(TypeScript.MemberName.create("): ")); + } + } + if(this.returnType.type) { + builder.add(this.returnType.type.getScopedTypeNameEx(scope)); + } else { + builder.add(TypeScript.MemberName.create("any")); + } + return builder; + }; + return Signature; + })(); + TypeScript.Signature = Signature; + var SignatureGroup = (function () { + function SignatureGroup() { + this.signatures = []; + this.hasImplementation = true; + this.definitionSignature = null; + this.hasBeenTypechecked = false; + this.flags = TypeScript.SignatureFlags.None; + } + SignatureGroup.prototype.addSignature = function (signature) { + if(this.signatures == null) { + this.signatures = new Array(); + } + this.signatures[this.signatures.length] = signature; + if(signature.declAST && !signature.declAST.isOverload && !signature.declAST.isSignature() && !TypeScript.hasFlag(signature.declAST.fncFlags, TypeScript.FncFlags.Ambient) && TypeScript.hasFlag(signature.declAST.fncFlags, TypeScript.FncFlags.Definition)) { + this.definitionSignature = signature; + } + }; + SignatureGroup.prototype.toString = function () { + return this.signatures.toString(); + }; + SignatureGroup.prototype.toStrings = function (prefix, shortform, scope) { + var result = []; + var len = this.signatures.length; + if(len > 1) { + shortform = false; + } + for(var i = 0; i < len; i++) { + if(len > 1 && this.signatures[i] == this.definitionSignature) { + continue; + } + if(this.flags & TypeScript.SignatureFlags.IsIndexer) { + result.push(this.signatures[i].toStringHelperEx(shortform, true, scope)); + } else { + result.push(this.signatures[i].toStringHelperEx(shortform, false, scope, prefix)); + } + } + return result; + }; + SignatureGroup.prototype.specializeType = function (pattern, replacement, checker) { + var result = new SignatureGroup(); + if(this.signatures) { + for(var i = 0, len = this.signatures.length; i < len; i++) { + result.addSignature(this.signatures[i].specializeType(pattern, replacement, checker)); + } + } + return result; + }; + SignatureGroup.prototype.verifySignatures = function (checker) { + var len = 0; + if(this.signatures && ((len = this.signatures.length) > 0)) { + for(var i = 0; i < len; i++) { + for(var j = i + 1; j < len; j++) { + if(this.signatures[i].declAST && this.signatures[j].declAST && (!TypeScript.hasFlag(this.signatures[i].declAST.fncFlags, TypeScript.FncFlags.Definition) && !TypeScript.hasFlag(this.signatures[j].declAST.fncFlags, TypeScript.FncFlags.Definition)) && checker.signaturesAreIdentical(this.signatures[i], this.signatures[j])) { + checker.errorReporter.simpleError(this.signatures[i].declAST, (this.signatures[i].declAST && this.signatures[i].declAST.name) ? "Signature for '" + this.signatures[i].declAST.name.actualText + "' is duplicated" : "Signature is duplicated"); + } + } + if(this.definitionSignature) { + if(!checker.signatureIsAssignableToTarget(this.definitionSignature, this.signatures[i])) { + checker.errorReporter.simpleError(this.signatures[i].declAST, "Overload signature is not compatible with function definition"); + } + } + } + } + }; + SignatureGroup.prototype.typeCheck = function (checker, ast, hasConstruct) { + if(this.hasBeenTypechecked) { + return; + } + this.hasBeenTypechecked = true; + var len = 0; + if(this.signatures && ((len = this.signatures.length) > 0)) { + for(var i = 0; i < len; i++) { + if(!hasConstruct && !this.definitionSignature && this.signatures[i].declAST && this.signatures[i].declAST.isOverload && !TypeScript.hasFlag(this.signatures[i].declAST.fncFlags, TypeScript.FncFlags.Ambient)) { + checker.errorReporter.simpleError(this.signatures[i].declAST, "Overload declaration lacks definition"); + } + if(this.signatures[i].declAST && this.signatures[i].declAST.isConstructor && this.signatures[i].declAST.classDecl && this.signatures[i].declAST.classDecl.type.symbol.typeCheckStatus == TypeScript.TypeCheckStatus.NotStarted) { + checker.typeFlow.typeCheck(this.signatures[i].declAST.classDecl); + } + checker.typeFlow.typeCheck(this.signatures[i].declAST); + } + this.verifySignatures(checker); + } + }; + return SignatureGroup; + })(); + TypeScript.SignatureGroup = SignatureGroup; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (TypeCheckStatus) { + TypeCheckStatus._map = []; + TypeCheckStatus._map[0] = "NotStarted"; + TypeCheckStatus.NotStarted = 0; + TypeCheckStatus._map[1] = "Started"; + TypeCheckStatus.Started = 1; + TypeCheckStatus._map[2] = "Finished"; + TypeCheckStatus.Finished = 2; + })(TypeScript.TypeCheckStatus || (TypeScript.TypeCheckStatus = {})); + var TypeCheckStatus = TypeScript.TypeCheckStatus; + function aLexicallyEnclosesB(a, b) { + if(a.declAST && b && b.declAST && a.declAST.nodeType == TypeScript.NodeType.FuncDecl) { + return a.declAST.minChar <= b.declAST.minChar && a.declAST.limChar >= b.declAST.limChar; + } else { + return false; + } + } + TypeScript.aLexicallyEnclosesB = aLexicallyEnclosesB; + function aEnclosesB(a, b) { + while(a.container) { + if(a == b || aLexicallyEnclosesB(a.container, b)) { + return true; + } + a = a.container; + } + return false; + } + TypeScript.aEnclosesB = aEnclosesB; + var Symbol = (function () { + function Symbol(name, location, length, unitIndex) { + this.name = name; + this.location = location; + this.length = length; + this.unitIndex = unitIndex; + this.bound = false; + this.flags = TypeScript.SymbolFlags.None; + this.isObjectLitField = false; + this.declAST = null; + this.declModule = null; + this.passSymbolCreated = TypeScript.CompilerDiagnostics.analysisPass; + } + Symbol.prototype.instanceScope = function () { + return null; + }; + Symbol.prototype.isVariable = function () { + return false; + }; + Symbol.prototype.isMember = function () { + return false; + }; + Symbol.prototype.isInferenceSymbol = function () { + return false; + }; + Symbol.prototype.isWith = function () { + return false; + }; + Symbol.prototype.writeable = function () { + return false; + }; + Symbol.prototype.isType = function () { + return false; + }; + Symbol.prototype.getType = function () { + return null; + }; + Symbol.prototype.isAccessor = function () { + return false; + }; + Symbol.prototype.isInstanceProperty = function () { + return TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Property) && (!TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.ModuleMember)); + }; + Symbol.prototype.getTypeName = function (scope) { + return this.getTypeNameEx(scope).toString(); + }; + Symbol.prototype.getTypeNameEx = function (scope) { + return TypeScript.MemberName.create(this.toString()); + }; + Symbol.prototype.getOptionalNameString = function () { + return TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Optional) ? "?" : ""; + }; + Symbol.prototype.pathToRoot = function () { + var path = new Array(); + var node = this; + while(node && (node.name != TypeScript.globalId)) { + path[path.length] = node; + node = node.container; + } + return path; + }; + Symbol.prototype.findCommonAncestorPath = function (b) { + if(this.container == null) { + return new Array(); + } + var aPath = this.container.pathToRoot(); + var bPath; + if(b) { + bPath = b.pathToRoot(); + } else { + bPath = new Array(); + } + var commonNodeIndex = -1; + for(var i = 0, aLen = aPath.length; i < aLen; i++) { + var aNode = aPath[i]; + for(var j = 0, bLen = bPath.length; j < bLen; j++) { + var bNode = bPath[j]; + if(aNode == bNode) { + commonNodeIndex = i; + break; + } + } + if(commonNodeIndex >= 0) { + break; + } + } + if(commonNodeIndex >= 0) { + return aPath.slice(0, commonNodeIndex); + } else { + return aPath; + } + }; + Symbol.prototype.getPrettyName = function (scopeSymbol) { + return this.name; + }; + Symbol.prototype.scopeRelativeName = function (scope) { + if(scope == null) { + return this.getPrettyName(null) + this.getOptionalNameString(); + } + var lca = this.findCommonAncestorPath(scope.container); + var builder = ""; + for(var i = 0, len = lca.length; i < len; i++) { + var prettyName = lca[i].getPrettyName(i == len - 1 ? scope.container : lca[i + 1]); + builder = prettyName + "." + builder; + } + builder += this.getPrettyName(len == 0 ? scope.container : lca[0]) + this.getOptionalNameString(); + return builder; + }; + Symbol.prototype.fullName = function () { + var builder = this.name; + var ancestor = this.container; + while(ancestor && (ancestor.name != TypeScript.globalId)) { + builder = ancestor.name + "." + builder; + ancestor = ancestor.container; + } + return builder; + }; + Symbol.prototype.isExternallyVisible = function (checker) { + if(this == checker.gloMod) { + return true; + } + if(TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Private)) { + return false; + } + if(!TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Exported)) { + return this.container == checker.gloMod; + } + return this.container.isExternallyVisible(checker); + }; + Symbol.prototype.visible = function (scope, checker) { + if(checker == null || this.container == checker.gloMod) { + return true; + } + if(TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.ModuleMember)) { + if(TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Exported)) { + if(!TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Private)) { + return true; + } else { + return aEnclosesB(this, scope.container); + } + } else { + return checker && (checker.currentModDecl == this.declModule) || (checker.currentModDecl && checker.currentModDecl.mod && checker.currentModDecl.mod.symbol && this.declModule && this.declModule.mod && this.declModule.mod.symbol && aEnclosesB(checker.currentModDecl.mod.symbol, this.declModule.mod.symbol)); + } + } else { + var isFunction = this.declAST && this.declAST.nodeType == TypeScript.NodeType.FuncDecl; + var isMethod = isFunction && (this.declAST).isMethod(); + var isStaticFunction = isFunction && TypeScript.hasFlag((this.declAST).fncFlags, TypeScript.FncFlags.Static); + var isPrivateMethod = isMethod && TypeScript.hasFlag((this.declAST).fncFlags, TypeScript.FncFlags.Private); + var isAlias = this.isType() && (this).aliasLink; + if(this.isMember() || isMethod || isStaticFunction || isAlias) { + if(TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Private) || isPrivateMethod) { + if(scope.container == null && this.container != scope.container) { + return false; + } else { + return this.container == null ? true : aEnclosesB(scope.container, this.container); + } + } else { + return true; + } + } else { + if(this.container) { + return aEnclosesB(this, scope.container); + } else { + return true; + } + } + } + }; + Symbol.prototype.addRef = function (identifier) { + if(!this.refs) { + this.refs = []; + } + this.refs[this.refs.length] = identifier; + }; + Symbol.prototype.toString = function () { + if(this.name) { + return this.name; + } else { + return "_anonymous"; + } + }; + Symbol.prototype.print = function (outfile) { + outfile.Write(this.toString()); + }; + Symbol.prototype.specializeType = function (pattern, replacement, checker) { + throw new Error("please implement in derived class"); + }; + Symbol.prototype.setType = function (type) { + throw new Error("please implement in derived class"); + }; + Symbol.prototype.kind = function () { + throw new Error("please implement in derived class"); + }; + Symbol.prototype.getInterfaceDeclFromSymbol = function (checker) { + if(this.declAST != null) { + if(this.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) { + return this.declAST; + } else { + if(this.container != null && this.container != checker.gloMod && this.container.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) { + return this.container.declAST; + } + } + } + return null; + }; + Symbol.prototype.getVarDeclFromSymbol = function () { + if(this.declAST != null && this.declAST.nodeType == TypeScript.NodeType.VarDecl) { + return this.declAST; + } + return null; + }; + Symbol.prototype.getDocComments = function () { + if(this.declAST != null) { + return this.declAST.getDocComments(); + } + return []; + }; + Symbol.prototype.isStatic = function () { + return TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Static); + }; + return Symbol; + })(); + TypeScript.Symbol = Symbol; + var ValueLocation = (function () { + function ValueLocation() { } + return ValueLocation; + })(); + TypeScript.ValueLocation = ValueLocation; + var InferenceSymbol = (function (_super) { + __extends(InferenceSymbol, _super); + function InferenceSymbol(name, location, length, unitIndex) { + _super.call(this, name, location, length, unitIndex); + this.typeCheckStatus = TypeCheckStatus.NotStarted; + } + InferenceSymbol.prototype.isInferenceSymbol = function () { + return true; + }; + InferenceSymbol.prototype.transferVarFlags = function (varFlags) { + if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Ambient)) { + this.flags |= TypeScript.SymbolFlags.Ambient; + } + if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Constant)) { + this.flags |= TypeScript.SymbolFlags.Constant; + } + if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Static)) { + this.flags |= TypeScript.SymbolFlags.Static; + } + if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Property)) { + this.flags |= TypeScript.SymbolFlags.Property; + } + if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Private)) { + this.flags |= TypeScript.SymbolFlags.Private; + } + if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Public)) { + this.flags |= TypeScript.SymbolFlags.Public; + } + if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Readonly)) { + this.flags |= TypeScript.SymbolFlags.Readonly; + } + if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Exported)) { + this.flags |= TypeScript.SymbolFlags.Exported; + } + }; + return InferenceSymbol; + })(Symbol); + TypeScript.InferenceSymbol = InferenceSymbol; + var TypeSymbol = (function (_super) { + __extends(TypeSymbol, _super); + function TypeSymbol(locName, location, length, unitIndex, type) { + _super.call(this, locName, location, length, unitIndex); + this.type = type; + this.expansions = []; + this.expansionsDeclAST = []; + this.isDynamic = false; + this.isMethod = false; + this.aliasLink = null; + this.onlyReferencedAsTypeRef = TypeScript.optimizeModuleCodeGen; + this.prettyName = this.name; + } + TypeSymbol.prototype.addLocation = function (loc) { + if(this.additionalLocations == null) { + this.additionalLocations = []; + } + this.additionalLocations[this.additionalLocations.length] = loc; + }; + TypeSymbol.prototype.kind = function () { + return TypeScript.SymbolKind.Type; + }; + TypeSymbol.prototype.isType = function () { + return true; + }; + TypeSymbol.prototype.getType = function () { + return this.type; + }; + TypeSymbol.prototype.getTypeNameEx = function (scope) { + return this.type.getMemberTypeNameEx(this.name ? this.name + this.getOptionalNameString() : "", false, false, scope); + }; + TypeSymbol.prototype.instanceScope = function () { + if(!(this.type.typeFlags & TypeScript.TypeFlags.IsClass) && this.type.isClass()) { + return this.type.instanceType.constructorScope; + } else { + return this.type.containedScope; + } + }; + TypeSymbol.prototype.toString = function () { + var result = this.type.getTypeName(); + if(this.name) { + result = this.name + ":" + result; + } + return result; + }; + TypeSymbol.prototype.isClass = function () { + return this.instanceType != null; + }; + TypeSymbol.prototype.isFunction = function () { + return this.declAST != null && this.declAST.nodeType == TypeScript.NodeType.FuncDecl; + }; + TypeSymbol.prototype.specializeType = function (pattern, replacement, checker) { + if(this.type == pattern) { + return replacement.symbol; + } else { + var replType = this.type.specializeType(pattern, replacement, checker, false); + if(replType != this.type) { + var result = new TypeSymbol(this.name, -1, 0, -1, replType); + return result; + } else { + return this; + } + } + }; + TypeSymbol.prototype.getPrettyName = function (scopeSymbol) { + if(!!scopeSymbol && TypeScript.isQuoted(this.prettyName) && this.type.isModuleType()) { + var symbolPath = scopeSymbol.pathToRoot(); + var prettyName = this.getPrettyNameOfDynamicModule(symbolPath); + if(prettyName != null) { + return prettyName.name; + } + } + return this.prettyName; + }; + TypeSymbol.prototype.getPrettyNameOfDynamicModule = function (scopeSymbolPath) { + var scopeSymbolPathLength = scopeSymbolPath.length; + var externalSymbol = null; + if(scopeSymbolPath.length > 0 && scopeSymbolPath[scopeSymbolPathLength - 1].getType().isModuleType() && (scopeSymbolPath[scopeSymbolPathLength - 1]).isDynamic) { + if(scopeSymbolPathLength > 1 && scopeSymbolPath[scopeSymbolPathLength - 2].getType().isModuleType() && (scopeSymbolPath[scopeSymbolPathLength - 2]).isDynamic) { + var moduleType = scopeSymbolPath[scopeSymbolPathLength - 2].getType(); + externalSymbol = moduleType.findDynamicModuleName(this.type); + } + if(externalSymbol == null) { + var moduleType = scopeSymbolPath[scopeSymbolPathLength - 1].getType(); + externalSymbol = moduleType.findDynamicModuleName(this.type); + } + } + return externalSymbol; + }; + TypeSymbol.prototype.getDocComments = function () { + var comments = []; + if(this.declAST != null) { + comments = comments.concat(this.declAST.getDocComments()); + } + for(var i = 0; i < this.expansionsDeclAST.length; i++) { + comments = comments.concat(this.expansionsDeclAST[i].getDocComments()); + } + return comments; + }; + return TypeSymbol; + })(InferenceSymbol); + TypeScript.TypeSymbol = TypeSymbol; + var WithSymbol = (function (_super) { + __extends(WithSymbol, _super); + function WithSymbol(location, unitIndex, withType) { + _super.call(this, "with", location, 4, unitIndex, withType); + } + WithSymbol.prototype.isWith = function () { + return true; + }; + return WithSymbol; + })(TypeSymbol); + TypeScript.WithSymbol = WithSymbol; + var FieldSymbol = (function (_super) { + __extends(FieldSymbol, _super); + function FieldSymbol(name, location, unitIndex, canWrite, field) { + _super.call(this, name, location, name.length, unitIndex); + this.canWrite = canWrite; + this.field = field; + this.getter = null; + this.setter = null; + this.hasBeenEmitted = false; + this.name = name; + this.location = location; + } + FieldSymbol.prototype.kind = function () { + return TypeScript.SymbolKind.Field; + }; + FieldSymbol.prototype.writeable = function () { + return this.isAccessor() ? this.setter != null : this.canWrite; + }; + FieldSymbol.prototype.getType = function () { + return this.field.typeLink.type; + }; + FieldSymbol.prototype.getTypeNameEx = function (scope) { + return TypeScript.MemberName.create(this.field.typeLink.type.getScopedTypeNameEx(scope), this.name + this.getOptionalNameString() + ": ", ""); + }; + FieldSymbol.prototype.isMember = function () { + return true; + }; + FieldSymbol.prototype.setType = function (type) { + this.field.typeLink.type = type; + }; + FieldSymbol.prototype.isAccessor = function () { + return this.getter != null || this.setter != null; + }; + FieldSymbol.prototype.isVariable = function () { + return true; + }; + FieldSymbol.prototype.toString = function () { + return this.getTypeNameEx(null).toString(); + }; + FieldSymbol.prototype.specializeType = function (pattern, replacement, checker) { + var rType = this.field.typeLink.type.specializeType(pattern, replacement, checker, false); + if(rType != this.field.typeLink.type) { + var fieldDef = new ValueLocation(); + var result = new FieldSymbol(this.name, 0, checker.locationInfo.unitIndex, this.canWrite, fieldDef); + result.flags = this.flags; + fieldDef.symbol = result; + fieldDef.typeLink = new TypeScript.TypeLink(); + result.setType(rType); + result.typeCheckStatus = TypeCheckStatus.Finished; + return result; + } else { + return this; + } + }; + FieldSymbol.prototype.getDocComments = function () { + if(this.getter != null || this.setter != null) { + var comments = []; + if(this.getter != null) { + comments = comments.concat(this.getter.getDocComments()); + } + if(this.setter != null) { + comments = comments.concat(this.setter.getDocComments()); + } + return comments; + } else { + if(this.declAST != null) { + return this.declAST.getDocComments(); + } + } + return []; + }; + return FieldSymbol; + })(InferenceSymbol); + TypeScript.FieldSymbol = FieldSymbol; + var ParameterSymbol = (function (_super) { + __extends(ParameterSymbol, _super); + function ParameterSymbol(name, location, unitIndex, parameter) { + _super.call(this, name, location, name.length, unitIndex); + this.parameter = parameter; + this.paramDocComment = null; + this.funcDecl = null; + this.argsOffset = (-1); + this.name = name; + this.location = location; + } + ParameterSymbol.prototype.kind = function () { + return TypeScript.SymbolKind.Parameter; + }; + ParameterSymbol.prototype.writeable = function () { + return true; + }; + ParameterSymbol.prototype.getType = function () { + return this.parameter.typeLink.type; + }; + ParameterSymbol.prototype.setType = function (type) { + this.parameter.typeLink.type = type; + }; + ParameterSymbol.prototype.isVariable = function () { + return true; + }; + ParameterSymbol.prototype.isOptional = function () { + if(this.parameter && this.parameter.symbol && this.parameter.symbol.declAST) { + return (this.parameter.symbol.declAST).isOptional; + } else { + return false; + } + }; + ParameterSymbol.prototype.getTypeNameEx = function (scope) { + return TypeScript.MemberName.create(this.getType().getScopedTypeNameEx(scope), this.name + (this.isOptional() ? "?" : "") + ": ", ""); + }; + ParameterSymbol.prototype.toString = function () { + return this.getTypeNameEx(null).toString(); + }; + ParameterSymbol.prototype.specializeType = function (pattern, replacement, checker) { + var rType = this.parameter.typeLink.type.specializeType(pattern, replacement, checker, false); + if(this.parameter.typeLink.type != rType) { + var paramDef = new ValueLocation(); + var result = new ParameterSymbol(this.name, 0, checker.locationInfo.unitIndex, paramDef); + paramDef.symbol = result; + result.setType(rType); + return result; + } else { + return this; + } + }; + ParameterSymbol.prototype.getParameterDocComments = function () { + if(!this.paramDocComment) { + var parameterComments = []; + if(this.funcDecl) { + var fncDocComments = this.funcDecl.getDocComments(); + var paramComment = TypeScript.Comment.getParameterDocCommentText(this.name, fncDocComments); + if(paramComment != "") { + parameterComments.push(paramComment); + } + } + var docComments = TypeScript.Comment.getDocCommentText(this.getDocComments()); + if(docComments != "") { + parameterComments.push(docComments); + } + this.paramDocComment = parameterComments.join("\n"); + } + return this.paramDocComment; + }; + return ParameterSymbol; + })(InferenceSymbol); + TypeScript.ParameterSymbol = ParameterSymbol; + var VariableSymbol = (function (_super) { + __extends(VariableSymbol, _super); + function VariableSymbol(name, location, unitIndex, variable) { + _super.call(this, name, location, name.length, unitIndex); + this.variable = variable; + } + VariableSymbol.prototype.kind = function () { + return TypeScript.SymbolKind.Variable; + }; + VariableSymbol.prototype.writeable = function () { + return true; + }; + VariableSymbol.prototype.getType = function () { + return this.variable.typeLink.type; + }; + VariableSymbol.prototype.getTypeNameEx = function (scope) { + return TypeScript.MemberName.create(this.getType().getScopedTypeNameEx(scope), this.name + ": ", ""); + }; + VariableSymbol.prototype.setType = function (type) { + this.variable.typeLink.type = type; + }; + VariableSymbol.prototype.isVariable = function () { + return true; + }; + return VariableSymbol; + })(InferenceSymbol); + TypeScript.VariableSymbol = VariableSymbol; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ScopedMembers = (function () { + function ScopedMembers(dualMembers) { + this.dualMembers = dualMembers; + this.allMembers = this.dualMembers; + this.publicMembers = this.dualMembers.primaryTable; + this.privateMembers = this.dualMembers.secondaryTable; + } + ScopedMembers.prototype.addPublicMember = function (key, data) { + return this.dualMembers.primaryTable.add(key, data); + }; + ScopedMembers.prototype.addPrivateMember = function (key, data) { + return this.dualMembers.secondaryTable.add(key, data); + }; + return ScopedMembers; + })(); + TypeScript.ScopedMembers = ScopedMembers; + (function (SymbolKind) { + SymbolKind._map = []; + SymbolKind._map[0] = "None"; + SymbolKind.None = 0; + SymbolKind._map[1] = "Type"; + SymbolKind.Type = 1; + SymbolKind._map[2] = "Field"; + SymbolKind.Field = 2; + SymbolKind._map[3] = "Parameter"; + SymbolKind.Parameter = 3; + SymbolKind._map[4] = "Variable"; + SymbolKind.Variable = 4; + })(TypeScript.SymbolKind || (TypeScript.SymbolKind = {})); + var SymbolKind = TypeScript.SymbolKind; + var SymbolScope = (function () { + function SymbolScope(container) { + this.container = container; + } + SymbolScope.prototype.printLabel = function () { + return "base"; + }; + SymbolScope.prototype.getAllSymbolNames = function (members) { + return [ + "please", + "implement", + "in", + "derived", + "classes" + ]; + }; + SymbolScope.prototype.getAllTypeSymbolNames = function (members) { + return [ + "please", + "implement", + "in", + "derived", + "classes" + ]; + }; + SymbolScope.prototype.getAllValueSymbolNames = function (members) { + return [ + "please", + "implement", + "in", + "derived", + "classes" + ]; + }; + SymbolScope.prototype.search = function (filter, name, publicOnly, typespace) { + return null; + }; + SymbolScope.prototype.findLocal = function (name, publicOnly, typespace) { + return null; + }; + SymbolScope.prototype.find = function (name, publicOnly, typespace) { + return null; + }; + SymbolScope.prototype.findImplementation = function (name, publicOnly, typespace) { + return null; + }; + SymbolScope.prototype.findAmbient = function (name, publicOnly, typespace) { + return null; + }; + SymbolScope.prototype.print = function (outfile) { + if(this.container) { + outfile.WriteLine(this.printLabel() + " scope with container: " + this.container.name + "..."); + } else { + outfile.WriteLine(this.printLabel() + " scope..."); + } + }; + SymbolScope.prototype.enter = function (container, ast, symbol, errorReporter, publicOnly, typespace, ambient) { + throw new Error("please implement in derived class"); + }; + SymbolScope.prototype.getTable = function () { + throw new Error("please implement in derived class"); + }; + return SymbolScope; + })(); + TypeScript.SymbolScope = SymbolScope; + function symbolCanBeUsed(sym, publicOnly) { + return publicOnly ? !(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Private) || (sym.declAST && sym.declAST.nodeType == TypeScript.NodeType.FuncDecl && TypeScript.hasFlag((sym.declAST).fncFlags, TypeScript.FncFlags.Private))) : true; + } + var SymbolAggregateScope = (function (_super) { + __extends(SymbolAggregateScope, _super); + function SymbolAggregateScope(container) { + _super.call(this, container); + this.valueCache = null; + this.valueImplCache = null; + this.valueAmbientCache = null; + this.typeCache = null; + this.typeImplCache = null; + this.typeAmbientCache = null; + this.parents = null; + this.container = container; + } + SymbolAggregateScope.prototype.printLabel = function () { + return "agg"; + }; + SymbolAggregateScope.prototype.search = function (filter, name, publicOnly, typespace) { + if(this.parents) { + for(var i = 0; i < this.parents.length; i++) { + var sym = this.parents[i].search(filter, name, publicOnly, typespace); + if(sym) { + if(filter.update(sym)) { + return sym; + } + } + } + } + return filter.result; + }; + SymbolAggregateScope.prototype.getAllSymbolNames = function (members) { + var result = []; + if(this.parents) { + for(var i = 0; i < this.parents.length; i++) { + var parentResult = this.parents[i].getAllSymbolNames(members); + if(parentResult) { + result = result.concat(parentResult); + } + } + } + return result; + }; + SymbolAggregateScope.prototype.getAllTypeSymbolNames = function (members) { + var result = []; + if(this.parents) { + for(var i = 0; i < this.parents.length; i++) { + var parentResult = this.parents[i].getAllTypeSymbolNames(members); + if(parentResult) { + result = result.concat(parentResult); + } + } + } + return result; + }; + SymbolAggregateScope.prototype.getAllValueSymbolNames = function (members) { + var result = []; + if(this.parents) { + for(var i = 0; i < this.parents.length; i++) { + var parentResult = this.parents[i].getAllValueSymbolNames(members); + if(parentResult) { + result = result.concat(parentResult); + } + } + } + return result; + }; + SymbolAggregateScope.prototype.print = function (outfile) { + _super.prototype.print.call(this, outfile); + if(this.parents) { + for(var i = 0; i < this.parents.length; i++) { + this.parents[i].print(outfile); + } + } + }; + SymbolAggregateScope.prototype.findImplementation = function (name, publicOnly, typespace) { + var sym = null; + var i = 0; + var implCache = this.valueImplCache; + if(typespace) { + implCache = this.typeImplCache; + } + if(implCache && ((sym = implCache.lookup(name)) != null) && (publicOnly ? !(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Private) || (sym.declAST && sym.declAST.nodeType == TypeScript.NodeType.FuncDecl && TypeScript.hasFlag((sym.declAST).fncFlags, TypeScript.FncFlags.Private))) : true)) { + return sym; + } + if(this.parents) { + for(i = 0; i < this.parents.length; i++) { + sym = this.parents[i].findImplementation(name, publicOnly, typespace); + if(sym) { + break; + } + } + } + if(implCache) { + if(typespace) { + this.typeImplCache = new TypeScript.StringHashTable(); + implCache = this.typeImplCache; + } else { + this.valueImplCache = new TypeScript.StringHashTable(); + implCache = this.valueImplCache; + } + } + implCache.add(name, sym); + return sym; + }; + SymbolAggregateScope.prototype.find = function (name, publicOnly, typespace) { + var sym = null; + var i = 0; + var cache = this.valueCache; + if(typespace) { + cache = this.typeCache; + } + if(cache && ((sym = cache.lookup(name)) != null) && (publicOnly ? !(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Private) || (sym.declAST && sym.declAST.nodeType == TypeScript.NodeType.FuncDecl && TypeScript.hasFlag((sym.declAST).fncFlags, TypeScript.FncFlags.Private))) : true)) { + return sym; + } + if(this.parents) { + for(i = 0; i < this.parents.length; i++) { + sym = this.parents[i].find(name, publicOnly, typespace); + if(sym) { + break; + } + } + } + if(cache == null) { + if(typespace) { + this.typeCache = new TypeScript.StringHashTable(); + cache = this.typeCache; + } else { + this.valueCache = new TypeScript.StringHashTable(); + cache = this.valueCache; + } + } + cache.add(name, sym); + return sym; + }; + SymbolAggregateScope.prototype.findAmbient = function (name, publicOnly, typespace) { + var sym = null; + var i = 0; + var cache = this.valueAmbientCache; + if(typespace) { + cache = this.typeAmbientCache; + } + if(cache && ((sym = cache.lookup(name)) != null)) { + return sym; + } + if(this.parents) { + for(i = 0; i < this.parents.length; i++) { + sym = this.parents[i].findAmbient(name, publicOnly, typespace); + if(sym) { + break; + } + } + } + if(cache == null) { + if(typespace) { + this.typeAmbientCache = new TypeScript.StringHashTable(); + cache = this.typeAmbientCache; + } else { + this.valueAmbientCache = new TypeScript.StringHashTable(); + cache = this.valueAmbientCache; + } + } + cache.add(name, sym); + return sym; + }; + SymbolAggregateScope.prototype.addParentScope = function (parent) { + if(this.parents == null) { + this.parents = new Array(); + } + this.parents[this.parents.length] = parent; + }; + return SymbolAggregateScope; + })(SymbolScope); + TypeScript.SymbolAggregateScope = SymbolAggregateScope; + var SymbolTableScope = (function (_super) { + __extends(SymbolTableScope, _super); + function SymbolTableScope(valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, container) { + _super.call(this, container); + this.valueMembers = valueMembers; + this.ambientValueMembers = ambientValueMembers; + this.enclosedTypes = enclosedTypes; + this.ambientEnclosedTypes = ambientEnclosedTypes; + this.container = container; + } + SymbolTableScope.prototype.printLabel = function () { + return "table"; + }; + SymbolTableScope.prototype.getAllSymbolNames = function (members) { + var result = this.getAllTypeSymbolNames(members); + return result.concat(this.getAllValueSymbolNames(members)); + }; + SymbolTableScope.prototype.getAllTypeSymbolNames = function (members) { + var result = []; + if(this.ambientEnclosedTypes) { + result = result.concat(this.ambientEnclosedTypes.allMembers.getAllKeys()); + } + if(this.enclosedTypes) { + result = result.concat(this.enclosedTypes.allMembers.getAllKeys()); + } + return result; + }; + SymbolTableScope.prototype.getAllValueSymbolNames = function (members) { + var result = []; + if(this.ambientValueMembers) { + result = result.concat(this.ambientValueMembers.allMembers.getAllKeys()); + } + if(this.valueMembers) { + result = result.concat(this.valueMembers.allMembers.getAllKeys()); + } + return result; + }; + SymbolTableScope.prototype.search = function (filter, name, publicOnly, typespace) { + var sym = this.find(name, publicOnly, typespace); + filter.update(sym); + return filter.result; + }; + SymbolTableScope.prototype.find = function (name, publicOnly, typespace) { + var table = null; + var ambientTable = null; + if(typespace) { + table = (this.enclosedTypes == null) ? null : publicOnly ? this.enclosedTypes.publicMembers : this.enclosedTypes.allMembers; + ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; + } else { + table = (this.valueMembers == null) ? null : publicOnly ? this.valueMembers.publicMembers : this.valueMembers.allMembers; + ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; + } + if(ambientTable) { + var s = ambientTable.lookup(name); + if(s) { + return s; + } + } + if(table) { + var s = table.lookup(name); + if(s) { + return s; + } + } + return null; + }; + SymbolTableScope.prototype.findAmbient = function (name, publicOnly, typespace) { + var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; + if(typespace) { + ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; + } + if(ambientTable) { + var s = ambientTable.lookup(name); + if(s) { + return s; + } + } + return null; + }; + SymbolTableScope.prototype.print = function (outfile) { + _super.prototype.print.call(this, outfile); + if(this.ambientValueMembers) { + this.ambientValueMembers.allMembers.map(function (key, sym, context) { + outfile.WriteLine(" " + key); + }, null); + } + if(this.valueMembers) { + this.valueMembers.allMembers.map(function (key, sym, context) { + outfile.WriteLine(" " + key); + }, null); + } + if(this.ambientEnclosedTypes) { + this.ambientEnclosedTypes.allMembers.map(function (key, sym, context) { + outfile.WriteLine(" " + key); + }, null); + } + if(this.enclosedTypes) { + this.enclosedTypes.allMembers.map(function (key, sym, context) { + outfile.WriteLine(" " + key); + }, null); + } + }; + SymbolTableScope.prototype.findImplementation = function (name, publicOnly, typespace) { + var sym = this.find(name, publicOnly, typespace); + if(sym) { + if(sym.kind() == SymbolKind.Type) { + var typeSym = sym; + if(!typeSym.type.hasImplementation()) { + sym = null; + } + } else { + if(sym.container) { + if(sym.container.kind() == SymbolKind.Type) { + var ctypeSym = sym.container; + if(!ctypeSym.type.hasImplementation()) { + sym = null; + } + } + } + } + } + return sym; + }; + SymbolTableScope.prototype.getTable = function () { + return this.valueMembers.publicMembers; + }; + return SymbolTableScope; + })(SymbolScope); + TypeScript.SymbolTableScope = SymbolTableScope; + var SymbolScopeBuilder = (function (_super) { + __extends(SymbolScopeBuilder, _super); + function SymbolScopeBuilder(valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, parent, container) { + _super.call(this, container); + this.valueMembers = valueMembers; + this.ambientValueMembers = ambientValueMembers; + this.enclosedTypes = enclosedTypes; + this.ambientEnclosedTypes = ambientEnclosedTypes; + this.parent = parent; + this.container = container; + } + SymbolScopeBuilder.prototype.printLabel = function () { + return "builder"; + }; + SymbolScopeBuilder.prototype.getAllSymbolNames = function (members) { + var result = this.getAllTypeSymbolNames(members); + return result.concat(this.getAllValueSymbolNames(members)); + }; + SymbolScopeBuilder.prototype.getAllTypeSymbolNames = function (members) { + var result = []; + if(this.ambientEnclosedTypes) { + result = result.concat(this.ambientEnclosedTypes.allMembers.getAllKeys()); + } + if(this.enclosedTypes) { + result = result.concat(this.enclosedTypes.allMembers.getAllKeys()); + } + if(!members && this.parent) { + var parentResult = this.parent.getAllTypeSymbolNames(members); + if(parentResult) { + result = result.concat(parentResult); + } + } + return result; + }; + SymbolScopeBuilder.prototype.getAllValueSymbolNames = function (members) { + var result = []; + if(this.ambientValueMembers) { + result = result.concat(this.ambientValueMembers.allMembers.getAllKeys()); + } + if(this.valueMembers) { + result = result.concat(this.valueMembers.allMembers.getAllKeys()); + } + if(!members && this.parent) { + var parentResult = this.parent.getAllValueSymbolNames(members); + if(parentResult) { + result = result.concat(parentResult); + } + } + return result; + }; + SymbolScopeBuilder.prototype.search = function (filter, name, publicOnly, typespace) { + var sym = null; + var table = (this.valueMembers == null) ? null : publicOnly ? this.valueMembers.publicMembers : this.valueMembers.allMembers; + var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; + if(typespace) { + table = (this.enclosedTypes == null) ? null : publicOnly ? this.enclosedTypes.publicMembers : this.enclosedTypes.allMembers; + ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; + } + if(ambientTable) { + if((sym = ambientTable.lookup(name)) != null) { + if(filter.update(sym)) { + return sym; + } + } + } + if(table) { + if((sym = table.lookup(name)) != null) { + if(filter.update(sym)) { + return sym; + } + } + } + if(this.parent) { + sym = this.parent.search(filter, name, publicOnly, typespace); + if(sym) { + if(filter.update(sym)) { + return sym; + } + } + } + return filter.result; + }; + SymbolScopeBuilder.prototype.print = function (outfile) { + _super.prototype.print.call(this, outfile); + if(this.ambientValueMembers) { + this.ambientValueMembers.allMembers.map(function (key, s, context) { + var sym = s; + outfile.WriteLine(" " + key); + }, null); + } + if(this.valueMembers) { + this.valueMembers.allMembers.map(function (key, s, context) { + var sym = s; + outfile.WriteLine(" " + key); + }, null); + } + if(this.ambientEnclosedTypes) { + this.ambientEnclosedTypes.allMembers.map(function (key, s, context) { + var sym = s; + outfile.WriteLine(" " + key); + }, null); + } + if(this.enclosedTypes) { + this.enclosedTypes.allMembers.map(function (key, s, context) { + var sym = s; + outfile.WriteLine(" " + key); + }, null); + } + if(this.parent) { + this.parent.print(outfile); + } + }; + SymbolScopeBuilder.prototype.find = function (name, publicOnly, typespace) { + var sym = null; + var table = (this.valueMembers == null) ? null : publicOnly ? this.valueMembers.publicMembers : this.valueMembers.allMembers; + var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; + if(typespace) { + table = (this.enclosedTypes == null) ? null : publicOnly ? this.enclosedTypes.publicMembers : this.enclosedTypes.allMembers; + ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; + } + if(ambientTable && ((sym = ambientTable.lookup(name)) != null)) { + return sym; + } + if(table && ((sym = table.lookup(name)) != null)) { + return sym; + } + if(this.parent) { + return this.parent.find(name, publicOnly, typespace); + } + return null; + }; + SymbolScopeBuilder.prototype.findAmbient = function (name, publicOnly, typespace) { + var sym = null; + var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; + if(typespace) { + ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; + } + if(ambientTable && ((sym = ambientTable.lookup(name)) != null)) { + return sym; + } + if(this.parent) { + return this.parent.findAmbient(name, publicOnly, typespace); + } + return null; + }; + SymbolScopeBuilder.prototype.findLocal = function (name, publicOnly, typespace) { + var sym = null; + var table = (this.valueMembers == null) ? null : publicOnly ? this.valueMembers.publicMembers : this.valueMembers.allMembers; + var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; + if(typespace) { + table = (this.enclosedTypes == null) ? null : publicOnly ? this.enclosedTypes.publicMembers : this.enclosedTypes.allMembers; + ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; + } + if(table) { + if((sym = table.lookup(name)) != null) { + if(sym) { + return sym; + } + } + } + if(ambientTable) { + if((sym = ambientTable.lookup(name)) != null) { + if(sym) { + return sym; + } + } + } + return null; + }; + SymbolScopeBuilder.prototype.enter = function (container, ast, symbol, errorReporter, insertAsPublic, typespace, ambient) { + var table = null; + if(ambient) { + if(typespace) { + table = (this.ambientEnclosedTypes == null) ? null : insertAsPublic ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.privateMembers; + } else { + table = (this.ambientValueMembers == null) ? null : insertAsPublic ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.privateMembers; + } + } else { + if(typespace) { + table = (this.enclosedTypes == null) ? null : insertAsPublic ? this.enclosedTypes.publicMembers : this.enclosedTypes.privateMembers; + } else { + table = (this.valueMembers == null) ? null : insertAsPublic ? this.valueMembers.publicMembers : this.valueMembers.privateMembers; + } + } + if(table) { + if(!table.add(symbol.name, symbol)) { + errorReporter.duplicateIdentifier(ast, symbol.name); + } + } else { + TypeScript.CompilerDiagnostics.Alert("YYYYY"); + } + symbol.container = container; + }; + SymbolScopeBuilder.prototype.getTable = function () { + return this.valueMembers.allMembers; + }; + return SymbolScopeBuilder; + })(SymbolScope); + TypeScript.SymbolScopeBuilder = SymbolScopeBuilder; + var FilteredSymbolScope = (function (_super) { + __extends(FilteredSymbolScope, _super); + function FilteredSymbolScope(scope, container, filter) { + _super.call(this, container); + this.scope = scope; + this.filter = filter; + } + FilteredSymbolScope.prototype.print = function (outfile) { + this.scope.print(outfile); + }; + FilteredSymbolScope.prototype.find = function (name, publicOnly, typespace) { + this.filter.reset(); + return this.scope.search(this.filter, name, publicOnly, typespace); + }; + FilteredSymbolScope.prototype.findLocal = function (name, publicOnly, typespace) { + return this.scope.findLocal(name, publicOnly, typespace); + }; + return FilteredSymbolScope; + })(SymbolScope); + TypeScript.FilteredSymbolScope = FilteredSymbolScope; + var FilteredSymbolScopeBuilder = (function (_super) { + __extends(FilteredSymbolScopeBuilder, _super); + function FilteredSymbolScopeBuilder(valueMembers, parent, container, filter) { + _super.call(this, valueMembers, null, null, null, parent, container); + this.filter = filter; + } + FilteredSymbolScopeBuilder.prototype.findLocal = function (name, publicOnly, typespace) { + var sym = _super.prototype.findLocal.call(this, name, publicOnly, typespace); + if(sym) { + if(!this.filter(sym)) { + return null; + } + } + return sym; + }; + FilteredSymbolScopeBuilder.prototype.search = function (filter, name, publicOnly, typespace) { + throw new Error("please implement"); + }; + FilteredSymbolScopeBuilder.prototype.find = function (name, publicOnly, typespace) { + var sym = _super.prototype.findLocal.call(this, name, publicOnly, typespace); + if(sym) { + if(!this.filter(sym)) { + return null; + } + } + return _super.prototype.find.call(this, name, publicOnly, typespace); + }; + return FilteredSymbolScopeBuilder; + })(SymbolScopeBuilder); + TypeScript.FilteredSymbolScopeBuilder = FilteredSymbolScopeBuilder; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (TokenID) { + TokenID._map = []; + TokenID._map[0] = "Any"; + TokenID.Any = 0; + TokenID._map[1] = "Bool"; + TokenID.Bool = 1; + TokenID._map[2] = "Break"; + TokenID.Break = 2; + TokenID._map[3] = "Case"; + TokenID.Case = 3; + TokenID._map[4] = "Catch"; + TokenID.Catch = 4; + TokenID._map[5] = "Class"; + TokenID.Class = 5; + TokenID._map[6] = "Const"; + TokenID.Const = 6; + TokenID._map[7] = "Continue"; + TokenID.Continue = 7; + TokenID._map[8] = "Debugger"; + TokenID.Debugger = 8; + TokenID._map[9] = "Default"; + TokenID.Default = 9; + TokenID._map[10] = "Delete"; + TokenID.Delete = 10; + TokenID._map[11] = "Do"; + TokenID.Do = 11; + TokenID._map[12] = "Else"; + TokenID.Else = 12; + TokenID._map[13] = "Enum"; + TokenID.Enum = 13; + TokenID._map[14] = "Export"; + TokenID.Export = 14; + TokenID._map[15] = "Extends"; + TokenID.Extends = 15; + TokenID._map[16] = "Declare"; + TokenID.Declare = 16; + TokenID._map[17] = "False"; + TokenID.False = 17; + TokenID._map[18] = "Finally"; + TokenID.Finally = 18; + TokenID._map[19] = "For"; + TokenID.For = 19; + TokenID._map[20] = "Function"; + TokenID.Function = 20; + TokenID._map[21] = "Constructor"; + TokenID.Constructor = 21; + TokenID._map[22] = "Get"; + TokenID.Get = 22; + TokenID._map[23] = "If"; + TokenID.If = 23; + TokenID._map[24] = "Implements"; + TokenID.Implements = 24; + TokenID._map[25] = "Import"; + TokenID.Import = 25; + TokenID._map[26] = "In"; + TokenID.In = 26; + TokenID._map[27] = "InstanceOf"; + TokenID.InstanceOf = 27; + TokenID._map[28] = "Interface"; + TokenID.Interface = 28; + TokenID._map[29] = "Let"; + TokenID.Let = 29; + TokenID._map[30] = "Module"; + TokenID.Module = 30; + TokenID._map[31] = "New"; + TokenID.New = 31; + TokenID._map[32] = "Number"; + TokenID.Number = 32; + TokenID._map[33] = "Null"; + TokenID.Null = 33; + TokenID._map[34] = "Package"; + TokenID.Package = 34; + TokenID._map[35] = "Private"; + TokenID.Private = 35; + TokenID._map[36] = "Protected"; + TokenID.Protected = 36; + TokenID._map[37] = "Public"; + TokenID.Public = 37; + TokenID._map[38] = "Return"; + TokenID.Return = 38; + TokenID._map[39] = "Set"; + TokenID.Set = 39; + TokenID._map[40] = "Static"; + TokenID.Static = 40; + TokenID._map[41] = "String"; + TokenID.String = 41; + TokenID._map[42] = "Super"; + TokenID.Super = 42; + TokenID._map[43] = "Switch"; + TokenID.Switch = 43; + TokenID._map[44] = "This"; + TokenID.This = 44; + TokenID._map[45] = "Throw"; + TokenID.Throw = 45; + TokenID._map[46] = "True"; + TokenID.True = 46; + TokenID._map[47] = "Try"; + TokenID.Try = 47; + TokenID._map[48] = "TypeOf"; + TokenID.TypeOf = 48; + TokenID._map[49] = "Var"; + TokenID.Var = 49; + TokenID._map[50] = "Void"; + TokenID.Void = 50; + TokenID._map[51] = "With"; + TokenID.With = 51; + TokenID._map[52] = "While"; + TokenID.While = 52; + TokenID._map[53] = "Yield"; + TokenID.Yield = 53; + TokenID._map[54] = "Semicolon"; + TokenID.Semicolon = 54; + TokenID._map[55] = "OpenParen"; + TokenID.OpenParen = 55; + TokenID._map[56] = "CloseParen"; + TokenID.CloseParen = 56; + TokenID._map[57] = "OpenBracket"; + TokenID.OpenBracket = 57; + TokenID._map[58] = "CloseBracket"; + TokenID.CloseBracket = 58; + TokenID._map[59] = "OpenBrace"; + TokenID.OpenBrace = 59; + TokenID._map[60] = "CloseBrace"; + TokenID.CloseBrace = 60; + TokenID._map[61] = "Comma"; + TokenID.Comma = 61; + TokenID._map[62] = "Equals"; + TokenID.Equals = 62; + TokenID._map[63] = "PlusEquals"; + TokenID.PlusEquals = 63; + TokenID._map[64] = "MinusEquals"; + TokenID.MinusEquals = 64; + TokenID._map[65] = "AsteriskEquals"; + TokenID.AsteriskEquals = 65; + TokenID._map[66] = "SlashEquals"; + TokenID.SlashEquals = 66; + TokenID._map[67] = "PercentEquals"; + TokenID.PercentEquals = 67; + TokenID._map[68] = "AmpersandEquals"; + TokenID.AmpersandEquals = 68; + TokenID._map[69] = "CaretEquals"; + TokenID.CaretEquals = 69; + TokenID._map[70] = "BarEquals"; + TokenID.BarEquals = 70; + TokenID._map[71] = "LessThanLessThanEquals"; + TokenID.LessThanLessThanEquals = 71; + TokenID._map[72] = "GreaterThanGreaterThanEquals"; + TokenID.GreaterThanGreaterThanEquals = 72; + TokenID._map[73] = "GreaterThanGreaterThanGreaterThanEquals"; + TokenID.GreaterThanGreaterThanGreaterThanEquals = 73; + TokenID._map[74] = "Question"; + TokenID.Question = 74; + TokenID._map[75] = "Colon"; + TokenID.Colon = 75; + TokenID._map[76] = "BarBar"; + TokenID.BarBar = 76; + TokenID._map[77] = "AmpersandAmpersand"; + TokenID.AmpersandAmpersand = 77; + TokenID._map[78] = "Bar"; + TokenID.Bar = 78; + TokenID._map[79] = "Caret"; + TokenID.Caret = 79; + TokenID._map[80] = "And"; + TokenID.And = 80; + TokenID._map[81] = "EqualsEquals"; + TokenID.EqualsEquals = 81; + TokenID._map[82] = "ExclamationEquals"; + TokenID.ExclamationEquals = 82; + TokenID._map[83] = "EqualsEqualsEquals"; + TokenID.EqualsEqualsEquals = 83; + TokenID._map[84] = "ExclamationEqualsEquals"; + TokenID.ExclamationEqualsEquals = 84; + TokenID._map[85] = "LessThan"; + TokenID.LessThan = 85; + TokenID._map[86] = "LessThanEquals"; + TokenID.LessThanEquals = 86; + TokenID._map[87] = "GreaterThan"; + TokenID.GreaterThan = 87; + TokenID._map[88] = "GreaterThanEquals"; + TokenID.GreaterThanEquals = 88; + TokenID._map[89] = "LessThanLessThan"; + TokenID.LessThanLessThan = 89; + TokenID._map[90] = "GreaterThanGreaterThan"; + TokenID.GreaterThanGreaterThan = 90; + TokenID._map[91] = "GreaterThanGreaterThanGreaterThan"; + TokenID.GreaterThanGreaterThanGreaterThan = 91; + TokenID._map[92] = "Plus"; + TokenID.Plus = 92; + TokenID._map[93] = "Minus"; + TokenID.Minus = 93; + TokenID._map[94] = "Asterisk"; + TokenID.Asterisk = 94; + TokenID._map[95] = "Slash"; + TokenID.Slash = 95; + TokenID._map[96] = "Percent"; + TokenID.Percent = 96; + TokenID._map[97] = "Tilde"; + TokenID.Tilde = 97; + TokenID._map[98] = "Exclamation"; + TokenID.Exclamation = 98; + TokenID._map[99] = "PlusPlus"; + TokenID.PlusPlus = 99; + TokenID._map[100] = "MinusMinus"; + TokenID.MinusMinus = 100; + TokenID._map[101] = "Dot"; + TokenID.Dot = 101; + TokenID._map[102] = "DotDotDot"; + TokenID.DotDotDot = 102; + TokenID._map[103] = "Error"; + TokenID.Error = 103; + TokenID._map[104] = "EndOfFile"; + TokenID.EndOfFile = 104; + TokenID._map[105] = "EqualsGreaterThan"; + TokenID.EqualsGreaterThan = 105; + TokenID._map[106] = "Identifier"; + TokenID.Identifier = 106; + TokenID._map[107] = "StringLiteral"; + TokenID.StringLiteral = 107; + TokenID._map[108] = "RegularExpressionLiteral"; + TokenID.RegularExpressionLiteral = 108; + TokenID._map[109] = "NumberLiteral"; + TokenID.NumberLiteral = 109; + TokenID._map[110] = "Whitespace"; + TokenID.Whitespace = 110; + TokenID._map[111] = "Comment"; + TokenID.Comment = 111; + TokenID._map[112] = "Lim"; + TokenID.Lim = 112; + TokenID.LimFixed = TokenID.EqualsGreaterThan; + TokenID.LimKeyword = TokenID.Yield; + })(TypeScript.TokenID || (TypeScript.TokenID = {})); + var TokenID = TypeScript.TokenID; + TypeScript.tokenTable = new Array(); + TypeScript.nodeTypeTable = new Array(); + TypeScript.nodeTypeToTokTable = new Array(); + TypeScript.noRegexTable = new Array(); + TypeScript.noRegexTable[TokenID.Identifier] = true; + TypeScript.noRegexTable[TokenID.StringLiteral] = true; + TypeScript.noRegexTable[TokenID.NumberLiteral] = true; + TypeScript.noRegexTable[TokenID.RegularExpressionLiteral] = true; + TypeScript.noRegexTable[TokenID.This] = true; + TypeScript.noRegexTable[TokenID.PlusPlus] = true; + TypeScript.noRegexTable[TokenID.MinusMinus] = true; + TypeScript.noRegexTable[TokenID.CloseParen] = true; + TypeScript.noRegexTable[TokenID.CloseBracket] = true; + TypeScript.noRegexTable[TokenID.CloseBrace] = true; + TypeScript.noRegexTable[TokenID.True] = true; + TypeScript.noRegexTable[TokenID.False] = true; + (function (OperatorPrecedence) { + OperatorPrecedence._map = []; + OperatorPrecedence._map[0] = "None"; + OperatorPrecedence.None = 0; + OperatorPrecedence._map[1] = "Comma"; + OperatorPrecedence.Comma = 1; + OperatorPrecedence._map[2] = "Assignment"; + OperatorPrecedence.Assignment = 2; + OperatorPrecedence._map[3] = "Conditional"; + OperatorPrecedence.Conditional = 3; + OperatorPrecedence._map[4] = "LogicalOr"; + OperatorPrecedence.LogicalOr = 4; + OperatorPrecedence._map[5] = "LogicalAnd"; + OperatorPrecedence.LogicalAnd = 5; + OperatorPrecedence._map[6] = "BitwiseOr"; + OperatorPrecedence.BitwiseOr = 6; + OperatorPrecedence._map[7] = "BitwiseExclusiveOr"; + OperatorPrecedence.BitwiseExclusiveOr = 7; + OperatorPrecedence._map[8] = "BitwiseAnd"; + OperatorPrecedence.BitwiseAnd = 8; + OperatorPrecedence._map[9] = "Equality"; + OperatorPrecedence.Equality = 9; + OperatorPrecedence._map[10] = "Relational"; + OperatorPrecedence.Relational = 10; + OperatorPrecedence._map[11] = "Shift"; + OperatorPrecedence.Shift = 11; + OperatorPrecedence._map[12] = "Additive"; + OperatorPrecedence.Additive = 12; + OperatorPrecedence._map[13] = "Multiplicative"; + OperatorPrecedence.Multiplicative = 13; + OperatorPrecedence._map[14] = "Unary"; + OperatorPrecedence.Unary = 14; + OperatorPrecedence._map[15] = "Lim"; + OperatorPrecedence.Lim = 15; + })(TypeScript.OperatorPrecedence || (TypeScript.OperatorPrecedence = {})); + var OperatorPrecedence = TypeScript.OperatorPrecedence; + (function (Reservation) { + Reservation._map = []; + Reservation.None = 0; + Reservation.Javascript = 1; + Reservation.JavascriptFuture = 2; + Reservation.TypeScript = 4; + Reservation.JavascriptFutureStrict = 8; + Reservation.TypeScriptAndJS = Reservation.Javascript | Reservation.TypeScript; + Reservation.TypeScriptAndJSFuture = Reservation.JavascriptFuture | Reservation.TypeScript; + Reservation.TypeScriptAndJSFutureStrict = Reservation.JavascriptFutureStrict | Reservation.TypeScript; + })(TypeScript.Reservation || (TypeScript.Reservation = {})); + var Reservation = TypeScript.Reservation; + var TokenInfo = (function () { + function TokenInfo(tokenId, reservation, binopPrecedence, binopNodeType, unopPrecedence, unopNodeType, text, ers) { + this.tokenId = tokenId; + this.reservation = reservation; + this.binopPrecedence = binopPrecedence; + this.binopNodeType = binopNodeType; + this.unopPrecedence = unopPrecedence; + this.unopNodeType = unopNodeType; + this.text = text; + this.ers = ers; + } + return TokenInfo; + })(); + TypeScript.TokenInfo = TokenInfo; + function setTokenInfo(tokenId, reservation, binopPrecedence, binopNodeType, unopPrecedence, unopNodeType, text, ers) { + if(tokenId !== undefined) { + TypeScript.tokenTable[tokenId] = new TokenInfo(tokenId, reservation, binopPrecedence, binopNodeType, unopPrecedence, unopNodeType, text, ers); + if(binopNodeType != TypeScript.NodeType.None) { + TypeScript.nodeTypeTable[binopNodeType] = text; + TypeScript.nodeTypeToTokTable[binopNodeType] = tokenId; + } + if(unopNodeType != TypeScript.NodeType.None) { + TypeScript.nodeTypeTable[unopNodeType] = text; + } + } + } + setTokenInfo(TokenID.Any, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "any", TypeScript.ErrorRecoverySet.PrimType); + setTokenInfo(TokenID.Bool, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "bool", TypeScript.ErrorRecoverySet.PrimType); + setTokenInfo(TokenID.Break, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "break", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.Case, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "case", TypeScript.ErrorRecoverySet.SCase); + setTokenInfo(TokenID.Catch, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "catch", TypeScript.ErrorRecoverySet.Catch); + setTokenInfo(TokenID.Class, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "class", TypeScript.ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.Const, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "const", TypeScript.ErrorRecoverySet.Var); + setTokenInfo(TokenID.Continue, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "continue", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.Debugger, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.Debugger, "debugger", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.Default, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "default", TypeScript.ErrorRecoverySet.SCase); + setTokenInfo(TokenID.Delete, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.Delete, "delete", TypeScript.ErrorRecoverySet.Prefix); + setTokenInfo(TokenID.Do, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "do", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.Else, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "else", TypeScript.ErrorRecoverySet.Else); + setTokenInfo(TokenID.Enum, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "enum", TypeScript.ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.Export, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "export", TypeScript.ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.Extends, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "extends", TypeScript.ErrorRecoverySet.None); + setTokenInfo(TokenID.Declare, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "declare", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.False, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "false", TypeScript.ErrorRecoverySet.RLit); + setTokenInfo(TokenID.Finally, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "finally", TypeScript.ErrorRecoverySet.Catch); + setTokenInfo(TokenID.For, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "for", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.Function, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "function", TypeScript.ErrorRecoverySet.Func); + setTokenInfo(TokenID.Constructor, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "constructor", TypeScript.ErrorRecoverySet.Func); + setTokenInfo(TokenID.Get, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "get", TypeScript.ErrorRecoverySet.Func); + setTokenInfo(TokenID.Set, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "set", TypeScript.ErrorRecoverySet.Func); + setTokenInfo(TokenID.If, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "if", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.Implements, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "implements", TypeScript.ErrorRecoverySet.None); + setTokenInfo(TokenID.Import, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "import", TypeScript.ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.In, Reservation.TypeScriptAndJS, OperatorPrecedence.Relational, TypeScript.NodeType.In, OperatorPrecedence.None, TypeScript.NodeType.None, "in", TypeScript.ErrorRecoverySet.None); + setTokenInfo(TokenID.InstanceOf, Reservation.TypeScriptAndJS, OperatorPrecedence.Relational, TypeScript.NodeType.InstOf, OperatorPrecedence.None, TypeScript.NodeType.None, "instanceof", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.Interface, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "interface", TypeScript.ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.Let, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "let", TypeScript.ErrorRecoverySet.None); + setTokenInfo(TokenID.Module, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "module", TypeScript.ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.New, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "new", TypeScript.ErrorRecoverySet.PreOp); + setTokenInfo(TokenID.Number, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "number", TypeScript.ErrorRecoverySet.PrimType); + setTokenInfo(TokenID.Null, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "null", TypeScript.ErrorRecoverySet.RLit); + setTokenInfo(TokenID.Package, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "package", TypeScript.ErrorRecoverySet.None); + setTokenInfo(TokenID.Private, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "private", TypeScript.ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.Protected, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "protected", TypeScript.ErrorRecoverySet.None); + setTokenInfo(TokenID.Public, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "public", TypeScript.ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.Return, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "return", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.Static, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "static", TypeScript.ErrorRecoverySet.None); + setTokenInfo(TokenID.String, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "string", TypeScript.ErrorRecoverySet.PrimType); + setTokenInfo(TokenID.Super, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "super", TypeScript.ErrorRecoverySet.RLit); + setTokenInfo(TokenID.Switch, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "switch", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.This, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "this", TypeScript.ErrorRecoverySet.RLit); + setTokenInfo(TokenID.Throw, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "throw", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.True, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "true", TypeScript.ErrorRecoverySet.RLit); + setTokenInfo(TokenID.Try, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "try", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.TypeOf, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.Typeof, "typeof", TypeScript.ErrorRecoverySet.Prefix); + setTokenInfo(TokenID.Var, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "var", TypeScript.ErrorRecoverySet.Var); + setTokenInfo(TokenID.Void, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.Void, "void", TypeScript.ErrorRecoverySet.Prefix); + setTokenInfo(TokenID.With, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.With, "with", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.While, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "while", TypeScript.ErrorRecoverySet.While); + setTokenInfo(TokenID.Yield, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "yield", TypeScript.ErrorRecoverySet.None); + setTokenInfo(TokenID.Identifier, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "identifier", TypeScript.ErrorRecoverySet.ID); + setTokenInfo(TokenID.NumberLiteral, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "numberLiteral", TypeScript.ErrorRecoverySet.Literal); + setTokenInfo(TokenID.RegularExpressionLiteral, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "regex", TypeScript.ErrorRecoverySet.RegExp); + setTokenInfo(TokenID.StringLiteral, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "qstring", TypeScript.ErrorRecoverySet.Literal); + setTokenInfo(TokenID.Semicolon, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, ";", TypeScript.ErrorRecoverySet.SColon); + setTokenInfo(TokenID.CloseParen, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, ")", TypeScript.ErrorRecoverySet.RParen); + setTokenInfo(TokenID.CloseBracket, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "]", TypeScript.ErrorRecoverySet.RBrack); + setTokenInfo(TokenID.OpenBrace, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "{", TypeScript.ErrorRecoverySet.LCurly); + setTokenInfo(TokenID.CloseBrace, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "}", TypeScript.ErrorRecoverySet.RCurly); + setTokenInfo(TokenID.DotDotDot, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "...", TypeScript.ErrorRecoverySet.None); + setTokenInfo(TokenID.Comma, Reservation.None, OperatorPrecedence.Comma, TypeScript.NodeType.Comma, OperatorPrecedence.None, TypeScript.NodeType.None, ",", TypeScript.ErrorRecoverySet.Comma); + setTokenInfo(TokenID.Equals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.Asg, OperatorPrecedence.None, TypeScript.NodeType.None, "=", TypeScript.ErrorRecoverySet.Asg); + setTokenInfo(TokenID.PlusEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgAdd, OperatorPrecedence.None, TypeScript.NodeType.None, "+=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.MinusEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgSub, OperatorPrecedence.None, TypeScript.NodeType.None, "-=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.AsteriskEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgMul, OperatorPrecedence.None, TypeScript.NodeType.None, "*=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.SlashEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgDiv, OperatorPrecedence.None, TypeScript.NodeType.None, "/=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.PercentEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgMod, OperatorPrecedence.None, TypeScript.NodeType.None, "%=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.AmpersandEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgAnd, OperatorPrecedence.None, TypeScript.NodeType.None, "&=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.CaretEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgXor, OperatorPrecedence.None, TypeScript.NodeType.None, "^=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.BarEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgOr, OperatorPrecedence.None, TypeScript.NodeType.None, "|=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.LessThanLessThanEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgLsh, OperatorPrecedence.None, TypeScript.NodeType.None, "<<=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.GreaterThanGreaterThanEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgRsh, OperatorPrecedence.None, TypeScript.NodeType.None, ">>=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.GreaterThanGreaterThanGreaterThanEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgRs2, OperatorPrecedence.None, TypeScript.NodeType.None, ">>>=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.Question, Reservation.None, OperatorPrecedence.Conditional, TypeScript.NodeType.ConditionalExpression, OperatorPrecedence.None, TypeScript.NodeType.None, "?", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.Colon, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, ":", TypeScript.ErrorRecoverySet.Colon); + setTokenInfo(TokenID.BarBar, Reservation.None, OperatorPrecedence.LogicalOr, TypeScript.NodeType.LogOr, OperatorPrecedence.None, TypeScript.NodeType.None, "||", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.AmpersandAmpersand, Reservation.None, OperatorPrecedence.LogicalAnd, TypeScript.NodeType.LogAnd, OperatorPrecedence.None, TypeScript.NodeType.None, "&&", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.Bar, Reservation.None, OperatorPrecedence.BitwiseOr, TypeScript.NodeType.Or, OperatorPrecedence.None, TypeScript.NodeType.None, "|", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.Caret, Reservation.None, OperatorPrecedence.BitwiseExclusiveOr, TypeScript.NodeType.Xor, OperatorPrecedence.None, TypeScript.NodeType.None, "^", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.And, Reservation.None, OperatorPrecedence.BitwiseAnd, TypeScript.NodeType.And, OperatorPrecedence.None, TypeScript.NodeType.None, "&", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.EqualsEquals, Reservation.None, OperatorPrecedence.Equality, TypeScript.NodeType.Eq, OperatorPrecedence.None, TypeScript.NodeType.None, "==", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.ExclamationEquals, Reservation.None, OperatorPrecedence.Equality, TypeScript.NodeType.Ne, OperatorPrecedence.None, TypeScript.NodeType.None, "!=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.EqualsEqualsEquals, Reservation.None, OperatorPrecedence.Equality, TypeScript.NodeType.Eqv, OperatorPrecedence.None, TypeScript.NodeType.None, "===", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.ExclamationEqualsEquals, Reservation.None, OperatorPrecedence.Equality, TypeScript.NodeType.NEqv, OperatorPrecedence.None, TypeScript.NodeType.None, "!==", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.LessThan, Reservation.None, OperatorPrecedence.Relational, TypeScript.NodeType.Lt, OperatorPrecedence.None, TypeScript.NodeType.None, "<", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.LessThanEquals, Reservation.None, OperatorPrecedence.Relational, TypeScript.NodeType.Le, OperatorPrecedence.None, TypeScript.NodeType.None, "<=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.GreaterThan, Reservation.None, OperatorPrecedence.Relational, TypeScript.NodeType.Gt, OperatorPrecedence.None, TypeScript.NodeType.None, ">", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.GreaterThanEquals, Reservation.None, OperatorPrecedence.Relational, TypeScript.NodeType.Ge, OperatorPrecedence.None, TypeScript.NodeType.None, ">=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.LessThanLessThan, Reservation.None, OperatorPrecedence.Shift, TypeScript.NodeType.Lsh, OperatorPrecedence.None, TypeScript.NodeType.None, "<<", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.GreaterThanGreaterThan, Reservation.None, OperatorPrecedence.Shift, TypeScript.NodeType.Rsh, OperatorPrecedence.None, TypeScript.NodeType.None, ">>", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.GreaterThanGreaterThanGreaterThan, Reservation.None, OperatorPrecedence.Shift, TypeScript.NodeType.Rs2, OperatorPrecedence.None, TypeScript.NodeType.None, ">>>", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.Plus, Reservation.None, OperatorPrecedence.Additive, TypeScript.NodeType.Add, OperatorPrecedence.Unary, TypeScript.NodeType.Pos, "+", TypeScript.ErrorRecoverySet.AddOp); + setTokenInfo(TokenID.Minus, Reservation.None, OperatorPrecedence.Additive, TypeScript.NodeType.Sub, OperatorPrecedence.Unary, TypeScript.NodeType.Neg, "-", TypeScript.ErrorRecoverySet.AddOp); + setTokenInfo(TokenID.Asterisk, Reservation.None, OperatorPrecedence.Multiplicative, TypeScript.NodeType.Mul, OperatorPrecedence.None, TypeScript.NodeType.None, "*", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.Slash, Reservation.None, OperatorPrecedence.Multiplicative, TypeScript.NodeType.Div, OperatorPrecedence.None, TypeScript.NodeType.None, "/", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.Percent, Reservation.None, OperatorPrecedence.Multiplicative, TypeScript.NodeType.Mod, OperatorPrecedence.None, TypeScript.NodeType.None, "%", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.Tilde, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.Not, "~", TypeScript.ErrorRecoverySet.PreOp); + setTokenInfo(TokenID.Exclamation, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.LogNot, "!", TypeScript.ErrorRecoverySet.PreOp); + setTokenInfo(TokenID.PlusPlus, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.IncPre, "++", TypeScript.ErrorRecoverySet.PreOp); + setTokenInfo(TokenID.MinusMinus, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.DecPre, "--", TypeScript.ErrorRecoverySet.PreOp); + setTokenInfo(TokenID.OpenParen, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "(", TypeScript.ErrorRecoverySet.LParen); + setTokenInfo(TokenID.OpenBracket, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "[", TypeScript.ErrorRecoverySet.LBrack); + setTokenInfo(TokenID.Dot, Reservation.None, OperatorPrecedence.Unary, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, ".", TypeScript.ErrorRecoverySet.Dot); + setTokenInfo(TokenID.EndOfFile, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "", TypeScript.ErrorRecoverySet.EOF); + setTokenInfo(TokenID.EqualsGreaterThan, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "=>", TypeScript.ErrorRecoverySet.None); + function lookupToken(tokenId) { + return TypeScript.tokenTable[tokenId]; + } + TypeScript.lookupToken = lookupToken; + (function (TokenClass) { + TokenClass._map = []; + TokenClass._map[0] = "Punctuation"; + TokenClass.Punctuation = 0; + TokenClass._map[1] = "Keyword"; + TokenClass.Keyword = 1; + TokenClass._map[2] = "Operator"; + TokenClass.Operator = 2; + TokenClass._map[3] = "Comment"; + TokenClass.Comment = 3; + TokenClass._map[4] = "Whitespace"; + TokenClass.Whitespace = 4; + TokenClass._map[5] = "Identifier"; + TokenClass.Identifier = 5; + TokenClass._map[6] = "NumberLiteral"; + TokenClass.NumberLiteral = 6; + TokenClass._map[7] = "StringLiteral"; + TokenClass.StringLiteral = 7; + TokenClass._map[8] = "RegExpLiteral"; + TokenClass.RegExpLiteral = 8; + })(TypeScript.TokenClass || (TypeScript.TokenClass = {})); + var TokenClass = TypeScript.TokenClass; + var SavedToken = (function () { + function SavedToken(tok, minChar, limChar) { + this.tok = tok; + this.minChar = minChar; + this.limChar = limChar; + } + return SavedToken; + })(); + TypeScript.SavedToken = SavedToken; + var Token = (function () { + function Token(tokenId) { + this.tokenId = tokenId; + } + Token.prototype.toString = function () { + return "token: " + this.tokenId + " " + this.getText() + " (" + (TokenID)._map[this.tokenId] + ")"; + }; + Token.prototype.print = function (line, outfile) { + outfile.WriteLine(this.toString() + ",on line" + line); + }; + Token.prototype.getText = function () { + return TypeScript.tokenTable[this.tokenId].text; + }; + Token.prototype.classification = function () { + if(this.tokenId <= TokenID.LimKeyword) { + return TokenClass.Keyword; + } else { + var tokenInfo = lookupToken(this.tokenId); + if(tokenInfo != undefined) { + if((tokenInfo.unopNodeType != TypeScript.NodeType.None) || (tokenInfo.binopNodeType != TypeScript.NodeType.None)) { + return TokenClass.Operator; + } + } + } + return TokenClass.Punctuation; + }; + return Token; + })(); + TypeScript.Token = Token; + var NumberLiteralToken = (function (_super) { + __extends(NumberLiteralToken, _super); + function NumberLiteralToken(value, hasEmptyFraction) { + _super.call(this, TokenID.NumberLiteral); + this.value = value; + this.hasEmptyFraction = hasEmptyFraction; + } + NumberLiteralToken.prototype.getText = function () { + return this.hasEmptyFraction ? this.value.toString() + ".0" : this.value.toString(); + }; + NumberLiteralToken.prototype.classification = function () { + return TokenClass.NumberLiteral; + }; + return NumberLiteralToken; + })(Token); + TypeScript.NumberLiteralToken = NumberLiteralToken; + var StringLiteralToken = (function (_super) { + __extends(StringLiteralToken, _super); + function StringLiteralToken(value) { + _super.call(this, TokenID.StringLiteral); + this.value = value; + } + StringLiteralToken.prototype.getText = function () { + return this.value; + }; + StringLiteralToken.prototype.classification = function () { + return TokenClass.StringLiteral; + }; + return StringLiteralToken; + })(Token); + TypeScript.StringLiteralToken = StringLiteralToken; + var IdentifierToken = (function (_super) { + __extends(IdentifierToken, _super); + function IdentifierToken(value, hasEscapeSequence) { + _super.call(this, TokenID.Identifier); + this.value = value; + this.hasEscapeSequence = hasEscapeSequence; + } + IdentifierToken.prototype.getText = function () { + return this.value; + }; + IdentifierToken.prototype.classification = function () { + return TokenClass.Identifier; + }; + return IdentifierToken; + })(Token); + TypeScript.IdentifierToken = IdentifierToken; + var WhitespaceToken = (function (_super) { + __extends(WhitespaceToken, _super); + function WhitespaceToken(tokenId, value) { + _super.call(this, tokenId); + this.value = value; + } + WhitespaceToken.prototype.getText = function () { + return this.value; + }; + WhitespaceToken.prototype.classification = function () { + return TokenClass.Whitespace; + }; + return WhitespaceToken; + })(Token); + TypeScript.WhitespaceToken = WhitespaceToken; + var CommentToken = (function (_super) { + __extends(CommentToken, _super); + function CommentToken(tokenID, value, isBlock, startPos, line, endsLine) { + _super.call(this, tokenID); + this.value = value; + this.isBlock = isBlock; + this.startPos = startPos; + this.line = line; + this.endsLine = endsLine; + } + CommentToken.prototype.getText = function () { + return this.value; + }; + CommentToken.prototype.classification = function () { + return TokenClass.Comment; + }; + return CommentToken; + })(Token); + TypeScript.CommentToken = CommentToken; + var RegularExpressionLiteralToken = (function (_super) { + __extends(RegularExpressionLiteralToken, _super); + function RegularExpressionLiteralToken(regex) { + _super.call(this, TokenID.RegularExpressionLiteral); + this.regex = regex; + } + RegularExpressionLiteralToken.prototype.getText = function () { + return this.regex.toString(); + }; + RegularExpressionLiteralToken.prototype.classification = function () { + return TokenClass.RegExpLiteral; + }; + return RegularExpressionLiteralToken; + })(Token); + TypeScript.RegularExpressionLiteralToken = RegularExpressionLiteralToken; + TypeScript.staticTokens = new Array(); + function initializeStaticTokens() { + for(var i = 0; i <= TokenID.LimFixed; i++) { + TypeScript.staticTokens[i] = new Token(i); + } + } + TypeScript.initializeStaticTokens = initializeStaticTokens; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ArrayCache = (function () { + function ArrayCache() { + this.arrayBase = null; + } + ArrayCache.prototype.specialize = function (arrInstType, checker) { + if(this.arrayBase == null) { + this.arrayBase = arrInstType.specializeType(checker.wildElm.type, this.arrayType.elementType, checker, true); + } + return this.arrayBase; + }; + return ArrayCache; + })(); + TypeScript.ArrayCache = ArrayCache; + var TypeComparisonInfo = (function () { + function TypeComparisonInfo() { + this.onlyCaptureFirstError = false; + this.flags = TypeScript.TypeRelationshipFlags.SuccessfulComparison; + this.message = ""; + } + TypeComparisonInfo.prototype.addMessageToFront = function (message) { + if(!this.onlyCaptureFirstError) { + this.message = this.message ? message + ":\n\t" + this.message : message; + } else { + this.setMessage(message); + } + }; + TypeComparisonInfo.prototype.setMessage = function (message) { + this.message = message; + }; + return TypeComparisonInfo; + })(); + TypeScript.TypeComparisonInfo = TypeComparisonInfo; + (function (TypeCheckCollectionMode) { + TypeCheckCollectionMode._map = []; + TypeCheckCollectionMode._map[0] = "Resident"; + TypeCheckCollectionMode.Resident = 0; + TypeCheckCollectionMode._map[1] = "Transient"; + TypeCheckCollectionMode.Transient = 1; + })(TypeScript.TypeCheckCollectionMode || (TypeScript.TypeCheckCollectionMode = {})); + var TypeCheckCollectionMode = TypeScript.TypeCheckCollectionMode; + var PersistentGlobalTypeState = (function () { + function PersistentGlobalTypeState(errorReporter) { + this.errorReporter = errorReporter; + this.importedGlobalsTable = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + this.importedGlobalsTypeTable = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + this.globals = null; + this.globalTypes = null; + this.ambientGlobals = null; + this.ambientGlobalTypes = null; + this.residentGlobalValues = new TypeScript.StringHashTable(); + this.residentGlobalTypes = new TypeScript.StringHashTable(); + this.residentGlobalAmbientValues = new TypeScript.StringHashTable(); + this.residentGlobalAmbientTypes = new TypeScript.StringHashTable(); + this.residentTypeCheck = true; + this.mod = null; + this.gloMod = null; + this.wildElm = null; + this.importedGlobals = new TypeScript.SymbolScopeBuilder(null, this.importedGlobalsTable, null, this.importedGlobalsTypeTable, null, null); + this.dualGlobalValues = new TypeScript.DualStringHashTable(this.residentGlobalValues, new TypeScript.StringHashTable()); + this.dualGlobalTypes = new TypeScript.DualStringHashTable(this.residentGlobalTypes, new TypeScript.StringHashTable()); + this.dualAmbientGlobalValues = new TypeScript.DualStringHashTable(this.residentGlobalAmbientValues, new TypeScript.StringHashTable()); + this.dualAmbientGlobalTypes = new TypeScript.DualStringHashTable(this.residentGlobalAmbientTypes, new TypeScript.StringHashTable()); + var dualGlobalScopedMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(this.dualGlobalValues, new TypeScript.StringHashTable())); + var dualGlobalScopedAmbientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(this.dualAmbientGlobalValues, new TypeScript.StringHashTable())); + var dualGlobalScopedEnclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(this.dualGlobalTypes, new TypeScript.StringHashTable())); + var dualGlobalScopedAmbientEnclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(this.dualAmbientGlobalTypes, new TypeScript.StringHashTable())); + this.globalScope = new TypeScript.SymbolScopeBuilder(dualGlobalScopedMembers, dualGlobalScopedAmbientMembers, dualGlobalScopedEnclosedTypes, dualGlobalScopedAmbientEnclosedTypes, this.importedGlobals, null); + this.voidType = this.enterPrimitive(TypeScript.Primitive.Void, "void"); + this.booleanType = this.enterPrimitive(TypeScript.Primitive.Boolean, "bool"); + this.doubleType = this.enterPrimitive(TypeScript.Primitive.Double, "number"); + this.importedGlobals.ambientEnclosedTypes.addPublicMember("number", this.doubleType.symbol); + this.stringType = this.enterPrimitive(TypeScript.Primitive.String, "string"); + this.anyType = this.enterPrimitive(TypeScript.Primitive.Any, "any"); + this.nullType = this.enterPrimitive(TypeScript.Primitive.Null, "null"); + this.undefinedType = this.enterPrimitive(TypeScript.Primitive.Undefined, "undefined"); + this.setCollectionMode(TypeCheckCollectionMode.Resident); + this.wildElm = new TypeScript.TypeSymbol("_element", -1, 0, -1, new TypeScript.Type()); + this.importedGlobalsTypeTable.addPublicMember(this.wildElm.name, this.wildElm); + this.mod = new TypeScript.ModuleType(dualGlobalScopedEnclosedTypes, dualGlobalScopedAmbientEnclosedTypes); + this.mod.members = dualGlobalScopedMembers; + this.mod.ambientMembers = dualGlobalScopedAmbientMembers; + this.mod.containedScope = this.globalScope; + this.gloMod = new TypeScript.TypeSymbol(TypeScript.globalId, -1, 0, -1, this.mod); + this.mod.members.addPublicMember(this.gloMod.name, this.gloMod); + this.defineGlobalValue("undefined", this.undefinedType); + } + PersistentGlobalTypeState.prototype.enterPrimitive = function (flags, name) { + var primitive = new TypeScript.Type(); + primitive.primitiveTypeClass = flags; + var symbol = new TypeScript.TypeSymbol(name, -1, name.length, -1, primitive); + symbol.typeCheckStatus = TypeScript.TypeCheckStatus.Finished; + primitive.symbol = symbol; + this.importedGlobals.enter(null, null, symbol, this.errorReporter, true, true, true); + return primitive; + }; + PersistentGlobalTypeState.prototype.setCollectionMode = function (mode) { + this.residentTypeCheck = this.dualGlobalValues.insertPrimary = this.dualGlobalTypes.insertPrimary = this.dualAmbientGlobalValues.insertPrimary = this.dualAmbientGlobalTypes.insertPrimary = mode == TypeCheckCollectionMode.Resident; + }; + PersistentGlobalTypeState.prototype.refreshPersistentState = function () { + this.globals = new TypeScript.StringHashTable(); + this.globalTypes = new TypeScript.StringHashTable(); + this.ambientGlobals = new TypeScript.StringHashTable(); + this.ambientGlobalTypes = new TypeScript.StringHashTable(); + this.globalTypes.add(this.voidType.symbol.name, this.voidType.symbol); + this.globalTypes.add(this.booleanType.symbol.name, this.booleanType.symbol); + this.globalTypes.add(this.doubleType.symbol.name, this.doubleType.symbol); + this.globalTypes.add("number", this.doubleType.symbol); + this.globalTypes.add(this.stringType.symbol.name, this.stringType.symbol); + this.globalTypes.add(this.anyType.symbol.name, this.anyType.symbol); + this.globalTypes.add(this.nullType.symbol.name, this.nullType.symbol); + this.globalTypes.add(this.undefinedType.symbol.name, this.undefinedType.symbol); + this.dualGlobalValues.secondaryTable = this.globals; + this.dualGlobalTypes.secondaryTable = this.globalTypes; + this.dualAmbientGlobalValues.secondaryTable = this.ambientGlobals; + this.dualAmbientGlobalTypes.secondaryTable = this.ambientGlobalTypes; + }; + PersistentGlobalTypeState.prototype.defineGlobalValue = function (name, type) { + var valueLocation = new TypeScript.ValueLocation(); + valueLocation.typeLink = new TypeScript.TypeLink(); + var sym = new TypeScript.VariableSymbol(name, 0, -1, valueLocation); + sym.setType(type); + sym.typeCheckStatus = TypeScript.TypeCheckStatus.Finished; + sym.container = this.gloMod; + this.importedGlobalsTable.addPublicMember(name, sym); + }; + return PersistentGlobalTypeState; + })(); + TypeScript.PersistentGlobalTypeState = PersistentGlobalTypeState; + var ContextualTypeContext = (function () { + function ContextualTypeContext(contextualType, provisional, contextID) { + this.contextualType = contextualType; + this.provisional = provisional; + this.contextID = contextID; + this.targetSig = null; + this.targetThis = null; + this.targetAccessorType = null; + } + return ContextualTypeContext; + })(); + TypeScript.ContextualTypeContext = ContextualTypeContext; + var ContextualTypingContextStack = (function () { + function ContextualTypingContextStack(checker) { + this.checker = checker; + this.contextStack = []; + this.hadProvisionalErrors = false; + } + ContextualTypingContextStack.contextID = TypeScript.TypeCheckStatus.Finished + 1; + ContextualTypingContextStack.prototype.pushContextualType = function (type, provisional) { + this.contextStack.push(new ContextualTypeContext(type, provisional, ContextualTypingContextStack.contextID++)); + this.checker.errorReporter.pushToErrorSink = provisional; + }; + ContextualTypingContextStack.prototype.popContextualType = function () { + var tc = this.contextStack.pop(); + this.checker.errorReporter.pushToErrorSink = this.isProvisional(); + this.hadProvisionalErrors = this.hadProvisionalErrors || (tc.provisional && (this.checker.errorReporter.getCapturedErrors().length)); + this.checker.errorReporter.freeCapturedErrors(); + return tc; + }; + ContextualTypingContextStack.prototype.getContextualType = function () { + return (!this.contextStack.length ? null : this.contextStack[this.contextStack.length - 1]); + }; + ContextualTypingContextStack.prototype.getContextID = function () { + return (!this.contextStack.length ? TypeScript.TypeCheckStatus.Finished : this.contextStack[this.contextStack.length - 1].contextID); + }; + ContextualTypingContextStack.prototype.isProvisional = function () { + return (!this.contextStack.length ? false : this.contextStack[this.contextStack.length - 1].provisional); + }; + return ContextualTypingContextStack; + })(); + TypeScript.ContextualTypingContextStack = ContextualTypingContextStack; + var TypeChecker = (function () { + function TypeChecker(persistentState) { + this.persistentState = persistentState; + this.errorReporter = null; + this.checkControlFlow = false; + this.printControlFlowGraph = false; + this.checkControlFlowUseDef = false; + this.styleSettings = null; + this.units = null; + this.anon = "_anonymous"; + this.locationInfo = null; + this.typeFlow = null; + this.currentCompareA = null; + this.currentCompareB = null; + this.currentModDecl = null; + this.inBind = false; + this.inWith = false; + this.errorsOnWith = true; + this.currentContextualTypeContext = null; + this.resolvingBases = false; + this.canCallDefinitionSignature = false; + this.assignableCache = { + }; + this.subtypeCache = { + }; + this.identicalCache = { + }; + this.provisionalStartedTypecheckObjects = []; + this.mustCaptureGlobalThis = false; + this.voidType = this.persistentState.voidType; + this.booleanType = this.persistentState.booleanType; + this.numberType = this.persistentState.doubleType; + this.stringType = this.persistentState.stringType; + this.anyType = this.persistentState.anyType; + this.nullType = this.persistentState.nullType; + this.undefinedType = this.persistentState.undefinedType; + this.globals = this.persistentState.dualGlobalValues; + this.globalTypes = this.persistentState.dualGlobalTypes; + this.ambientGlobals = this.persistentState.dualAmbientGlobalValues; + this.ambientGlobalTypes = this.persistentState.dualAmbientGlobalTypes; + this.gloModType = this.persistentState.mod; + this.gloMod = this.persistentState.gloMod; + this.wildElm = this.persistentState.wildElm; + this.globalScope = this.persistentState.globalScope; + this.typingContextStack = new ContextualTypingContextStack(this); + } + TypeChecker.prototype.setStyleOptions = function (style) { + this.styleSettings = style; + }; + TypeChecker.prototype.setContextualType = function (type, provisional) { + this.typingContextStack.pushContextualType(type, provisional); + this.currentContextualTypeContext = this.typingContextStack.getContextualType(); + }; + TypeChecker.prototype.unsetContextualType = function () { + var lastTC = this.typingContextStack.popContextualType(); + this.currentContextualTypeContext = this.typingContextStack.getContextualType(); + return lastTC; + }; + TypeChecker.prototype.hadProvisionalErrors = function () { + return this.typingContextStack.hadProvisionalErrors; + }; + TypeChecker.prototype.resetProvisionalErrors = function () { + if(!this.typingContextStack.getContextualType()) { + this.typingContextStack.hadProvisionalErrors = false; + } + }; + TypeChecker.prototype.typeCheckWithContextualType = function (contextType, provisional, condition, ast) { + if(condition) { + this.setContextualType(contextType, this.typingContextStack.isProvisional() || provisional); + } + this.typeFlow.typeCheck(ast); + if(condition) { + this.unsetContextualType(); + } + }; + TypeChecker.prototype.resetTargetType = function () { + this.currentContextualTypeContext = this.typingContextStack.getContextualType(); + }; + TypeChecker.prototype.killCurrentContextualType = function () { + this.currentContextualTypeContext = null; + this.errorReporter.pushToErrorSink = false; + }; + TypeChecker.prototype.hasTargetType = function () { + return this.currentContextualTypeContext && this.currentContextualTypeContext.contextualType; + }; + TypeChecker.prototype.getTargetTypeContext = function () { + return this.currentContextualTypeContext; + }; + TypeChecker.prototype.inProvisionalTypecheckMode = function () { + return this.typingContextStack.isProvisional(); + }; + TypeChecker.prototype.getTypeCheckFinishedStatus = function () { + if(this.inProvisionalTypecheckMode()) { + return this.typingContextStack.getContextID(); + } + return TypeScript.TypeCheckStatus.Finished; + }; + TypeChecker.prototype.typeStatusIsFinished = function (status) { + return status == TypeScript.TypeCheckStatus.Finished || (this.inProvisionalTypecheckMode() && status == this.typingContextStack.getContextID()); + }; + TypeChecker.prototype.addStartedPTO = function (pto) { + if(this.inProvisionalTypecheckMode()) { + this.provisionalStartedTypecheckObjects[this.provisionalStartedTypecheckObjects.length] = pto; + } + }; + TypeChecker.prototype.cleanStartedPTO = function () { + for(var i = 0; i < this.provisionalStartedTypecheckObjects.length; i++) { + if(this.provisionalStartedTypecheckObjects[i].typeCheckStatus >= this.typingContextStack.getContextID()) { + this.provisionalStartedTypecheckObjects[i].typeCheckStatus = TypeScript.TypeCheckStatus.NotStarted; + } + } + this.provisionalStartedTypecheckObjects = []; + }; + TypeChecker.prototype.collectTypes = function (ast) { + if(ast.nodeType == TypeScript.NodeType.Script) { + var script = ast; + this.locationInfo = script.locationInfo; + } + var globalChain = new TypeScript.ScopeChain(this.gloMod, null, this.globalScope); + var context = new TypeScript.TypeCollectionContext(globalChain, this); + TypeScript.getAstWalkerFactory().walk(ast, TypeScript.preCollectTypes, TypeScript.postCollectTypes, null, context); + }; + TypeChecker.prototype.makeArrayType = function (type) { + if(type.arrayCache == null) { + type.arrayCache = new ArrayCache(); + type.arrayCache.arrayType = new TypeScript.Type(); + type.arrayCache.arrayType.elementType = type; + type.arrayCache.arrayType.symbol = type.symbol; + } + return type.arrayCache.arrayType; + }; + TypeChecker.prototype.getParameterList = function (funcDecl, container) { + var args = funcDecl.arguments; + var parameterTable = null; + var parameterBuilder = null; + var len = args.members.length; + var nonOptionalParams = 0; + var result = []; + if(len > 0) { + parameterTable = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + parameterBuilder = new TypeScript.SymbolScopeBuilder(parameterTable, null, null, null, null, container); + for(var i = 0; i < len; i++) { + var parameter = args.members[i]; + var paramDef = new TypeScript.ValueLocation(); + var parameterSymbol = new TypeScript.ParameterSymbol(parameter.id.text, parameter.minChar, this.locationInfo.unitIndex, paramDef); + parameterSymbol.declAST = parameter; + parameterSymbol.funcDecl = funcDecl; + parameter.id.sym = parameterSymbol; + parameter.sym = parameterSymbol; + paramDef.symbol = parameterSymbol; + paramDef.typeLink = TypeScript.getTypeLink(parameter.typeExpr, this, false); + parameterBuilder.enter(null, parameter, parameterSymbol, this.errorReporter, true, false, false); + result[result.length] = parameterSymbol; + if(!parameter.isOptionalArg()) { + nonOptionalParams++; + } + } + } + return { + parameters: result, + nonOptionalParameterCount: nonOptionalParams + }; + }; + TypeChecker.prototype.createFunctionSignature = function (funcDecl, container, scope, overloadGroupSym, addToScope) { + var isExported = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Exported | TypeScript.FncFlags.ClassPropertyMethodExported) || container == this.gloMod; + var isStatic = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static); + var isPrivate = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Private); + var isDefinition = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Definition); + var isAmbient = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Ambient); + var isConstructor = funcDecl.isConstructMember() || funcDecl.isConstructor; + var isGlobal = container == this.gloMod; + var signature = new TypeScript.Signature(); + var isLambda = funcDecl.fncFlags & TypeScript.FncFlags.IsFunctionExpression; + if(funcDecl.returnTypeAnnotation || isDefinition) { + signature.returnType = TypeScript.getTypeLink(funcDecl.returnTypeAnnotation, this, false); + } else { + signature.returnType = new TypeScript.TypeLink(); + signature.returnType.type = this.anyType; + } + signature.hasVariableArgList = funcDecl.variableArgList; + var sigData = this.getParameterList(funcDecl, container); + signature.parameters = sigData.parameters; + signature.nonOptionalParameterCount = sigData.nonOptionalParameterCount; + funcDecl.signature = signature; + signature.declAST = funcDecl; + var useOverloadGroupSym = overloadGroupSym && overloadGroupSym.getType() && !overloadGroupSym.isAccessor() && (funcDecl.isSignature() || (isAmbient == TypeScript.hasFlag(overloadGroupSym.flags, TypeScript.SymbolFlags.Ambient))); + if(useOverloadGroupSym && isPrivate != TypeScript.hasFlag(overloadGroupSym.flags, TypeScript.SymbolFlags.Private)) { + this.errorReporter.simpleError(funcDecl, "Public/Private visibility of overloads does not agree"); + } + var groupType = useOverloadGroupSym ? overloadGroupSym.getType() : new TypeScript.Type(); + if(isConstructor) { + if(groupType.construct == null) { + groupType.construct = new TypeScript.SignatureGroup(); + } + groupType.construct.addSignature(signature); + groupType.construct.hasImplementation = !(funcDecl.isSignature()); + if(groupType.construct.hasImplementation) { + groupType.setHasImplementation(); + } + } else { + if(funcDecl.isIndexerMember()) { + if(groupType.index == null) { + groupType.index = new TypeScript.SignatureGroup(); + groupType.index.flags |= TypeScript.SignatureFlags.IsIndexer; + } + groupType.index.addSignature(signature); + groupType.index.hasImplementation = !(funcDecl.isSignature()); + if(groupType.index.hasImplementation) { + groupType.setHasImplementation(); + } + } else { + if(groupType.call == null) { + groupType.call = new TypeScript.SignatureGroup(); + } + groupType.call.addSignature(signature); + groupType.call.hasImplementation = !(funcDecl.isSignature()); + if(groupType.call.hasImplementation) { + groupType.setHasImplementation(); + } + } + } + var instanceType = groupType.instanceType; + var funcName = null; + var usedHint = false; + if(funcDecl.name && !funcDecl.name.isMissing()) { + funcName = funcDecl.name.text; + } else { + if(funcDecl.hint) { + funcName = funcDecl.hint; + usedHint = true; + } + } + if(groupType.symbol == null) { + groupType.symbol = new TypeScript.TypeSymbol(funcName ? funcName : this.anon, funcDecl.minChar, funcDecl.limChar - funcDecl.minChar, this.locationInfo.unitIndex, groupType); + if(!useOverloadGroupSym) { + groupType.symbol.declAST = funcDecl; + } + } + if(isStatic) { + groupType.symbol.flags |= TypeScript.SymbolFlags.Static; + } + if(isAmbient) { + groupType.symbol.flags |= TypeScript.SymbolFlags.Ambient; + } + if(isPrivate) { + groupType.symbol.flags |= TypeScript.SymbolFlags.Private; + } + groupType.symbol.isMethod = funcDecl.isMethod(); + if(groupType.symbol.isMethod) { + groupType.symbol.flags |= TypeScript.SymbolFlags.Property; + } + funcDecl.type = groupType; + if(!isConstructor) { + if(funcName && !isLambda && !funcDecl.isAccessor() && !usedHint) { + if(addToScope) { + if(funcDecl.isMethod() && isStatic) { + if(!(container).type.members.publicMembers.add(funcName, groupType.symbol)) { + this.errorReporter.duplicateIdentifier(funcDecl, funcName); + } + groupType.symbol.container = container; + } else { + if(overloadGroupSym == null || (overloadGroupSym.declAST && !(overloadGroupSym.declAST).isOverload && (container.isType()))) { + scope.enter(container, funcDecl, groupType.symbol, this.errorReporter, !isPrivate && (isExported || isStatic || isGlobal), false, isAmbient); + } + } + } else { + if(!funcDecl.isSpecialFn()) { + groupType.symbol.container = container; + } + } + } else { + if(!funcDecl.isSpecialFn()) { + groupType.symbol.container = container; + } + } + } + if(useOverloadGroupSym) { + var overloadGroupType = overloadGroupSym ? overloadGroupSym.getType() : null; + var classType = groupType; + if(classType != overloadGroupType) { + if(classType.construct == null) { + if(overloadGroupType && overloadGroupType.construct) { + classType.construct = overloadGroupType.construct; + } else { + classType.construct = new TypeScript.SignatureGroup(); + } + } else { + if(overloadGroupType) { + if(overloadGroupType.construct) { + classType.construct.signatures.concat(overloadGroupType.construct.signatures); + } + } + } + if(overloadGroupType) { + if(classType.call == null) { + classType.call = overloadGroupType.call; + } else { + if(overloadGroupType.call) { + classType.call.signatures.concat(overloadGroupType.call.signatures); + } + } + if(!isStatic) { + if(classType.instanceType == null) { + classType.instanceType = overloadGroupType.instanceType; + } + var instanceType = classType.instanceType; + if(instanceType) { + if(instanceType.call == null) { + instanceType.call = overloadGroupType.call; + } else { + if(overloadGroupType.call) { + instanceType.call.signatures.concat(overloadGroupType.call.signatures); + } + } + } + } + if(classType.index == null) { + classType.index = overloadGroupType.index; + } else { + if(overloadGroupType.index) { + classType.index.signatures.concat(overloadGroupType.index.signatures); + } + } + } + } + } + return signature; + }; + TypeChecker.prototype.createAccessorSymbol = function (funcDecl, fgSym, enclosingClass, addToMembers, isClassProperty, scope, container) { + var accessorSym = null; + var sig = funcDecl.signature; + var nameText = funcDecl.name.text; + var isStatic = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static); + var isPrivate = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Private); + if(fgSym == null) { + var field = new TypeScript.ValueLocation(); + accessorSym = new TypeScript.FieldSymbol(nameText, funcDecl.minChar, this.locationInfo.unitIndex, false, field); + field.symbol = accessorSym; + accessorSym.declAST = funcDecl; + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { + if(accessorSym.getter) { + this.errorReporter.simpleError(funcDecl, "Redeclaration of property getter"); + } + accessorSym.getter = sig.declAST.type.symbol; + } else { + if(accessorSym.setter) { + this.errorReporter.simpleError(funcDecl, "Redeclaration of property setter"); + } + accessorSym.setter = sig.declAST.type.symbol; + } + field.typeLink = TypeScript.getTypeLink(null, this, false); + if(addToMembers) { + if(enclosingClass) { + if(!enclosingClass.members.publicMembers.add(nameText, accessorSym)) { + this.errorReporter.duplicateIdentifier(funcDecl, accessorSym.name); + } + accessorSym.container = enclosingClass.symbol; + } else { + this.errorReporter.simpleError(funcDecl, "Accessor property may not be added in this context"); + } + } else { + scope.enter(container, funcDecl, accessorSym, this.errorReporter, !isPrivate || isStatic, false, false); + } + if(isClassProperty) { + accessorSym.flags |= TypeScript.SymbolFlags.Property; + } + if(isStatic) { + accessorSym.flags |= TypeScript.SymbolFlags.Static; + } + if(isPrivate) { + accessorSym.flags |= TypeScript.SymbolFlags.Private; + } else { + accessorSym.flags |= TypeScript.SymbolFlags.Public; + } + } else { + accessorSym = (fgSym); + if(isPrivate != TypeScript.hasFlag(accessorSym.flags, TypeScript.SymbolFlags.Private)) { + this.errorReporter.simpleError(funcDecl, "Getter and setter accessors do not agree in visibility"); + } + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { + if(accessorSym.getter) { + this.errorReporter.simpleError(funcDecl, "Redeclaration of property getter"); + } + accessorSym.getter = funcDecl.type.symbol; + } else { + if(accessorSym.setter) { + this.errorReporter.simpleError(funcDecl, "Redeclaration of property setter"); + } + accessorSym.setter = funcDecl.type.symbol; + } + } + return accessorSym; + }; + TypeChecker.prototype.addBases = function (resultScope, type, baseContext) { + resultScope.addParentScope(new TypeScript.SymbolTableScope(type.members, type.ambientMembers, type.getAllEnclosedTypes(), type.getAllAmbientEnclosedTypes(), type.symbol)); + var i = 0; + var parent; + if(type.extendsList) { + for(var len = type.extendsList.length; i < len; i++) { + parent = type.extendsList[i]; + if(baseContext.baseId == parent.typeID) { + this.errorReporter.reportErrorFromSym(parent.symbol, "Type '" + baseContext.base + "' is recursively referenced as a base class of itself"); + parent.symbol.flags |= TypeScript.SymbolFlags.RecursivelyReferenced; + break; + } + this.addBases(resultScope, parent, baseContext); + } + } + }; + TypeChecker.prototype.scopeOf = function (type) { + var resultScope = new TypeScript.SymbolAggregateScope(type.symbol); + var baseContext = { + base: type.symbol && type.symbol.name ? type.symbol.name : "{}", + baseId: type.typeID + }; + this.addBases(resultScope, type, baseContext); + return resultScope; + }; + TypeChecker.prototype.lookupMemberTypeSymbol = function (containingType, name) { + var symbol = null; + if(containingType.containedScope) { + symbol = containingType.containedScope.find(name, false, true); + } else { + if(containingType.members) { + symbol = containingType.members.allMembers.lookup(name); + if(symbol == null && containingType.ambientMembers) { + symbol = containingType.ambientMembers.allMembers.lookup(name); + } + } + } + if(symbol == null) { + var typeMembers = containingType.getAllEnclosedTypes(); + var ambientTypeMembers = containingType.getAllAmbientEnclosedTypes(); + if(typeMembers) { + symbol = typeMembers.allMembers.lookup(name); + if(symbol == null && ambientTypeMembers) { + symbol = ambientTypeMembers.allMembers.lookup(name); + } + } + } + if(symbol && symbol.isType()) { + return symbol; + } else { + return null; + } + }; + TypeChecker.prototype.findSymbolForDynamicModule = function (idText, currentFileName, search) { + var originalIdText = idText; + var symbol = search(idText); + if(symbol == null) { + if(!symbol) { + idText = TypeScript.swapQuotes(originalIdText); + symbol = search(idText); + } + if(!symbol) { + idText = TypeScript.stripQuotes(originalIdText) + ".ts"; + symbol = search(idText); + } + if(!symbol) { + idText = TypeScript.stripQuotes(originalIdText) + ".str"; + symbol = search(idText); + } + if(!symbol) { + idText = TypeScript.stripQuotes(originalIdText) + ".d.ts"; + symbol = search(idText); + } + if(!symbol) { + idText = TypeScript.stripQuotes(originalIdText) + ".d.str"; + symbol = search(idText); + } + if(!symbol && !TypeScript.isRelative(originalIdText)) { + idText = originalIdText; + var strippedIdText = TypeScript.stripQuotes(idText); + var path = TypeScript.getRootFilePath(TypeScript.switchToForwardSlashes(currentFileName)); + while(symbol == null && path != "") { + idText = TypeScript.normalizePath(path + strippedIdText + ".ts"); + symbol = search(idText); + if(symbol == null) { + idText = TypeScript.changePathToSTR(idText); + symbol = search(idText); + } + if(symbol == null) { + idText = TypeScript.changePathToDTS(idText); + symbol = search(idText); + } + if(symbol == null) { + idText = TypeScript.changePathToDSTR(idText); + symbol = search(idText); + } + if(symbol == null) { + if(path === '/') { + path = ''; + } else { + path = TypeScript.normalizePath(path + ".."); + path = path && path != '/' ? path + '/' : path; + } + } + } + } + } + return symbol; + }; + TypeChecker.prototype.resolveTypeMember = function (scope, dotNode) { + var lhs = dotNode.operand1; + var rhs = dotNode.operand2; + var resultType = this.anyType; + var lhsType = this.anyType; + if(lhs && rhs && (rhs.nodeType == TypeScript.NodeType.Name)) { + if(lhs.nodeType == TypeScript.NodeType.Dot) { + lhsType = this.resolveTypeMember(scope, lhs); + } else { + if(lhs.nodeType == TypeScript.NodeType.Name) { + var identifier = lhs; + var symbol = scope.find(identifier.text, false, true); + if(symbol == null) { + this.errorReporter.unresolvedSymbol(identifier, identifier.actualText); + } else { + if(symbol.isType()) { + var typeSymbol = symbol; + if(typeSymbol.aliasLink && !typeSymbol.type && typeSymbol.aliasLink.alias.nodeType == TypeScript.NodeType.Name) { + var modPath = (typeSymbol.aliasLink.alias).text; + var modSym = this.findSymbolForDynamicModule(modPath, this.locationInfo.filename, function (id) { + return scope.find(id, false, true); + }); + if(modSym) { + typeSymbol.type = modSym.getType(); + } + } + if(TypeScript.optimizeModuleCodeGen && symbol) { + var symType = symbol.getType(); + if(symType && typeSymbol.aliasLink && typeSymbol.onlyReferencedAsTypeRef) { + var modDecl = symType.symbol.declAST; + if(modDecl && TypeScript.hasFlag(modDecl.modFlags, TypeScript.ModuleFlags.IsDynamic)) { + typeSymbol.onlyReferencedAsTypeRef = !this.resolvingBases; + } + } + } + if(!symbol.visible(scope, this)) { + this.errorReporter.simpleError(lhs, "The symbol '" + identifier.actualText + "' is not visible at this point"); + } + lhsType = symbol.getType(); + identifier.sym = symbol; + } else { + this.errorReporter.simpleError(lhs, "Expected type"); + } + } + } + } + if(!lhsType) { + lhsType = this.anyType; + } + if(lhsType != this.anyType) { + var rhsIdentifier = rhs; + var resultSymbol = this.lookupMemberTypeSymbol(lhsType, rhsIdentifier.text); + if(resultSymbol == null) { + resultType = this.anyType; + this.errorReporter.simpleError(dotNode, "Expected type"); + } else { + resultType = resultSymbol.getType(); + if(!resultSymbol.visible(scope, this)) { + this.errorReporter.simpleError(lhs, "The symbol '" + (rhs).actualText + "' is not visible at this point"); + } + } + rhsIdentifier.sym = resultType.symbol; + } + } + if(resultType.isClass()) { + resultType = resultType.instanceType; + } + return resultType; + }; + TypeChecker.prototype.resolveFuncDecl = function (funcDecl, scope, fgSym) { + var functionGroupSymbol = this.createFunctionSignature(funcDecl, scope.container, scope, fgSym, false).declAST.type.symbol; + var signatures; + if(funcDecl.isConstructMember()) { + signatures = functionGroupSymbol.type.construct.signatures; + } else { + if(funcDecl.isIndexerMember()) { + signatures = functionGroupSymbol.type.getInstanceType().index.signatures; + } else { + signatures = functionGroupSymbol.type.call.signatures; + } + } + var signature = signatures[signatures.length - 1]; + var len = signature.parameters.length; + for(var i = 0; i < len; i++) { + var paramSym = signature.parameters[i]; + this.resolveTypeLink(scope, paramSym.parameter.typeLink, true); + } + if(len && funcDecl.variableArgList) { + if(!signature.parameters[len - 1].parameter.typeLink.type.elementType) { + this.errorReporter.simpleErrorFromSym(signature.parameters[len - 1].parameter.symbol, "... parameter must have array type"); + signature.parameters[len - 1].parameter.typeLink.type = this.makeArrayType(signature.parameters[len - 1].parameter.typeLink.type); + } + } + this.resolveTypeLink(scope, signature.returnType, funcDecl.isSignature()); + return functionGroupSymbol; + }; + TypeChecker.prototype.resolveVarDecl = function (varDecl, scope) { + var field = new TypeScript.ValueLocation(); + var fieldSymbol = new TypeScript.FieldSymbol(varDecl.id.text, varDecl.minChar, this.locationInfo.unitIndex, (varDecl.varFlags & TypeScript.VarFlags.Readonly) == TypeScript.VarFlags.None, field); + fieldSymbol.transferVarFlags(varDecl.varFlags); + field.symbol = fieldSymbol; + fieldSymbol.declAST = varDecl; + field.typeLink = TypeScript.getTypeLink(varDecl.typeExpr, this, varDecl.init == null); + this.resolveTypeLink(scope, field.typeLink, true); + varDecl.sym = fieldSymbol; + varDecl.type = field.typeLink.type; + return fieldSymbol; + }; + TypeChecker.prototype.resolveTypeLink = function (scope, typeLink, supplyVar) { + var arrayCount = 0; + if(typeLink.type == null) { + var ast = typeLink.ast; + if(ast) { + while(typeLink.type == null) { + switch(ast.nodeType) { + case TypeScript.NodeType.Name: { + var identifier = ast; + var symbol = scope.find(identifier.text, false, true); + if(symbol == null) { + typeLink.type = this.anyType; + this.errorReporter.unresolvedSymbol(identifier, identifier.actualText); + } else { + if(symbol.isType()) { + if(!symbol.visible(scope, this)) { + this.errorReporter.simpleError(ast, "The symbol '" + identifier.actualText + "' is not visible at this point"); + } + identifier.sym = symbol; + typeLink.type = symbol.getType(); + if(typeLink.type) { + if(typeLink.type.isClass()) { + typeLink.type = typeLink.type.instanceType; + } + } else { + typeLink.type = this.anyType; + } + } else { + typeLink.type = this.anyType; + this.errorReporter.simpleError(ast, "Expected type"); + } + } + break; + + } + case TypeScript.NodeType.Dot: { + typeLink.type = this.resolveTypeMember(scope, ast); + break; + + } + case TypeScript.NodeType.TypeRef: { + var typeRef = ast; + arrayCount = typeRef.arrayCount; + ast = typeRef.term; + if(ast == null) { + typeLink.type = this.anyType; + } + break; + + } + case TypeScript.NodeType.InterfaceDeclaration: { + var interfaceDecl = ast; + var interfaceType = new TypeScript.Type(); + var interfaceSymbol = new TypeScript.TypeSymbol((interfaceDecl.name).text, ast.minChar, ast.limChar - ast.minChar, this.locationInfo.unitIndex, interfaceType); + interfaceType.symbol = interfaceSymbol; + interfaceType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + interfaceType.containedScope = new TypeScript.SymbolTableScope(interfaceType.members, null, null, null, interfaceSymbol); + interfaceType.containedScope.container = interfaceSymbol; + interfaceType.memberScope = interfaceType.containedScope; + var memberList = interfaceDecl.members; + var props = memberList.members; + var propsLen = props.length; + for(var j = 0; j < propsLen; j++) { + var propDecl = props[j]; + var propSym = null; + var addMember = true; + var id = null; + if(propDecl.nodeType == TypeScript.NodeType.FuncDecl) { + var funcDecl = propDecl; + id = funcDecl.name; + propSym = interfaceType.members.allMembers.lookup(funcDecl.getNameText()); + addMember = (propSym == null); + if(funcDecl.isSpecialFn()) { + addMember = false; + propSym = this.resolveFuncDecl(funcDecl, scope, interfaceSymbol); + } else { + propSym = this.resolveFuncDecl(funcDecl, scope, propSym); + } + funcDecl.type = (propSym).type; + } else { + id = (propDecl).id; + propSym = this.resolveVarDecl(propDecl, scope); + addMember = !id.isMissing(); + } + if(addMember) { + if(id && TypeScript.hasFlag(id.flags, TypeScript.ASTFlags.OptionalName)) { + propSym.flags |= TypeScript.SymbolFlags.Optional; + } + if(!interfaceType.members.allMembers.add(propSym.name, propSym)) { + this.errorReporter.duplicateIdentifier(ast, propSym.name); + } + } + } + ast.type = interfaceType; + typeLink.type = interfaceType; + break; + + } + case TypeScript.NodeType.FuncDecl: { + var tsym = this.resolveFuncDecl(ast, scope, null); + typeLink.type = tsym.type; + break; + + } + default: { + typeLink.type = this.anyType; + this.errorReporter.simpleError(ast, "Expected type"); + break; + + } + } + } + } + for(var count = arrayCount; count > 0; count--) { + typeLink.type = this.makeArrayType(typeLink.type); + } + if(supplyVar && (typeLink.type == null)) { + typeLink.type = this.anyType; + } + if(typeLink.ast) { + typeLink.ast.type = typeLink.type; + } + } + }; + TypeChecker.prototype.resolveBaseTypeLink = function (typeLink, scope) { + this.resolvingBases = true; + this.resolveTypeLink(scope, typeLink, true); + this.resolvingBases = false; + var extendsType = null; + if(typeLink.type.isClass()) { + extendsType = typeLink.type.instanceType; + } else { + extendsType = typeLink.type; + } + return extendsType; + }; + TypeChecker.prototype.findMostApplicableSignature = function (signatures, args) { + if(signatures.length == 1) { + return { + sig: signatures[0].signature, + ambiguous: false + }; + } + var best = signatures[0]; + var Q = null; + var AType = null; + var PType = null; + var QType = null; + var ambiguous = false; + for(var qSig = 1; qSig < signatures.length; qSig++) { + Q = signatures[qSig]; + var i = 0; + for(i = 0; args && i < args.members.length; i++) { + AType = args.members[i].type; + PType = i < best.signature.parameters.length ? best.signature.parameters[i].getType() : best.signature.parameters[best.signature.parameters.length - 1].getType().elementType; + QType = i < Q.signature.parameters.length ? Q.signature.parameters[i].getType() : Q.signature.parameters[Q.signature.parameters.length - 1].getType().elementType; + if(this.typesAreIdentical(PType, QType)) { + continue; + } else { + if(this.typesAreIdentical(AType, PType)) { + break; + } else { + if(this.typesAreIdentical(AType, QType)) { + best = Q; + break; + } else { + if(this.sourceIsSubtypeOfTarget(PType, QType)) { + break; + } else { + if(this.sourceIsSubtypeOfTarget(QType, PType)) { + best = Q; + break; + } else { + if(Q.hadProvisionalErrors) { + break; + } else { + if(best.hadProvisionalErrors) { + best = Q; + break; + } + } + } + } + } + } + } + } + if(!args || i == args.members.length) { + var collection = { + getLength: function () { + return 2; + }, + setTypeAtIndex: function (index, type) { + }, + getTypeAtIndex: function (index) { + return index ? Q.signature.returnType.type : best.signature.returnType.type; + } + }; + var bct = this.findBestCommonType(best.signature.returnType.type, null, collection, true); + ambiguous = !bct; + } else { + ambiguous = false; + } + } + return { + sig: best.signature, + ambiguous: ambiguous + }; + }; + TypeChecker.prototype.getApplicableSignatures = function (signatures, args, comparisonInfo) { + var applicableSigs = []; + var memberType = null; + var miss = false; + var cxt = null; + var hadProvisionalErrors = false; + for(var i = 0; i < signatures.length; i++) { + miss = false; + for(var j = 0; j < args.members.length; j++) { + if(j >= signatures[i].parameters.length) { + continue; + } + memberType = signatures[i].parameters[j].getType(); + if(signatures[i].declAST.variableArgList && (j >= signatures[i].nonOptionalParameterCount - 1) && memberType.isArray()) { + memberType = memberType.elementType; + } + if(memberType == this.anyType) { + continue; + } else { + if(args.members[j].nodeType == TypeScript.NodeType.FuncDecl) { + if(this.typeFlow.functionInterfaceType && memberType == this.typeFlow.functionInterfaceType) { + continue; + } + if(!this.canContextuallyTypeFunction(memberType, args.members[j], true)) { + if(this.canContextuallyTypeFunction(memberType, args.members[j], false)) { + this.typeFlow.typeCheck(args.members[j]); + if(!this.sourceIsAssignableToTarget(args.members[j].type, memberType, comparisonInfo)) { + break; + } + } else { + break; + } + } else { + this.typeCheckWithContextualType(memberType, true, true, args.members[j]); + this.cleanStartedPTO(); + hadProvisionalErrors = this.hadProvisionalErrors(); + if(!this.sourceIsAssignableToTarget(args.members[j].type, memberType, comparisonInfo)) { + if(comparisonInfo) { + comparisonInfo.setMessage("Could not apply type '" + memberType.getTypeName() + "' to argument " + (j + 1) + ", which is of type '" + args.members[j].type.getTypeName() + "'"); + } + miss = true; + } + this.resetProvisionalErrors(); + if(miss) { + break; + } + } + } else { + if(args.members[j].nodeType == TypeScript.NodeType.ObjectLit) { + if(this.typeFlow.objectInterfaceType && memberType == this.typeFlow.objectInterfaceType) { + continue; + } + this.typeCheckWithContextualType(memberType, true, true, args.members[j]); + this.cleanStartedPTO(); + hadProvisionalErrors = this.hadProvisionalErrors(); + if(!this.sourceIsAssignableToTarget(args.members[j].type, memberType, comparisonInfo)) { + if(comparisonInfo) { + comparisonInfo.setMessage("Could not apply type '" + memberType.getTypeName() + "' to argument " + (j + 1) + ", which is of type '" + args.members[j].type.getTypeName() + "'"); + } + miss = true; + } + this.resetProvisionalErrors(); + if(miss) { + break; + } + } else { + if(args.members[j].nodeType == TypeScript.NodeType.ArrayLit) { + if(this.typeFlow.arrayInterfaceType && memberType == this.typeFlow.arrayInterfaceType) { + continue; + } + this.typeCheckWithContextualType(memberType, true, true, args.members[j]); + this.cleanStartedPTO(); + hadProvisionalErrors = this.hadProvisionalErrors(); + if(!this.sourceIsAssignableToTarget(args.members[j].type, memberType, comparisonInfo)) { + if(comparisonInfo) { + comparisonInfo.setMessage("Could not apply type '" + memberType.getTypeName() + "' to argument " + (j + 1) + ", which is of type '" + args.members[j].type.getTypeName() + "'"); + } + break; + } + this.resetProvisionalErrors(); + if(miss) { + break; + } + } + } + } + } + } + if(j == args.members.length) { + applicableSigs[applicableSigs.length] = { + signature: signatures[i], + hadProvisionalErrors: hadProvisionalErrors + }; + } + hadProvisionalErrors = false; + } + return applicableSigs; + }; + TypeChecker.prototype.canContextuallyTypeFunction = function (candidateType, funcDecl, beStringent) { + if(funcDecl.isParenthesized || funcDecl.isMethod() || beStringent && funcDecl.returnTypeAnnotation || funcDecl.isInlineCallLiteral) { + return false; + } + beStringent = beStringent || (this.typeFlow.functionInterfaceType == candidateType); + if(!beStringent) { + return true; + } + if(!funcDecl.signature) { + this.createFunctionSignature(funcDecl, this.typeFlow.scope.container, this.typeFlow.scope, null, null); + this.typeFlow.typeCheck(funcDecl); + } + var signature = funcDecl.signature; + var paramLen = signature.parameters.length; + for(var i = 0; i < paramLen; i++) { + var param = signature.parameters[i]; + var symbol = param; + var argDecl = symbol.declAST; + if(beStringent && argDecl.typeExpr) { + return false; + } + } + if(candidateType.construct && candidateType.call) { + return false; + } + var candidateSigs = candidateType.construct ? candidateType.construct : candidateType.call; + if(!candidateSigs || candidateSigs.signatures.length > 1) { + return false; + } + return true; + }; + TypeChecker.prototype.canContextuallyTypeObjectLiteral = function (targetType, objectLit) { + if(targetType == this.typeFlow.objectInterfaceType) { + return true; + } + var memberDecls = objectLit.operand; + if(!(memberDecls && targetType.memberScope)) { + return false; + } + var id = null; + var targetMember = null; + var text = ""; + var foundSyms = { + }; + for(var i = 0; i < memberDecls.members.length; i++) { + id = (memberDecls.members[i]).operand1; + if(id.nodeType == TypeScript.NodeType.Name) { + text = (id).text; + } else { + if(id.nodeType == TypeScript.NodeType.QString) { + var idText = (id).text; + text = idText.substring(1, idText.length - 1); + } else { + return false; + } + } + targetMember = targetType.memberScope.find(text, true, false); + if(!targetMember) { + return false; + } + foundSyms[text] = true; + } + var targetMembers = targetType.memberScope.getAllValueSymbolNames(true); + for(var i = 0; i < targetMembers.length; i++) { + var memberName = targetMembers[i]; + var memberSym = targetType.memberScope.find(memberName, true, false); + if(!foundSyms[targetMembers[i]] && !TypeScript.hasFlag(memberSym.flags, TypeScript.SymbolFlags.Optional)) { + return false; + } + } + return true; + }; + TypeChecker.prototype.widenType = function (t) { + if(t == this.undefinedType || t == this.nullType) { + return this.anyType; + } + return t; + }; + TypeChecker.prototype.isNullOrUndefinedType = function (t) { + return t == this.undefinedType || t == this.nullType; + }; + TypeChecker.prototype.findBestCommonType = function (initialType, targetType, collection, acceptVoid, comparisonInfo) { + var i = 0; + var len = collection.getLength(); + var nlastChecked = 0; + var bestCommonType = initialType; + if(targetType) { + bestCommonType = bestCommonType ? bestCommonType.mergeOrdered(targetType, this, acceptVoid) : targetType; + } + var convergenceType = bestCommonType; + while(nlastChecked < len) { + for(i = 0; i < len; i++) { + if(i == nlastChecked) { + continue; + } + if(convergenceType && (bestCommonType = convergenceType.mergeOrdered(collection.getTypeAtIndex(i), this, acceptVoid, comparisonInfo))) { + convergenceType = bestCommonType; + } + if(bestCommonType == this.anyType || bestCommonType == null) { + break; + } else { + if(targetType) { + collection.setTypeAtIndex(i, targetType); + } + } + } + if(convergenceType && bestCommonType) { + break; + } + nlastChecked++; + if(nlastChecked < len) { + convergenceType = collection.getTypeAtIndex(nlastChecked); + } + } + return acceptVoid ? bestCommonType : (bestCommonType == this.voidType ? null : bestCommonType); + }; + TypeChecker.prototype.typesAreIdentical = function (t1, t2) { + if(t1 == t2) { + return true; + } + if(!t1 || !t2) { + return false; + } + if(t1.isClass() || t1.isClassInstance()) { + return false; + } + var comboId = (t2.typeID << 16) | t1.typeID; + if(this.identicalCache[comboId]) { + return true; + } + if((t1.typeFlags & TypeScript.TypeFlags.IsEnum) || (t2.typeFlags & TypeScript.TypeFlags.IsEnum)) { + return false; + } + if(t1.isArray() || t2.isArray()) { + if(!(t1.isArray() && t2.isArray())) { + return false; + } + this.identicalCache[comboId] = false; + var ret = this.typesAreIdentical(t1.elementType, t2.elementType); + if(ret) { + this.subtypeCache[comboId] = true; + } else { + this.subtypeCache[comboId] = undefined; + } + return ret; + } + if(t1.primitiveTypeClass != t2.primitiveTypeClass) { + return false; + } + this.identicalCache[comboId] = false; + if(t1.memberScope && t2.memberScope) { + var t1MemberKeys = t1.memberScope.getAllValueSymbolNames(true).sort(); + var t2MemberKeys = t2.memberScope.getAllValueSymbolNames(true).sort(); + if(t1MemberKeys.length != t2MemberKeys.length) { + this.identicalCache[comboId] = undefined; + return false; + } + var t1MemberSymbol = null; + var t2MemberSymbol = null; + var t1MemberType = null; + var t2MemberType = null; + for(var iMember = 0; iMember < t1MemberKeys.length; iMember++) { + if(t1MemberKeys[iMember] != t2MemberKeys[iMember]) { + this.identicalCache[comboId] = undefined; + return false; + } + t1MemberSymbol = t1.memberScope.find(t1MemberKeys[iMember], false, false); + t2MemberSymbol = t2.memberScope.find(t2MemberKeys[iMember], false, false); + if((t1MemberSymbol.flags & TypeScript.SymbolFlags.Optional) != (t2MemberSymbol.flags & TypeScript.SymbolFlags.Optional)) { + this.identicalCache[comboId] = undefined; + return false; + } + t1MemberType = t1MemberSymbol.getType(); + t2MemberType = t2MemberSymbol.getType(); + if(t1MemberType && t2MemberType && (this.identicalCache[(t2MemberType.typeID << 16) | t1MemberType.typeID] != undefined)) { + continue; + } + if(!this.typesAreIdentical(t1MemberType, t2MemberType)) { + this.identicalCache[comboId] = undefined; + return false; + } + } + } else { + if(t1.memberScope || t2.memberScope) { + this.identicalCache[comboId] = undefined; + return false; + } + } + if(!this.signatureGroupsAreIdentical(t1.call, t2.call)) { + this.identicalCache[comboId] = undefined; + return false; + } + if(!this.signatureGroupsAreIdentical(t1.construct, t2.construct)) { + this.identicalCache[comboId] = undefined; + return false; + } + if(!this.signatureGroupsAreIdentical(t1.index, t2.index)) { + this.identicalCache[comboId] = undefined; + return false; + } + this.identicalCache[comboId] = true; + return true; + }; + TypeChecker.prototype.signatureGroupsAreIdentical = function (sg1, sg2) { + if(sg1 == sg2) { + return true; + } + if(!sg1 || !sg2) { + return false; + } + if(sg1.signatures.length != sg2.signatures.length) { + return false; + } + var sig1 = null; + var sig2 = null; + var sigsMatch = false; + for(var iSig1 = 0; iSig1 < sg1.signatures.length; iSig1++) { + sig1 = sg1.signatures[iSig1]; + for(var iSig2 = 0; iSig2 < sg2.signatures.length; iSig2++) { + sig2 = sg2.signatures[iSig2]; + if(this.signaturesAreIdentical(sig1, sig2)) { + sigsMatch = true; + break; + } + } + if(sigsMatch) { + sigsMatch = false; + continue; + } + return false; + } + return true; + }; + TypeChecker.prototype.signaturesAreIdentical = function (s1, s2) { + if(s1.hasVariableArgList != s2.hasVariableArgList) { + return false; + } + if(s1.nonOptionalParameterCount != s2.nonOptionalParameterCount) { + return false; + } + if(s1.parameters.length != s2.parameters.length) { + return false; + } + if(!this.typesAreIdentical(s1.returnType.type, s2.returnType.type)) { + return false; + } + for(var iParam = 0; iParam < s1.parameters.length; iParam++) { + if(!this.typesAreIdentical(s1.parameters[iParam].parameter.typeLink.type, s2.parameters[iParam].parameter.typeLink.type)) { + return false; + } + } + return true; + }; + TypeChecker.prototype.sourceIsSubtypeOfTarget = function (source, target, comparisonInfo) { + return this.sourceIsRelatableToTarget(source, target, false, this.subtypeCache, comparisonInfo); + }; + TypeChecker.prototype.signatureGroupIsSubtypeOfTarget = function (sg1, sg2, comparisonInfo) { + return this.signatureGroupIsRelatableToTarget(sg1, sg2, false, this.subtypeCache, comparisonInfo); + }; + TypeChecker.prototype.signatureIsSubtypeOfTarget = function (s1, s2, comparisonInfo) { + return this.signatureIsRelatableToTarget(s1, s2, false, this.subtypeCache, comparisonInfo); + }; + TypeChecker.prototype.sourceIsAssignableToTarget = function (source, target, comparisonInfo) { + return this.sourceIsRelatableToTarget(source, target, true, this.assignableCache, comparisonInfo); + }; + TypeChecker.prototype.signatureGroupIsAssignableToTarget = function (sg1, sg2, comparisonInfo) { + return this.signatureGroupIsRelatableToTarget(sg1, sg2, true, this.assignableCache, comparisonInfo); + }; + TypeChecker.prototype.signatureIsAssignableToTarget = function (s1, s2, comparisonInfo) { + return this.signatureIsRelatableToTarget(s1, s2, true, this.assignableCache, comparisonInfo); + }; + TypeChecker.prototype.sourceIsRelatableToTarget = function (source, target, assignableTo, comparisonCache, comparisonInfo) { + if(source == target) { + return true; + } + if(!(source && target)) { + return true; + } + var comboId = (source.typeID << 16) | target.typeID; + if(comparisonCache[comboId] != undefined) { + return true; + } + if(assignableTo) { + if(source == this.anyType || target == this.anyType) { + return true; + } + } else { + if(target == this.anyType) { + return true; + } + } + if(source == this.undefinedType) { + return true; + } + if((source == this.nullType) && (target != this.undefinedType && target != this.voidType)) { + return true; + } + if(target == this.numberType && (source.typeFlags & TypeScript.TypeFlags.IsEnum)) { + return true; + } + if(source == this.numberType && (target.typeFlags & TypeScript.TypeFlags.IsEnum)) { + return true; + } + if((source.typeFlags & TypeScript.TypeFlags.IsEnum) || (target.typeFlags & TypeScript.TypeFlags.IsEnum)) { + return false; + } + if(source.isArray() || target.isArray()) { + if(!(source.isArray() && target.isArray())) { + return false; + } + comparisonCache[comboId] = false; + var ret = this.sourceIsRelatableToTarget(source.elementType, target.elementType, assignableTo, comparisonCache, comparisonInfo); + if(ret) { + comparisonCache[comboId] = true; + } else { + comparisonCache[comboId] = undefined; + } + return ret; + } + if(source.primitiveTypeClass != target.primitiveTypeClass) { + if(target.primitiveTypeClass == TypeScript.Primitive.None) { + if(source == this.numberType && this.typeFlow.numberInterfaceType) { + source = this.typeFlow.numberInterfaceType; + } else { + if(source == this.stringType && this.typeFlow.stringInterfaceType) { + source = this.typeFlow.stringInterfaceType; + } else { + if(source == this.booleanType && this.typeFlow.booleanInterfaceType) { + source = this.typeFlow.booleanInterfaceType; + } else { + return false; + } + } + } + } else { + return false; + } + } + comparisonCache[comboId] = false; + if(source.hasBase(target)) { + comparisonCache[comboId] = true; + return true; + } + if(this.typeFlow.objectInterfaceType && target == this.typeFlow.objectInterfaceType) { + return true; + } + if(this.typeFlow.functionInterfaceType && (source.call || source.construct) && target == this.typeFlow.functionInterfaceType) { + return true; + } + if(target.isClass() || target.isClassInstance()) { + comparisonCache[comboId] = undefined; + return false; + } + if(target.memberScope && source.memberScope) { + var mPropKeys = target.memberScope.getAllValueSymbolNames(true); + var mProp = null; + var nProp = null; + var mPropType = null; + var nPropType = null; + var inferenceSymbol = null; + for(var iMProp = 0; iMProp < mPropKeys.length; iMProp++) { + mProp = target.memberScope.find(mPropKeys[iMProp], false, false); + nProp = source.memberScope.find(mPropKeys[iMProp], false, false); + if(mProp.name == "arguments" && this.typeFlow.iargumentsInterfaceType && (this.typeFlow.iargumentsInterfaceType.symbol.flags & TypeScript.SymbolFlags.CompilerGenerated) && mProp.kind() == TypeScript.SymbolKind.Variable && (mProp).variable.typeLink.type == this.typeFlow.iargumentsInterfaceType) { + continue; + } + if(mProp.isInferenceSymbol()) { + inferenceSymbol = mProp; + if(inferenceSymbol.typeCheckStatus == TypeScript.TypeCheckStatus.NotStarted) { + this.typeFlow.typeCheck(mProp.declAST); + } + } + mPropType = mProp.getType(); + if(!nProp) { + if(this.typeFlow.objectInterfaceType) { + nProp = this.typeFlow.objectInterfaceType.memberScope.find(mPropKeys[iMProp], false, false); + } + if(!nProp) { + if(this.typeFlow.functionInterfaceType && (mPropType.call || mPropType.construct)) { + nProp = this.typeFlow.functionInterfaceType.memberScope.find(mPropKeys[iMProp], false, false); + } + if(!nProp) { + if(!(mProp.flags & TypeScript.SymbolFlags.Optional)) { + comparisonCache[comboId] = undefined; + if(comparisonInfo) { + comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.RequiredPropertyIsMissing; + comparisonInfo.addMessageToFront("Type '" + source.getTypeName() + "' is missing property '" + mPropKeys[iMProp] + "' from type '" + target.getTypeName() + "'"); + } + return false; + } else { + continue; + } + } + } + } + if(nProp.isInferenceSymbol()) { + inferenceSymbol = nProp; + if(inferenceSymbol.typeCheckStatus == TypeScript.TypeCheckStatus.NotStarted) { + this.typeFlow.typeCheck(nProp.declAST); + } + } + nPropType = nProp.getType(); + if(mPropType && nPropType && (comparisonCache[(nPropType.typeID << 16) | mPropType.typeID] != undefined)) { + continue; + } + if(!this.sourceIsRelatableToTarget(nPropType, mPropType, assignableTo, comparisonCache, comparisonInfo)) { + comparisonCache[comboId] = undefined; + if(comparisonInfo) { + comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatiblePropertyTypes; + comparisonInfo.addMessageToFront("Types of property '" + mProp.name + "' of types '" + source.getTypeName() + "' and '" + target.getTypeName() + "' are incompatible"); + } + return false; + } + } + } + if(source.call || target.call) { + if(!this.signatureGroupIsRelatableToTarget(source.call, target.call, assignableTo, comparisonCache, comparisonInfo)) { + if(comparisonInfo) { + if(source.call && target.call) { + comparisonInfo.addMessageToFront("Call signatures of types '" + source.getTypeName() + "' and '" + target.getTypeName() + "' are incompatible"); + } else { + var hasSig = target.call ? target.getTypeName() : source.getTypeName(); + var lacksSig = !target.call ? target.getTypeName() : source.getTypeName(); + comparisonInfo.setMessage("Type '" + hasSig + "' requires a call signature, but Type '" + lacksSig + "' lacks one"); + } + comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleSignatures; + } + comparisonCache[comboId] = undefined; + return false; + } + } + if(source.construct || target.construct) { + if(!this.signatureGroupIsRelatableToTarget(source.construct, target.construct, assignableTo, comparisonCache, comparisonInfo)) { + if(comparisonInfo) { + if(source.construct && target.construct) { + comparisonInfo.addMessageToFront("Construct signatures of types '" + source.getTypeName() + "' and '" + target.getTypeName() + "' are incompatible"); + } else { + var hasSig = target.construct ? target.getTypeName() : source.getTypeName(); + var lacksSig = !target.construct ? target.getTypeName() : source.getTypeName(); + comparisonInfo.setMessage("Type '" + hasSig + "' requires a construct signature, but Type '" + lacksSig + "' lacks one"); + } + comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleSignatures; + } + comparisonCache[comboId] = undefined; + return false; + } + } + if(target.index) { + var targetIndex = !target.index && this.typeFlow.objectInterfaceType ? this.typeFlow.objectInterfaceType.index : target.index; + var sourceIndex = !source.index && this.typeFlow.objectInterfaceType ? this.typeFlow.objectInterfaceType.index : source.index; + if(!this.signatureGroupIsRelatableToTarget(sourceIndex, targetIndex, assignableTo, comparisonCache, comparisonInfo)) { + if(comparisonInfo) { + comparisonInfo.addMessageToFront("Index signatures of types '" + source.getTypeName() + "' and '" + target.getTypeName() + "' are incompatible"); + comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleSignatures; + } + comparisonCache[comboId] = undefined; + return false; + } + } + comparisonCache[comboId] = true; + return true; + }; + TypeChecker.prototype.signatureGroupIsRelatableToTarget = function (sourceSG, targetSG, assignableTo, comparisonCache, comparisonInfo) { + if(sourceSG == targetSG) { + return true; + } + if(!(sourceSG && targetSG)) { + return false; + } + var mSig = null; + var nSig = null; + var foundMatch = false; + for(var iMSig = 0; iMSig < targetSG.signatures.length; iMSig++) { + mSig = targetSG.signatures[iMSig]; + for(var iNSig = 0; iNSig < sourceSG.signatures.length; iNSig++) { + nSig = sourceSG.signatures[iNSig]; + if(this.signatureIsRelatableToTarget(nSig, mSig, assignableTo, comparisonCache, comparisonInfo)) { + foundMatch = true; + break; + } + } + if(foundMatch) { + foundMatch = false; + continue; + } + return false; + } + return true; + }; + TypeChecker.prototype.signatureIsRelatableToTarget = function (sourceSig, targetSig, assignableTo, comparisonCache, comparisonInfo) { + if(!sourceSig.parameters || !targetSig.parameters) { + return false; + } + var targetVarArgCount = targetSig.hasVariableArgList ? targetSig.nonOptionalParameterCount - 1 : targetSig.nonOptionalParameterCount; + var sourceVarArgCount = sourceSig.hasVariableArgList ? sourceSig.nonOptionalParameterCount - 1 : sourceSig.nonOptionalParameterCount; + if(sourceVarArgCount > targetVarArgCount && !targetSig.hasVariableArgList) { + if(comparisonInfo) { + comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.SourceSignatureHasTooManyParameters; + comparisonInfo.addMessageToFront("Call signature expects " + targetVarArgCount + " or fewer parameters"); + } + return false; + } + var sourceReturnType = sourceSig.returnType.type; + var targetReturnType = targetSig.returnType.type; + if(targetReturnType != this.voidType) { + if(!this.sourceIsRelatableToTarget(sourceReturnType, targetReturnType, assignableTo, comparisonCache, comparisonInfo)) { + if(comparisonInfo) { + comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleReturnTypes; + } + return false; + } + } + var len = (sourceVarArgCount < targetVarArgCount && sourceSig.hasVariableArgList) ? targetVarArgCount : sourceVarArgCount; + var sourceParamType = null; + var targetParamType = null; + var sourceParamName = ""; + var targetParamName = ""; + for(var iSource = 0, iTarget = 0; iSource < len; iSource++ , iTarget++) { + if(!sourceSig.hasVariableArgList || iSource < sourceVarArgCount) { + sourceParamType = (sourceSig.parameters[iSource]).parameter.typeLink.type; + sourceParamName = (sourceSig.parameters[iSource]).parameter.symbol.name; + } else { + if(iSource == sourceVarArgCount) { + sourceParamType = (sourceSig.parameters[iSource]).parameter.typeLink.type; + if(sourceParamType.elementType) { + sourceParamType = sourceParamType.elementType; + } + sourceParamName = (sourceSig.parameters[iSource]).parameter.symbol.name; + } + } + if(iTarget < targetSig.parameters.length && iTarget < targetVarArgCount) { + targetParamType = (targetSig.parameters[iTarget]).parameter.typeLink.type; + targetParamName = (targetSig.parameters[iTarget]).parameter.symbol.name; + } else { + if(targetSig.hasVariableArgList && iTarget == targetVarArgCount) { + targetParamType = (targetSig.parameters[iTarget]).parameter.typeLink.type; + if(targetParamType.elementType) { + targetParamType = targetParamType.elementType; + } + targetParamName = (targetSig.parameters[iTarget]).parameter.symbol.name; + } + } + if(!(this.sourceIsRelatableToTarget(sourceParamType, targetParamType, assignableTo, comparisonCache, comparisonInfo) || this.sourceIsRelatableToTarget(targetParamType, sourceParamType, assignableTo, comparisonCache, comparisonInfo))) { + if(comparisonInfo) { + comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleParameterTypes; + } + return false; + } + } + return true; + }; + return TypeChecker; + })(); + TypeScript.TypeChecker = TypeChecker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Continuation = (function () { + function Continuation(normalBlock) { + this.normalBlock = normalBlock; + this.exceptionBlock = -1; + } + return Continuation; + })(); + TypeScript.Continuation = Continuation; + function getBaseTypeLinks(bases, baseTypeLinks) { + if(bases) { + var len = bases.members.length; + if(baseTypeLinks == null) { + baseTypeLinks = new Array(); + } + for(var i = 0; i < len; i++) { + var baseExpr = bases.members[i]; + var name = baseExpr; + var typeLink = new TypeScript.TypeLink(); + typeLink.ast = name; + baseTypeLinks[baseTypeLinks.length] = typeLink; + } + } + return baseTypeLinks; + } + function getBases(type, typeDecl) { + type.extendsTypeLinks = getBaseTypeLinks(typeDecl.extendsList, type.extendsTypeLinks); + type.implementsTypeLinks = getBaseTypeLinks(typeDecl.implementsList, type.implementsTypeLinks); + } + function addPrototypeField(classType, ast, context) { + var field = new TypeScript.ValueLocation(); + field.typeLink = new TypeScript.TypeLink(); + field.typeLink.ast = ast; + field.typeLink.type = classType.instanceType; + var fieldSymbol = new TypeScript.FieldSymbol("prototype", ast.minChar, context.checker.locationInfo.unitIndex, true, field); + fieldSymbol.flags |= (TypeScript.SymbolFlags.Property | TypeScript.SymbolFlags.BuiltIn); + field.symbol = fieldSymbol; + fieldSymbol.declAST = ast; + classType.members.addPublicMember("prototype", fieldSymbol); + } + function createNewConstructGroupForType(type) { + var signature = new TypeScript.Signature(); + signature.returnType = new TypeScript.TypeLink(); + signature.returnType.type = type.instanceType; + signature.parameters = []; + type.construct = new TypeScript.SignatureGroup(); + type.construct.addSignature(signature); + } + TypeScript.createNewConstructGroupForType = createNewConstructGroupForType; + function cloneParentConstructGroupForChildType(child, parent) { + child.construct = new TypeScript.SignatureGroup(); + var sig = null; + if(!parent.construct) { + createNewConstructGroupForType(parent); + } + for(var i = 0; i < parent.construct.signatures.length; i++) { + sig = new TypeScript.Signature(); + sig.parameters = parent.construct.signatures[i].parameters; + sig.nonOptionalParameterCount = parent.construct.signatures[i].nonOptionalParameterCount; + sig.typeCheckStatus = parent.construct.signatures[i].typeCheckStatus; + sig.declAST = parent.construct.signatures[i].declAST; + sig.returnType = new TypeScript.TypeLink(); + sig.returnType.type = child.instanceType; + child.construct.addSignature(sig); + } + } + TypeScript.cloneParentConstructGroupForChildType = cloneParentConstructGroupForChildType; + TypeScript.globalId = "__GLO"; + function findTypeSymbolInScopeChain(name, scopeChain) { + var symbol = scopeChain.scope.find(name, false, true); + if(symbol == null && scopeChain.previous) { + symbol = findTypeSymbolInScopeChain(name, scopeChain.previous); + } + return symbol; + } + function findSymbolFromAlias(alias, context) { + var symbol = null; + switch(alias.nodeType) { + case TypeScript.NodeType.Name: { + var name = (alias).text; + var isDynamic = TypeScript.isQuoted(name); + var findSym = function (id) { + if(context.members) { + return context.members.lookup(name); + } else { + return findTypeSymbolInScopeChain(name, context.topLevelScope); + } + }; + if(isDynamic) { + symbol = context.tcContext.checker.findSymbolForDynamicModule(name, context.tcContext.script.locationInfo.filename, findSym); + } else { + symbol = findSym(name); + } + break; + + } + case TypeScript.NodeType.Dot: { + var dottedExpr = alias; + var op1Sym = findSymbolFromAlias(dottedExpr.operand1, context); + if(op1Sym && op1Sym.getType()) { + symbol = findSymbolFromAlias(dottedExpr.operand2, context); + } + break; + + } + default: { + break; + + } + } + if(symbol) { + var symType = symbol.getType(); + if(symType) { + var members = symType.members; + if(members) { + context.members = members.publicMembers; + } + } + } + return symbol; + } + function preCollectImportTypes(ast, parent, context) { + var scopeChain = context.scopeChain; + var typeSymbol = null; + var modType = null; + var importDecl = ast; + var aliasedModSymbol = findSymbolFromAlias(importDecl.alias, { + topLevelScope: scopeChain, + members: null, + tcContext: context + }); + var isGlobal = context.scopeChain.container == context.checker.gloMod; + if(aliasedModSymbol) { + var aliasedModType = aliasedModSymbol.getType(); + if(aliasedModType) { + modType = aliasedModType; + } + } + typeSymbol = new TypeScript.TypeSymbol(importDecl.id.text, importDecl.id.minChar, importDecl.limChar - importDecl.minChar, context.checker.locationInfo.unitIndex, modType); + typeSymbol.aliasLink = importDecl; + if(context.scopeChain.moduleDecl) { + typeSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; + typeSymbol.declModule = context.scopeChain.moduleDecl; + } + typeSymbol.declAST = importDecl; + importDecl.id.sym = typeSymbol; + scopeChain.scope.enter(scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isGlobal, true, false); + scopeChain.scope.enter(scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isGlobal, false, false); + return true; + } + TypeScript.preCollectImportTypes = preCollectImportTypes; + function preCollectModuleTypes(ast, parent, context) { + var scopeChain = context.scopeChain; + var moduleDecl = ast; + var isAmbient = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.Ambient); + var isEnum = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsEnum); + var isGlobal = context.scopeChain.container == context.checker.gloMod; + var isExported = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.Exported); + var modName = (moduleDecl.name).text; + var isDynamic = TypeScript.isQuoted(modName); + var symbol = scopeChain.scope.findLocal(modName, false, false); + var typeSymbol = null; + var modType = null; + if((symbol == null) || (symbol.kind() != TypeScript.SymbolKind.Type)) { + if(modType == null) { + var enclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + var ambientEnclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + modType = new TypeScript.ModuleType(enclosedTypes, ambientEnclosedTypes); + if(isEnum) { + modType.typeFlags |= TypeScript.TypeFlags.IsEnum; + } + modType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + modType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + modType.setHasImplementation(); + } + typeSymbol = new TypeScript.TypeSymbol(modName, moduleDecl.name.minChar, modName.length, context.checker.locationInfo.unitIndex, modType); + typeSymbol.isDynamic = TypeScript.isQuoted(moduleDecl.prettyName); + if(context.scopeChain.moduleDecl) { + typeSymbol.declModule = context.scopeChain.moduleDecl; + } + typeSymbol.declAST = moduleDecl; + typeSymbol.prettyName = moduleDecl.prettyName; + scopeChain.scope.enter(scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, true, isAmbient); + scopeChain.scope.enter(scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, false, isAmbient); + modType.symbol = typeSymbol; + } else { + if(symbol && symbol.declAST && symbol.declAST.nodeType != TypeScript.NodeType.ModuleDeclaration) { + context.checker.errorReporter.simpleError(moduleDecl, "Conflicting symbol name for module '" + modName + "'"); + } + typeSymbol = symbol; + var publicEnclosedTypes = typeSymbol.type.getAllEnclosedTypes().publicMembers; + var publicEnclosedTypesTable = (publicEnclosedTypes == null) ? new TypeScript.StringHashTable() : publicEnclosedTypes; + var enclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(publicEnclosedTypesTable, new TypeScript.StringHashTable())); + var publicEnclosedAmbientTypes = typeSymbol.type.getAllAmbientEnclosedTypes().publicMembers; + var publicAmbientEnclosedTypesTable = (publicEnclosedAmbientTypes == null) ? new TypeScript.StringHashTable() : publicEnclosedAmbientTypes; + var ambientEnclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(publicAmbientEnclosedTypesTable, new TypeScript.StringHashTable())); + var publicMembers = typeSymbol.type.members.publicMembers; + var publicMembersTable = (publicMembers == null) ? new TypeScript.StringHashTable() : publicMembers; + var members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(publicMembersTable, new TypeScript.StringHashTable())); + var publicAmbientMembers = typeSymbol.type.ambientMembers.publicMembers; + var publicAmbientMembersTable = (publicAmbientMembers == null) ? new TypeScript.StringHashTable() : publicAmbientMembers; + var ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(publicAmbientMembersTable, new TypeScript.StringHashTable())); + modType = new TypeScript.ModuleType(enclosedTypes, ambientEnclosedTypes); + if(isEnum) { + modType.typeFlags |= TypeScript.TypeFlags.IsEnum; + } + modType.members = members; + modType.ambientMembers = ambientMembers; + modType.setHasImplementation(); + modType.symbol = typeSymbol; + typeSymbol.addLocation(moduleDecl.minChar); + typeSymbol.expansions.push(modType); + typeSymbol.expansionsDeclAST.push(moduleDecl); + } + if(context.scopeChain.moduleDecl) { + context.scopeChain.moduleDecl.recordNonInterface(); + } + if(isExported) { + typeSymbol.flags |= TypeScript.SymbolFlags.Exported; + } + if((context.scopeChain.moduleDecl) || (context.scopeChain.container == context.checker.gloMod)) { + typeSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; + } + moduleDecl.mod = modType; + TypeScript.pushTypeCollectionScope(typeSymbol, modType.members, modType.ambientMembers, modType.enclosedTypes, modType.ambientEnclosedTypes, context, null, null, moduleDecl); + return true; + } + TypeScript.preCollectModuleTypes = preCollectModuleTypes; + function preCollectClassTypes(ast, parent, context) { + var scopeChain = context.scopeChain; + var classDecl = ast; + var classType; + var instanceType; + var typeSymbol = null; + var className = (classDecl.name).text; + var alreadyInScope = false; + var isAmbient = TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Ambient); + var isExported = TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Exported); + var isGlobal = context.scopeChain.container == context.checker.gloMod; + var containerMod = scopeChain.container; + var foundValSymbol = false; + typeSymbol = scopeChain.scope.findLocal(className, false, true); + if(!typeSymbol) { + var valTypeSymbol = scopeChain.scope.findLocal(className, false, false); + if(valTypeSymbol && valTypeSymbol.isType() && valTypeSymbol.declAST && valTypeSymbol.declAST.nodeType == TypeScript.NodeType.FuncDecl && (valTypeSymbol.declAST).isSignature()) { + typeSymbol = valTypeSymbol; + foundValSymbol = true; + if(isExported) { + typeSymbol.flags |= TypeScript.SymbolFlags.Exported; + } + if(isAmbient) { + typeSymbol.flags |= TypeScript.SymbolFlags.Ambient; + } + context.scopeChain.scope.enter(context.scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, true, isAmbient); + } + } + if(typeSymbol && !foundValSymbol && (typeSymbol.declAST != classDecl)) { + typeSymbol = null; + } + if(typeSymbol == null) { + var valueSymbol = scopeChain.scope.findLocal(className, false, false); + classType = new TypeScript.Type(); + classType.setHasImplementation(); + instanceType = new TypeScript.Type(); + instanceType.setHasImplementation(); + classType.instanceType = instanceType; + classType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + classType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + addPrototypeField(classType, classDecl, context); + instanceType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + instanceType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + typeSymbol = new TypeScript.TypeSymbol(className, classDecl.name.minChar, className.length, context.checker.locationInfo.unitIndex, classType); + typeSymbol.declAST = classDecl; + typeSymbol.instanceType = instanceType; + classType.symbol = typeSymbol; + instanceType.symbol = typeSymbol; + if(context.scopeChain.moduleDecl) { + context.scopeChain.moduleDecl.recordNonInterface(); + typeSymbol.declModule = context.scopeChain.moduleDecl; + typeSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; + } + if(isExported) { + typeSymbol.flags |= TypeScript.SymbolFlags.Exported; + } + if(isAmbient) { + typeSymbol.flags |= TypeScript.SymbolFlags.Ambient; + } + ast.type = classType; + context.scopeChain.scope.enter(context.scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, true, isAmbient); + if(valueSymbol == null) { + context.scopeChain.scope.enter(context.scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, false, isAmbient); + } + } else { + classType = typeSymbol.type; + if(classType.instanceType == null) { + classType.instanceType = new TypeScript.Type(); + classType.instanceType.setHasImplementation(); + classType.instanceType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + classType.instanceType.symbol = classType.symbol; + classType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + classType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + } + instanceType = classType.instanceType; + ast.type = classType; + } + if(!classDecl.constructorDecl) { + if(typeSymbol && typeSymbol.declAST && typeSymbol.declAST.type && typeSymbol.declAST.type.call && !(typeSymbol.declAST).isOverload) { + context.checker.errorReporter.duplicateIdentifier(typeSymbol.declAST, typeSymbol.name); + } + createNewConstructGroupForType(classDecl.type); + } + classType.typeFlags |= TypeScript.TypeFlags.IsClass; + instanceType.typeFlags |= TypeScript.TypeFlags.IsClass; + getBases(instanceType, classDecl); + TypeScript.pushTypeCollectionScope(typeSymbol, instanceType.members, instanceType.ambientMembers, null, null, context, instanceType, classType, null); + return true; + } + TypeScript.preCollectClassTypes = preCollectClassTypes; + function preCollectInterfaceTypes(ast, parent, context) { + var scopeChain = context.scopeChain; + var interfaceDecl = ast; + var interfaceSymbol = null; + var interfaceType = null; + var isExported = TypeScript.hasFlag(interfaceDecl.varFlags, TypeScript.VarFlags.Exported); + var isGlobal = context.scopeChain.container == context.checker.gloMod; + var alreadyInScope = true; + alreadyInScope = false; + var interfaceName = (interfaceDecl.name).text; + interfaceSymbol = scopeChain.scope.findLocal(interfaceName, false, true); + if(interfaceSymbol == null) { + interfaceType = new TypeScript.Type(); + interfaceSymbol = new TypeScript.TypeSymbol(interfaceName, interfaceDecl.name.minChar, interfaceName.length, context.checker.locationInfo.unitIndex, interfaceType); + interfaceType.symbol = interfaceSymbol; + interfaceType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + interfaceType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + interfaceSymbol.declAST = interfaceDecl; + interfaceSymbol.declModule = context.scopeChain.moduleDecl; + } else { + alreadyInScope = true; + interfaceType = interfaceSymbol.type; + } + if(!interfaceType) { + interfaceType = context.checker.anyType; + } + ast.type = interfaceType; + getBases(interfaceType, interfaceDecl); + if(isExported) { + interfaceSymbol.flags |= TypeScript.SymbolFlags.Exported; + } + if(context.scopeChain.moduleDecl) { + interfaceSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; + } + if(!alreadyInScope) { + context.scopeChain.scope.enter(context.scopeChain.container, ast, interfaceSymbol, context.checker.errorReporter, isGlobal || isExported, true, false); + } + TypeScript.pushTypeCollectionScope(interfaceSymbol, interfaceType.members, interfaceType.ambientMembers, null, null, context, interfaceType, null, null); + return true; + } + TypeScript.preCollectInterfaceTypes = preCollectInterfaceTypes; + function preCollectArgDeclTypes(ast, parent, context) { + var scopeChain = context.scopeChain; + var argDecl = ast; + if(TypeScript.hasFlag(argDecl.varFlags, TypeScript.VarFlags.Public | TypeScript.VarFlags.Private)) { + var field = new TypeScript.ValueLocation(); + var isPrivate = TypeScript.hasFlag(argDecl.varFlags, TypeScript.VarFlags.Private); + var fieldSymbol = new TypeScript.FieldSymbol(argDecl.id.text, argDecl.id.minChar, context.checker.locationInfo.unitIndex, !TypeScript.hasFlag(argDecl.varFlags, TypeScript.VarFlags.Readonly), field); + fieldSymbol.transferVarFlags(argDecl.varFlags); + field.symbol = fieldSymbol; + fieldSymbol.declAST = ast; + argDecl.parameterPropertySym = fieldSymbol; + context.scopeChain.scope.enter(context.scopeChain.container, ast, fieldSymbol, context.checker.errorReporter, !isPrivate, false, false); + field.typeLink = TypeScript.getTypeLink(argDecl.typeExpr, context.checker, argDecl.init == null); + argDecl.sym = fieldSymbol; + } + return false; + } + TypeScript.preCollectArgDeclTypes = preCollectArgDeclTypes; + function preCollectVarDeclTypes(ast, parent, context) { + var scopeChain = context.scopeChain; + var varDecl = ast; + var isAmbient = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Ambient); + var isExported = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Exported); + var isGlobal = context.scopeChain.container == context.checker.gloMod; + var isProperty = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Property); + var isStatic = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static); + var isPrivate = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Private); + var isOptional = TypeScript.hasFlag(varDecl.id.flags, TypeScript.ASTFlags.OptionalName); + if(context.scopeChain.moduleDecl) { + context.scopeChain.moduleDecl.recordNonInterface(); + } + if(isProperty || isExported || (context.scopeChain.container == context.checker.gloMod) || context.scopeChain.moduleDecl) { + if(isAmbient) { + var existingSym = scopeChain.scope.findLocal(varDecl.id.text, false, false); + if(existingSym) { + varDecl.sym = existingSym; + return false; + } + } + if(varDecl.id == null) { + context.checker.errorReporter.simpleError(varDecl, "Expected variable identifier at this location"); + return false; + } + var field = new TypeScript.ValueLocation(); + var fieldSymbol = new TypeScript.FieldSymbol(varDecl.id.text, varDecl.id.minChar, context.checker.locationInfo.unitIndex, (varDecl.varFlags & TypeScript.VarFlags.Readonly) == TypeScript.VarFlags.None, field); + fieldSymbol.transferVarFlags(varDecl.varFlags); + if(isOptional) { + fieldSymbol.flags |= TypeScript.SymbolFlags.Optional; + } + field.symbol = fieldSymbol; + fieldSymbol.declAST = ast; + if((context.scopeChain.moduleDecl) || (context.scopeChain.container == context.checker.gloMod)) { + fieldSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; + fieldSymbol.declModule = context.scopeChain.moduleDecl; + } + if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Property) && isStatic && context.scopeChain.classType) { + if(!context.scopeChain.classType.members.publicMembers.add(varDecl.id.text, fieldSymbol)) { + context.checker.errorReporter.duplicateIdentifier(ast, fieldSymbol.name); + } + fieldSymbol.container = context.scopeChain.classType.symbol; + } else { + context.scopeChain.scope.enter(context.scopeChain.container, ast, fieldSymbol, context.checker.errorReporter, !isPrivate && (isProperty || isExported || isGlobal || isStatic), false, isAmbient); + } + if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Exported)) { + fieldSymbol.flags |= TypeScript.SymbolFlags.Exported; + } + field.typeLink = TypeScript.getTypeLink(varDecl.typeExpr, context.checker, varDecl.init == null); + varDecl.sym = fieldSymbol; + } + return false; + } + TypeScript.preCollectVarDeclTypes = preCollectVarDeclTypes; + function preCollectFuncDeclTypes(ast, parent, context) { + var scopeChain = context.scopeChain; + if(context.scopeChain.moduleDecl) { + context.scopeChain.moduleDecl.recordNonInterface(); + } + var funcDecl = ast; + var fgSym = null; + var nameText = funcDecl.getNameText(); + var isExported = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Exported | TypeScript.FncFlags.ClassPropertyMethodExported); + var isStatic = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static); + var isPrivate = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Private); + var isConstructor = funcDecl.isConstructMember() || funcDecl.isConstructor; + var containerSym = (((funcDecl.isMethod() && isStatic) || funcDecl.isAccessor()) && context.scopeChain.classType ? context.scopeChain.classType.symbol : context.scopeChain.container); + var containerScope = context.scopeChain.scope; + var isGlobal = containerSym == context.checker.gloMod; + var isOptional = funcDecl.name && TypeScript.hasFlag(funcDecl.name.flags, TypeScript.ASTFlags.OptionalName); + var go = false; + var foundSymbol = false; + if(isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { + containerSym = containerSym.container; + containerScope = scopeChain.previous.scope; + } + funcDecl.unitIndex = context.checker.locationInfo.unitIndex; + if(!funcDecl.isConstructor && containerSym && containerSym.declAST && containerSym.declAST.nodeType == TypeScript.NodeType.FuncDecl && (containerSym.declAST).isConstructor && !funcDecl.isMethod()) { + return go; + } + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Signature)) { + var instType = context.scopeChain.thisType; + if(nameText && nameText != "__missing") { + if(isStatic) { + fgSym = containerSym.type.members.allMembers.lookup(nameText); + } else { + fgSym = containerScope.findLocal(nameText, false, false); + if(fgSym == null) { + fgSym = containerScope.findLocal(nameText, false, true); + } + } + if(fgSym) { + foundSymbol = true; + if(!funcDecl.isSignature() && (TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Ambient) != TypeScript.hasFlag(fgSym.flags, TypeScript.SymbolFlags.Ambient))) { + fgSym = null; + } + } + } + if(fgSym == null) { + if(!(funcDecl.isSpecialFn())) { + fgSym = context.checker.createFunctionSignature(funcDecl, containerSym, containerScope, null, !foundSymbol).declAST.type.symbol; + } else { + fgSym = context.checker.createFunctionSignature(funcDecl, containerSym, containerScope, containerSym, false).declAST.type.symbol; + } + if(fgSym.declAST == null || !funcDecl.isSpecialFn()) { + fgSym.declAST = ast; + } + } else { + if((fgSym.kind() == TypeScript.SymbolKind.Type)) { + fgSym = context.checker.createFunctionSignature(funcDecl, containerSym, containerScope, fgSym, false).declAST.type.symbol; + } else { + context.checker.errorReporter.simpleError(funcDecl, "Function or method '" + funcDecl.name.actualText + "' already declared as a property"); + } + } + if(funcDecl.isSpecialFn() && !isStatic) { + funcDecl.type = instType ? instType : fgSym.type; + } else { + funcDecl.type = fgSym.type; + } + } else { + if(nameText) { + if(isStatic) { + fgSym = containerSym.type.members.allMembers.lookup(nameText); + } else { + if(funcDecl.isConstructor && context.scopeChain.previous) { + fgSym = context.scopeChain.previous.scope.findLocal(nameText, false, false); + } + if(fgSym == null) { + fgSym = containerScope.findLocal(nameText, false, false); + } + } + if(fgSym) { + foundSymbol = true; + if(!isConstructor && fgSym.declAST.nodeType == TypeScript.NodeType.FuncDecl && !(fgSym.declAST).isAccessor() && !(fgSym.declAST).isSignature()) { + fgSym = null; + foundSymbol = false; + } + } + } + if(fgSym && !fgSym.isAccessor() && fgSym.type && fgSym.type.construct && fgSym.type.construct.signatures != [] && (fgSym.type.construct.signatures[0].declAST == null || !TypeScript.hasFlag(fgSym.type.construct.signatures[0].declAST.fncFlags, TypeScript.FncFlags.Ambient)) && !funcDecl.isConstructor) { + context.checker.errorReporter.simpleError(funcDecl, "Functions may not have class overloads"); + } + if(fgSym && !(fgSym.kind() == TypeScript.SymbolKind.Type) && funcDecl.isMethod() && !funcDecl.isAccessor() && !funcDecl.isConstructor) { + context.checker.errorReporter.simpleError(funcDecl, "Function or method '" + funcDecl.name.actualText + "' already declared as a property"); + fgSym.type = context.checker.anyType; + } + var sig = context.checker.createFunctionSignature(funcDecl, containerSym, containerScope, fgSym, !foundSymbol); + if(((!fgSym || fgSym.declAST.nodeType != TypeScript.NodeType.FuncDecl) && funcDecl.isAccessor()) || (fgSym && fgSym.isAccessor())) { + funcDecl.accessorSymbol = context.checker.createAccessorSymbol(funcDecl, fgSym, containerSym.type, (funcDecl.isMethod() && isStatic), true, containerScope, containerSym); + } + funcDecl.type.symbol.declAST = ast; + if(funcDecl.isConstructor) { + go = true; + } + ; ; + } + if(isExported) { + if(funcDecl.type.call) { + funcDecl.type.symbol.flags |= TypeScript.SymbolFlags.Exported; + } + if(fgSym && !fgSym.isAccessor() && fgSym.kind() == TypeScript.SymbolKind.Type && fgSym.type.call) { + fgSym.flags |= TypeScript.SymbolFlags.Exported; + } + } + if(context.scopeChain.moduleDecl && !funcDecl.isSpecialFn()) { + funcDecl.type.symbol.flags |= TypeScript.SymbolFlags.ModuleMember; + funcDecl.type.symbol.declModule = context.scopeChain.moduleDecl; + } + if(fgSym && isOptional) { + fgSym.flags |= TypeScript.SymbolFlags.Optional; + } + return go; + } + TypeScript.preCollectFuncDeclTypes = preCollectFuncDeclTypes; + function preCollectTypes(ast, parent, walker) { + var context = walker.state; + var go = false; + var scopeChain = context.scopeChain; + if(ast.nodeType == TypeScript.NodeType.Script) { + var script = ast; + context.script = script; + go = true; + } else { + if(ast.nodeType == TypeScript.NodeType.List) { + go = true; + } else { + if(ast.nodeType == TypeScript.NodeType.ImportDeclaration) { + go = preCollectImportTypes(ast, parent, context); + } else { + if(ast.nodeType == TypeScript.NodeType.With) { + go = false; + } else { + if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { + go = preCollectModuleTypes(ast, parent, context); + } else { + if(ast.nodeType == TypeScript.NodeType.ClassDeclaration) { + go = preCollectClassTypes(ast, parent, context); + } else { + if(ast.nodeType == TypeScript.NodeType.Block) { + go = true; + } else { + if(ast.nodeType == TypeScript.NodeType.InterfaceDeclaration) { + go = preCollectInterfaceTypes(ast, parent, context); + } else { + if(ast.nodeType == TypeScript.NodeType.ArgDecl) { + go = preCollectArgDeclTypes(ast, parent, context); + } else { + if(ast.nodeType == TypeScript.NodeType.VarDecl) { + go = preCollectVarDeclTypes(ast, parent, context); + } else { + if(ast.nodeType == TypeScript.NodeType.FuncDecl) { + go = preCollectFuncDeclTypes(ast, parent, context); + } else { + if(ast.isStatementOrExpression() && context.scopeChain.moduleDecl) { + context.scopeChain.moduleDecl.recordNonInterface(); + } + } + } + } + } + } + } + } + } + } + } + } + walker.options.goChildren = go; + return ast; + } + TypeScript.preCollectTypes = preCollectTypes; + function postCollectTypes(ast, parent, walker) { + var context = walker.state; + if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { + TypeScript.popTypeCollectionScope(context); + } else { + if(ast.nodeType == TypeScript.NodeType.ClassDeclaration) { + TypeScript.popTypeCollectionScope(context); + } else { + if(ast.nodeType == TypeScript.NodeType.InterfaceDeclaration) { + TypeScript.popTypeCollectionScope(context); + } + } + } + return ast; + } + TypeScript.postCollectTypes = postCollectTypes; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ScopeChain = (function () { + function ScopeChain(container, previous, scope) { + this.container = container; + this.previous = previous; + this.scope = scope; + } + return ScopeChain; + })(); + TypeScript.ScopeChain = ScopeChain; + var BBUseDefInfo = (function () { + function BBUseDefInfo(bb) { + this.bb = bb; + this.defsBySymbol = new Array(); + this.useIndexBySymbol = new Array(); + } + BBUseDefInfo.prototype.updateTop = function () { + var temp = new BitVector(this.top.bitCount); + for(var i = 0, succLen = this.bb.successors.length; i < succLen; i++) { + var succ = this.bb.successors[i]; + if(succ.useDef) { + temp.union(succ.useDef.top); + } + } + temp.difference(this.kill); + temp.union(this.gen); + var changed = temp.notEq(this.top); + this.top = temp; + return changed; + }; + BBUseDefInfo.prototype.initialize = function (useDefContext) { + var _this = this; + var defSym = function (sym, context) { + if(context.isLocalSym(sym)) { + var index = context.getSymbolIndex(sym); + _this.useIndexBySymbol[index] = new Array(); + _this.defsBySymbol[index] = true; + } + }; + var useSym = function (sym, context, ast) { + if(context.isLocalSym(sym)) { + var symIndex = context.getSymbolIndex(sym); + if(_this.useIndexBySymbol[symIndex] == undefined) { + _this.useIndexBySymbol[symIndex] = new Array(); + } + var symUses = _this.useIndexBySymbol[symIndex]; + var astIndex = context.getUseIndex(ast); + context.addUse(symIndex, astIndex); + symUses.push(astIndex); + } + }; + function initUseDefPre(cur, parent, walker) { + var context = walker.state; + if(cur == null) { + cur = null; + } + if(cur.nodeType == TypeScript.NodeType.VarDecl) { + var varDecl = cur; + if(varDecl.init || TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.AutoInit)) { + defSym(varDecl.sym, context); + } + } else { + if(cur.nodeType == TypeScript.NodeType.Name) { + if(parent) { + if(parent.nodeType == TypeScript.NodeType.Asg) { + var asg = parent; + if(asg.operand1 == cur) { + return cur; + } + } else { + if(parent.nodeType == TypeScript.NodeType.VarDecl) { + var parentDecl = parent; + if(parentDecl.id == cur) { + return cur; + } + } + } + } + var id = cur; + useSym(id.sym, context, cur); + } else { + if((cur.nodeType >= TypeScript.NodeType.Asg) && (cur.nodeType <= TypeScript.NodeType.LastAsg)) { + var asg = cur; + if(asg.operand1 && (asg.operand1.nodeType == TypeScript.NodeType.Name)) { + var id = asg.operand1; + defSym(id.sym, context); + } + } else { + if(cur.nodeType == TypeScript.NodeType.FuncDecl) { + walker.options.goChildren = false; + } + } + } + } + return cur; + } + var options = new TypeScript.AstWalkOptions(); + options.reverseSiblings = true; + TypeScript.getAstWalkerFactory().walk(this.bb.content, initUseDefPre, null, options, useDefContext); + }; + BBUseDefInfo.prototype.initializeGen = function (useDefContext) { + var symbolLen = this.useIndexBySymbol.length; + var bitCount = useDefContext.uses.length; + this.gen = new BitVector(bitCount); + for(var s = 0; s < symbolLen; s++) { + var symUses = this.useIndexBySymbol[s]; + if((symUses != undefined) && (symUses.length > 0)) { + for(var u = 0, uLen = symUses.length; u < uLen; u++) { + this.gen.set(symUses[u], true); + } + } + } + this.top = this.gen; + }; + BBUseDefInfo.prototype.initializeKill = function (useDefContext) { + this.kill = new BitVector(this.gen.bitCount); + for(var s = 0, symbolLen = this.defsBySymbol.length; s < symbolLen; s++) { + if(this.defsBySymbol[s]) { + var globalSymUses = useDefContext.useIndexBySymbol[s]; + if(globalSymUses) { + for(var u = 0, useLen = globalSymUses.length; u < useLen; u++) { + this.kill.set(globalSymUses[u], true); + } + } + } + } + }; + return BBUseDefInfo; + })(); + TypeScript.BBUseDefInfo = BBUseDefInfo; + var UseDefContext = (function () { + function UseDefContext() { + this.useIndexBySymbol = new Array(); + this.uses = new Array(); + this.symbols = new Array(); + this.symbolMap = new TypeScript.StringHashTable(); + this.symbolCount = 0; + } + UseDefContext.prototype.getSymbolIndex = function (sym) { + var name = sym.name; + var index = (this.symbolMap.lookup(name)); + if(index == null) { + index = this.symbolCount++; + this.symbols[index] = sym; + this.symbolMap.add(name, index); + } + return index; + }; + UseDefContext.prototype.addUse = function (symIndex, astIndex) { + var useBySym = this.useIndexBySymbol[symIndex]; + if(useBySym == undefined) { + useBySym = new Array(); + this.useIndexBySymbol[symIndex] = useBySym; + } + useBySym[useBySym.length] = astIndex; + }; + UseDefContext.prototype.getUseIndex = function (ast) { + this.uses[this.uses.length] = ast; + return this.uses.length - 1; + }; + UseDefContext.prototype.isLocalSym = function (sym) { + return (sym && (sym.container == this.func) && (sym.kind() == TypeScript.SymbolKind.Variable)); + }; + UseDefContext.prototype.killSymbol = function (sym, bbUses) { + var index = this.symbolMap.lookup(sym.name); + var usesOfSym = this.useIndexBySymbol[index]; + for(var k = 0, len = usesOfSym.length; k < len; k++) { + bbUses.set(usesOfSym[k], true); + } + }; + return UseDefContext; + })(); + TypeScript.UseDefContext = UseDefContext; + var BitVector = (function () { + function BitVector(bitCount) { + this.bitCount = bitCount; + this.firstBits = 0; + this.restOfBits = null; + if(this.bitCount > BitVector.packBits) { + this.restOfBits = new Array(); + var len = Math.floor(this.bitCount / BitVector.packBits); + for(var i = 0; i < len; i++) { + this.restOfBits[i] = 0; + } + } + } + BitVector.packBits = 30; + BitVector.prototype.set = function (bitIndex, value) { + if(bitIndex < BitVector.packBits) { + if(value) { + this.firstBits |= (1 << bitIndex); + } else { + this.firstBits &= (~(1 << bitIndex)); + } + } else { + var offset = Math.floor(bitIndex / BitVector.packBits) - 1; + var localIndex = bitIndex % BitVector.packBits; + if(value) { + this.restOfBits[offset] |= (1 << localIndex); + } else { + this.restOfBits[offset] &= (~(1 << localIndex)); + } + } + }; + BitVector.prototype.map = function (fn) { + var k; + for(k = 0; k < BitVector.packBits; k++) { + if(k == this.bitCount) { + return; + } + if(((1 << k) & this.firstBits) != 0) { + fn(k); + } + } + if(this.restOfBits) { + var len; + var cumu = BitVector.packBits; + for(k = 0 , len = this.restOfBits.length; k < len; k++) { + var myBits = this.restOfBits[k]; + for(var j = 0; j < BitVector.packBits; j++) { + if(((1 << j) & myBits) != 0) { + fn(cumu); + } + cumu++; + if(cumu == this.bitCount) { + return; + } + } + } + } + }; + BitVector.prototype.union = function (b) { + this.firstBits |= b.firstBits; + if(this.restOfBits) { + for(var k = 0, len = this.restOfBits.length; k < len; k++) { + var myBits = this.restOfBits[k]; + var bBits = b.restOfBits[k]; + this.restOfBits[k] = myBits | bBits; + } + } + }; + BitVector.prototype.intersection = function (b) { + this.firstBits &= b.firstBits; + if(this.restOfBits) { + for(var k = 0, len = this.restOfBits.length; k < len; k++) { + var myBits = this.restOfBits[k]; + var bBits = b.restOfBits[k]; + this.restOfBits[k] = myBits & bBits; + } + } + }; + BitVector.prototype.notEq = function (b) { + if(this.firstBits != b.firstBits) { + return true; + } + if(this.restOfBits) { + for(var k = 0, len = this.restOfBits.length; k < len; k++) { + var myBits = this.restOfBits[k]; + var bBits = b.restOfBits[k]; + if(myBits != bBits) { + return true; + } + } + } + return false; + }; + BitVector.prototype.difference = function (b) { + var oldFirstBits = this.firstBits; + this.firstBits &= (~b.firstBits); + if(this.restOfBits) { + for(var k = 0, len = this.restOfBits.length; k < len; k++) { + var myBits = this.restOfBits[k]; + var bBits = b.restOfBits[k]; + this.restOfBits[k] &= (~bBits); + } + } + }; + return BitVector; + })(); + TypeScript.BitVector = BitVector; + var BasicBlock = (function () { + function BasicBlock() { + this.predecessors = new Array(); + this.index = -1; + this.markValue = 0; + this.successors = new Array(); + this.useDef = null; + this.content = new TypeScript.ASTList(); + } + BasicBlock.prototype.marked = function (markBase) { + return this.markValue > markBase; + }; + BasicBlock.prototype.mark = function () { + this.markValue++; + }; + BasicBlock.prototype.addSuccessor = function (successor) { + this.successors[this.successors.length] = successor; + successor.predecessors[successor.predecessors.length] = this; + }; + return BasicBlock; + })(); + TypeScript.BasicBlock = BasicBlock; + var ControlFlowContext = (function () { + function ControlFlowContext(current, exit) { + this.current = current; + this.exit = exit; + this.entry = null; + this.unreachable = null; + this.noContinuation = false; + this.statementStack = new Array(); + this.currentSwitch = new Array(); + this.markBase = 0; + this.linearBBs = new Array(); + this.entry = this.current; + } + ControlFlowContext.prototype.walk = function (ast, parent) { + return this.walker.walk(ast, parent); + }; + ControlFlowContext.prototype.pushSwitch = function (bb) { + this.currentSwitch.push(bb); + }; + ControlFlowContext.prototype.popSwitch = function () { + return this.currentSwitch.pop(); + }; + ControlFlowContext.prototype.reportUnreachable = function (er) { + if(this.unreachable && (this.unreachable.length > 0)) { + var len = this.unreachable.length; + for(var i = 0; i < len; i++) { + var unreachableAST = this.unreachable[i]; + if(unreachableAST.nodeType != TypeScript.NodeType.EndCode) { + er.simpleError(unreachableAST, "unreachable code"); + } + } + } + }; + ControlFlowContext.prototype.printAST = function (ast, outfile) { + var printContext = new TypeScript.PrintContext(outfile, null); + printContext.increaseIndent(); + TypeScript.getAstWalkerFactory().walk(ast, TypeScript.prePrintAST, TypeScript.postPrintAST, null, printContext); + printContext.decreaseIndent(); + }; + ControlFlowContext.prototype.printBlockContent = function (bb, outfile) { + var content = bb.content; + for(var i = 0, len = content.members.length; i < len; i++) { + var ast = content.members[i]; + this.printAST(ast, outfile); + } + }; + ControlFlowContext.prototype.bfs = function (nodeFunc, edgeFunc, preEdges, postEdges) { + var markValue = this.markBase++; + var q = new Array(); + q[q.length] = this.entry; + while(q.length > 0) { + var bb = q.pop(); + if(!(bb.marked(markValue))) { + bb.mark(); + if(nodeFunc) { + nodeFunc(bb); + } + var succLen = bb.successors.length; + if(succLen > 0) { + if(preEdges) { + preEdges(); + } + for(var j = succLen - 1; j >= 0; j--) { + var successor = bb.successors[j]; + if(!(successor.marked(this.markBase))) { + if(edgeFunc) { + edgeFunc(bb, successor); + } + q[q.length] = successor; + } + } + if(postEdges) { + postEdges(); + } + } + } + } + }; + ControlFlowContext.prototype.useDef = function (er, funcSym) { + var _this = this; + var useDefContext = new UseDefContext(); + useDefContext.func = funcSym; + var useDefInit = function (bb) { + bb.useDef = new BBUseDefInfo(bb); + bb.useDef.initialize(useDefContext); + _this.linearBBs[_this.linearBBs.length] = bb; + }; + this.bfs(useDefInit, null, null, null); + var i, bbLen; + for(i = 0 , bbLen = this.linearBBs.length; i < bbLen; i++) { + this.linearBBs[i].useDef.initializeGen(useDefContext); + this.linearBBs[i].useDef.initializeKill(useDefContext); + } + var changed = true; + while(changed) { + changed = false; + for(i = 0; i < bbLen; i++) { + changed = this.linearBBs[i].useDef.updateTop() || changed; + } + } + var top = this.entry.useDef.top; + top.map(function (index) { + var ast = useDefContext.uses[index]; + er.simpleError(ast, "use of variable '" + ast.actualText + "' that is not definitely assigned"); + }); + }; + ControlFlowContext.prototype.print = function (outfile) { + var _this = this; + var index = 0; + var node = function (bb) { + if(bb.index < 0) { + bb.index = index++; + } + if(bb == _this.exit) { + outfile.WriteLine("Exit block with index " + bb.index); + } else { + outfile.WriteLine("Basic block with index " + bb.index); + _this.printBlockContent(bb, outfile); + } + }; + function preEdges() { + outfile.Write(" Branches to "); + } + function postEdges() { + outfile.WriteLine(""); + } + function edge(node1, node2) { + if(node2.index < 0) { + node2.index = index++; + } + outfile.Write(node2.index + " "); + } + this.bfs(node, edge, preEdges, postEdges); + if(this.unreachable != null) { + for(var i = 0, len = this.unreachable.length; i < len; i++) { + outfile.WriteLine("Unreachable basic block ..."); + this.printAST(this.unreachable[i], outfile); + } + } + }; + ControlFlowContext.prototype.pushStatement = function (stmt, continueBB, breakBB) { + this.statementStack.push({ + stmt: stmt, + continueBB: continueBB, + breakBB: breakBB + }); + }; + ControlFlowContext.prototype.popStatement = function () { + return this.statementStack.pop(); + }; + ControlFlowContext.prototype.returnStmt = function () { + this.current.addSuccessor(this.exit); + this.setUnreachable(); + }; + ControlFlowContext.prototype.setUnreachable = function () { + this.current = null; + this.noContinuation = true; + }; + ControlFlowContext.prototype.addUnreachable = function (ast) { + if(this.unreachable === null) { + this.unreachable = new Array(); + } + this.unreachable[this.unreachable.length] = ast; + }; + ControlFlowContext.prototype.unconditionalBranch = function (target, isContinue) { + var targetBB = null; + for(var i = 0, len = this.statementStack.length; i < len; i++) { + var targetInfo = this.statementStack[i]; + if(targetInfo.stmt == target) { + if(isContinue) { + targetBB = targetInfo.continueBB; + } else { + targetBB = targetInfo.breakBB; + } + break; + } + } + if(targetBB) { + this.current.addSuccessor(targetBB); + } + this.setUnreachable(); + }; + ControlFlowContext.prototype.addContent = function (ast) { + if(this.current) { + this.current.content.append(ast); + } + }; + return ControlFlowContext; + })(); + TypeScript.ControlFlowContext = ControlFlowContext; + var ResolutionDataCache = (function () { + function ResolutionDataCache() { + this.cacheSize = 16; + this.rdCache = []; + this.nextUp = 0; + for(var i = 0; i < this.cacheSize; i++) { + this.rdCache[i] = { + actuals: new Array(), + exactCandidates: new Array(), + conversionCandidates: new Array(), + id: i + }; + } + } + ResolutionDataCache.prototype.getResolutionData = function () { + var rd = null; + if(this.nextUp < this.cacheSize) { + rd = this.rdCache[this.nextUp]; + } + if(rd == null) { + this.cacheSize++; + rd = { + actuals: new Array(), + exactCandidates: new Array(), + conversionCandidates: new Array(), + id: this.cacheSize + }; + this.rdCache[this.cacheSize] = rd; + } + this.nextUp++; + return rd; + }; + ResolutionDataCache.prototype.returnResolutionData = function (rd) { + rd.actuals.length = 0; + rd.exactCandidates.length = 0; + rd.conversionCandidates.length = 0; + this.nextUp = rd.id; + }; + return ResolutionDataCache; + })(); + TypeScript.ResolutionDataCache = ResolutionDataCache; + var TypeFlow = (function () { + function TypeFlow(logger, initScope, parser, checker) { + this.logger = logger; + this.initScope = initScope; + this.parser = parser; + this.checker = checker; + this.thisFnc = null; + this.thisClassNode = null; + this.enclosingFncIsMethod = false; + this.arrayInterfaceType = null; + this.stringInterfaceType = null; + this.objectInterfaceType = null; + this.functionInterfaceType = null; + this.numberInterfaceType = null; + this.booleanInterfaceType = null; + this.iargumentsInterfaceType = null; + this.currentScript = null; + this.inImportTypeCheck = false; + this.inTypeRefTypeCheck = false; + this.inArrayElementTypeCheck = false; + this.resolutionDataCache = new ResolutionDataCache(); + this.nestingLevel = 0; + this.inSuperCall = false; + this.checker.typeFlow = this; + this.scope = this.initScope; + this.globalScope = this.initScope; + this.doubleType = this.checker.numberType; + this.booleanType = this.checker.booleanType; + this.stringType = this.checker.stringType; + this.anyType = this.checker.anyType; + this.regexType = this.anyType; + this.nullType = this.checker.nullType; + this.voidType = this.checker.voidType; + this.arrayAnyType = this.checker.makeArrayType(this.anyType); + } + TypeFlow.prototype.initLibs = function () { + var arraySym = this.globalScope.find("Array", false, true); + if(arraySym && (arraySym.kind() == TypeScript.SymbolKind.Type)) { + this.arrayInterfaceType = (arraySym).type; + } + var stringSym = this.globalScope.find("String", false, true); + if(stringSym && (stringSym.kind() == TypeScript.SymbolKind.Type)) { + this.stringInterfaceType = (stringSym).type; + } + var objectSym = this.globalScope.find("Object", false, true); + if(objectSym && (objectSym.kind() == TypeScript.SymbolKind.Type)) { + this.objectInterfaceType = (objectSym).type; + } + var fnSym = this.globalScope.find("Function", false, true); + if(fnSym && (fnSym.kind() == TypeScript.SymbolKind.Type)) { + this.functionInterfaceType = (fnSym).type; + } + var numberSym = this.globalScope.find("Number", false, true); + if(numberSym && (numberSym.kind() == TypeScript.SymbolKind.Type)) { + this.numberInterfaceType = (numberSym).type; + } + var booleanSym = this.globalScope.find("Boolean", false, true); + if(booleanSym && (booleanSym.kind() == TypeScript.SymbolKind.Type)) { + this.booleanInterfaceType = (booleanSym).type; + } + var regexSym = this.globalScope.find("RegExp", false, true); + if(regexSym && (regexSym.kind() == TypeScript.SymbolKind.Type)) { + this.regexType = (regexSym).type; + } + }; + TypeFlow.prototype.cast = function (ast, type) { + return this.castWithCoercion(ast, type, true, false); + }; + TypeFlow.prototype.castWithCoercion = function (ast, type, applyCoercion, typeAssertion) { + var comparisonInfo = new TypeScript.TypeComparisonInfo(); + if(this.checker.sourceIsAssignableToTarget(ast.type, type, comparisonInfo) || (typeAssertion && this.checker.sourceIsAssignableToTarget(type, ast.type, comparisonInfo))) { + if(applyCoercion) { + if(type == null) { + ast.type = this.anyType; + } else { + if(type.isClass()) { + ast.type = type.instanceType; + } else { + ast.type = type; + } + } + } + return ast; + } else { + this.checker.errorReporter.incompatibleTypes(ast, ast.type, type, null, this.scope, comparisonInfo); + return ast; + } + }; + TypeFlow.prototype.inScopeTypeCheck = function (ast, enclosingScope) { + var prevScope = this.scope; + this.scope = enclosingScope; + var svThisFnc = this.thisFnc; + var svThisType = this.thisType; + var svThisClassNode = this.thisClassNode; + var svCurrentModDecl = this.checker.currentModDecl; + var prevMethodStatus = this.enclosingFncIsMethod; + var container = this.scope.container; + var fnc = null; + while(container) { + if(container.kind() == TypeScript.SymbolKind.Type) { + var typeSym = container; + var type = typeSym.type; + if(type.call) { + if(fnc == null) { + this.enclosingFncIsMethod = typeSym.isMethod; + fnc = container.declAST; + } + } + if(type.isClass()) { + this.thisType = type.instanceType; + if(typeSym.declAST && (typeSym.declAST.nodeType == TypeScript.NodeType.ClassDeclaration)) { + this.thisClassNode = typeSym.declAST; + } + break; + } + if(type.isModuleType()) { + this.checker.currentModDecl = typeSym.declAST; + break; + } + } + container = container.container; + } + this.thisFnc = fnc; + var updated = this.typeCheck(ast); + this.thisFnc = svThisFnc; + this.thisType = svThisType; + this.thisClassNode = svThisClassNode; + this.checker.currentModDecl = svCurrentModDecl; + this.enclosingFncIsMethod = prevMethodStatus; + this.scope = prevScope; + return updated; + }; + TypeFlow.prototype.typeCheck = function (ast) { + if(ast) { + return ast.typeCheck(this); + } else { + return null; + } + }; + TypeFlow.prototype.inScopeTypeCheckDecl = function (ast) { + if(ast.nodeType == TypeScript.NodeType.VarDecl || ast.nodeType == TypeScript.NodeType.ArgDecl) { + this.inScopeTypeCheckBoundDecl(ast); + } else { + if(ast.nodeType == TypeScript.NodeType.FuncDecl) { + var funcDecl = ast; + if(funcDecl.isAccessor()) { + this.typeCheckFunction(funcDecl); + } + } + } + }; + TypeFlow.prototype.inScopeTypeCheckBoundDecl = function (varDecl) { + var sym = varDecl.sym; + var svThisFnc = this.thisFnc; + var svThisType = this.thisType; + var prevMethodStatus = this.enclosingFncIsMethod; + var prevLocationInfo = this.checker.locationInfo; + if(sym && sym.container) { + var instanceScope = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.ClassConstructorProperty) ? sym.container.getType().constructorScope : sym.container.instanceScope(); + if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Property) && sym.container.declAST.nodeType == TypeScript.NodeType.FuncDecl) { + this.thisFnc = sym.container.declAST; + } + if(instanceScope) { + var prevScope = this.scope; + this.scope = instanceScope; + var container = sym.container; + if(this.checker.units && (sym.unitIndex >= 0) && (sym.unitIndex < this.checker.units.length)) { + this.checker.locationInfo = this.checker.units[sym.unitIndex]; + } else { + this.checker.locationInfo = TypeScript.unknownLocationInfo; + } + while(container) { + if(container.kind() == TypeScript.SymbolKind.Type) { + var typeSym = container; + var type = typeSym.type; + if(type.call) { + this.enclosingFncIsMethod = typeSym.isMethod; + } + if(type.isClass()) { + this.thisType = type.instanceType; + break; + } + } + container = container.container; + } + this.typeCheckBoundDecl(varDecl); + this.scope = prevScope; + } + } + this.thisFnc = svThisFnc; + this.thisType = svThisType; + this.checker.locationInfo = prevLocationInfo; + this.enclosingFncIsMethod = prevMethodStatus; + }; + TypeFlow.prototype.resolveBoundDecl = function (varDecl) { + if(varDecl.typeExpr) { + if(varDecl.typeExpr.type == null || (varDecl.typeExpr.type && varDecl.typeExpr.type == this.anyType && this.scope) || varDecl.typeExpr.type.symbol == null || !this.checker.typeStatusIsFinished(varDecl.typeExpr.type.symbol.typeCheckStatus)) { + this.typeCheck(varDecl.typeExpr); + } + varDecl.type = varDecl.typeExpr.type; + if(varDecl.sym) { + varDecl.sym.setType(varDecl.type); + } + } else { + if(varDecl.init == null) { + if(this.checker.styleSettings.implicitAny) { + this.checker.errorReporter.styleError(varDecl, "type implicitly set to 'any'"); + } + varDecl.type = this.anyType; + if(varDecl.sym) { + if(varDecl.sym.isType()) { + var tsym = varDecl.sym; + if(tsym.isMethod) { + this.checker.errorReporter.simpleError(varDecl, "Cannot bind method group to variable. (Did you mean to use 'declare function' instead of 'declare var'?)"); + return; + } else { + this.checker.errorReporter.simpleError(varDecl, "Cannot bind type to variable"); + return; + } + } + varDecl.sym.setType(varDecl.type); + } + } + } + }; + TypeFlow.prototype.typeCheckBoundDecl = function (varDecl) { + var _this = this; + var infSym = varDecl.sym; + if(infSym == null) { + if(varDecl.init) { + varDecl.init = this.typeCheck(varDecl.init); + varDecl.type = this.checker.widenType(varDecl.init.type); + } else { + if(this.checker.styleSettings.implicitAny) { + this.checker.errorReporter.styleError(varDecl, "type implicitly set to 'any'"); + } + varDecl.type = this.anyType; + } + } else { + if(infSym.typeCheckStatus == TypeScript.TypeCheckStatus.Started) { + if(this.checker.styleSettings.implicitAny) { + this.checker.errorReporter.styleError(varDecl, "type implicitly set to 'any'"); + } + varDecl.type = this.anyType; + infSym.setType(this.anyType); + } else { + if(infSym.typeCheckStatus == TypeScript.TypeCheckStatus.NotStarted) { + infSym.typeCheckStatus = TypeScript.TypeCheckStatus.Started; + this.checker.addStartedPTO(infSym); + var resolved = false; + if(varDecl.type == null) { + if(varDecl.typeExpr) { + this.resolveBoundDecl(varDecl); + resolved = true; + varDecl.type = varDecl.typeExpr.type; + infSym.typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); + } + } + if(varDecl.init) { + var isLocalStatic = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.LocalStatic); + var prevScope = this.scope; + var applyTargetType = !varDecl.init.isParenthesized; + if(isLocalStatic) { + this.scope = varDecl.sym.container.getType().memberScope; + } + if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Property) && this.thisClassNode) { + TypeScript.getAstWalkerFactory().walk(varDecl.init, function (ast, parent, walker) { + if(ast && ast.nodeType == TypeScript.NodeType.FuncDecl) { + if(TypeScript.hasFlag((ast).fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { + (ast).fncFlags |= TypeScript.FncFlags.IsPropertyBound; + } + walker.options.goChildren = false; + } + return ast; + }); + } + this.checker.typeCheckWithContextualType(varDecl.type, this.checker.inProvisionalTypecheckMode(), applyTargetType, varDecl.init); + this.scope = prevScope; + if(varDecl.type) { + var preserveScope = false; + var preservedContainedScope = null; + if(varDecl.init.type) { + preservedContainedScope = varDecl.init.type.containedScope; + preserveScope = true; + if(varDecl.init.type == this.voidType) { + this.checker.errorReporter.simpleError(varDecl, "Cannot assign type 'void' to variable '" + varDecl.id.actualText + "'"); + } + } + varDecl.init = this.castWithCoercion(varDecl.init, varDecl.type, applyTargetType && !this.checker.inProvisionalTypecheckMode(), false); + if(preserveScope && varDecl.init.type.containedScope == null) { + varDecl.init.type.containedScope = preservedContainedScope; + } + } else { + varDecl.type = this.checker.widenType(varDecl.init.type); + if(varDecl.type == this.voidType) { + this.checker.errorReporter.simpleError(varDecl, "Cannot assign type 'void' to variable '" + varDecl.id.actualText + "'"); + varDecl.type = this.anyType; + } + } + infSym.setType(varDecl.type); + } else { + if(!resolved) { + this.resolveBoundDecl(varDecl); + } + } + infSym.typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); + } else { + if(this.checker.typeStatusIsFinished(infSym.typeCheckStatus) && (infSym.declAST != varDecl)) { + if(varDecl.init) { + varDecl.init = this.typeCheck(varDecl.init); + varDecl.type = infSym.getType(); + varDecl.init = this.cast(varDecl.init, varDecl.type); + } + } + } + } + } + if(varDecl.id && varDecl.sym) { + varDecl.id.sym = varDecl.sym; + } + if(varDecl.sym && varDecl.sym.container) { + this.checkTypePrivacy(varDecl.sym.getType(), varDecl.sym, function (typeName, isModuleName) { + return _this.varPrivacyErrorReporter(varDecl, typeName, isModuleName); + }); + } + return varDecl; + }; + TypeFlow.prototype.varPrivacyErrorReporter = function (varDecl, typeName, isModuleName) { + var typestring = ""; + if(isModuleName) { + var quotestring = ""; + if(!TypeScript.isQuoted(typeName)) { + quotestring = "'"; + } + typestring = " is using inaccessible module " + quotestring + typeName + quotestring; + } else { + typestring = " has or is using private type '" + typeName + "'"; + } + if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Public)) { + if(varDecl.sym.container.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) { + this.checker.errorReporter.simpleError(varDecl, "property '" + varDecl.sym.name + "' of exported interface" + typestring); + } else { + this.checker.errorReporter.simpleError(varDecl, "public member '" + varDecl.sym.name + "' of exported class" + typestring); + } + } else { + this.checker.errorReporter.simpleError(varDecl, "exported variable '" + varDecl.sym.name + "'" + typestring); + } + }; + TypeFlow.prototype.typeCheckSuper = function (ast) { + if(this.thisType && (this.enclosingFncIsMethod && !this.thisFnc.isStatic()) && this.thisType.baseClass()) { + ast.type = this.thisType.baseClass(); + } else { + if(!this.enclosingFncIsMethod && this.thisType && this.thisType.baseClass() && this.thisFnc && TypeScript.hasFlag(this.thisFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { + var enclosingFnc = this.thisFnc.enclosingFnc; + while(TypeScript.hasFlag(enclosingFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { + enclosingFnc = enclosingFnc.enclosingFnc; + } + if(enclosingFnc && (enclosingFnc.isMethod() || enclosingFnc.isConstructor) && !enclosingFnc.isStatic()) { + ast.type = this.thisType.baseClass(); + enclosingFnc.setHasSuperReferenceInFatArrowFunction(); + return ast; + } + } + ast.type = this.anyType; + this.checker.errorReporter.invalidSuperReference(ast); + } + return ast; + }; + TypeFlow.prototype.typeCheckThis = function (ast) { + ast.type = this.anyType; + var illegalThisRef = false; + if(this.thisFnc == null) { + if(this.thisType) { + if(this.thisClassNode && this.thisClassNode.nodeType == TypeScript.NodeType.ClassDeclaration) { + illegalThisRef = true; + } else { + ast.type = this.thisType; + } + } else { + if(this.checker.currentModDecl) { + this.checker.errorReporter.simpleError(ast, "'this' may not be referenced within module bodies"); + } + } + } else { + if(this.thisClassNode && (TypeScript.hasFlag(this.thisFnc.fncFlags, TypeScript.FncFlags.IsPropertyBound) || (this.inSuperCall && TypeScript.hasFlag((this.thisClassNode).varFlags, TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor)))) { + illegalThisRef = true; + } + if(this.thisFnc.isMethod() || this.thisFnc.isConstructor || this.thisFnc.isTargetTypedAsMethod) { + if(this.thisType && !(this.thisFnc.fncFlags & TypeScript.FncFlags.Static)) { + ast.type = this.thisType; + } + } + } + if(!this.enclosingFncIsMethod && this.thisFnc && TypeScript.hasFlag(this.thisFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { + if(this.thisFnc.boundToProperty) { + var container = this.thisFnc.boundToProperty.sym.container; + if(container.declAST.nodeType == TypeScript.NodeType.FuncDecl) { + (container.declAST).setHasSelfReference(); + } + } else { + var encFnc = this.thisFnc.enclosingFnc; + var firstEncFnc = encFnc; + while(encFnc) { + if(this.thisClassNode && TypeScript.hasFlag(encFnc.fncFlags, TypeScript.FncFlags.IsPropertyBound)) { + illegalThisRef = true; + } + if(!TypeScript.hasFlag(encFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction) || encFnc.hasSelfReference()) { + encFnc.setHasSelfReference(); + break; + } + encFnc = encFnc.enclosingFnc; + } + if(!encFnc && firstEncFnc) { + encFnc = firstEncFnc; + encFnc.setHasSelfReference(); + } else { + if(!encFnc) { + if(this.thisClassNode) { + (this.thisClassNode).varFlags |= TypeScript.VarFlags.MustCaptureThis; + } else { + if(this.checker.currentModDecl) { + this.checker.currentModDecl.modFlags |= TypeScript.ModuleFlags.MustCaptureThis; + } else { + this.checker.mustCaptureGlobalThis = true; + } + } + } + } + if(encFnc && (encFnc.isMethod() || encFnc.isConstructor) && this.thisType && !TypeScript.hasFlag(encFnc.fncFlags, TypeScript.FncFlags.Static)) { + ast.type = this.thisType; + } + } + } + if(illegalThisRef) { + this.checker.errorReporter.simpleError(ast, "Keyword 'this' cannot be referenced in initializers in a class body, or in super constructor calls"); + } + return ast; + }; + TypeFlow.prototype.setTypeFromSymbol = function (ast, symbol) { + if(symbol.isVariable()) { + if(symbol.isInferenceSymbol()) { + var infSym = symbol; + if(infSym.declAST && !this.checker.typeStatusIsFinished(infSym.typeCheckStatus)) { + this.inScopeTypeCheckDecl(infSym.declAST); + } + if(!this.checker.styleSettings.innerScopeDeclEscape) { + if(infSym.declAST && (infSym.declAST.nodeType == TypeScript.NodeType.VarDecl)) { + if(this.nestingLevel < (infSym.declAST).nestingLevel) { + this.checker.errorReporter.styleError(ast, "Illegal reference to a variable defined in more nested scope"); + } + } + } + } + ast.type = symbol.getType(); + if(!symbol.writeable()) { + ast.flags = ast.flags & (~(TypeScript.ASTFlags.Writeable)); + } + } else { + if(symbol.isType()) { + ast.type = symbol.getType(); + ast.flags = ast.flags & (~(TypeScript.ASTFlags.Writeable)); + } else { + ast.type = this.anyType; + this.checker.errorReporter.symbolDoesNotReferToAValue(ast, symbol.name); + } + } + }; + TypeFlow.prototype.typeCheckName = function (ast) { + var _this = this; + var identifier = ast; + if(this.checker.inWith) { + identifier.type = this.anyType; + } else { + var typespace = this.inTypeRefTypeCheck; + var idText = identifier.text; + var originalIdText = idText; + var isDynamicModuleName = TypeScript.isQuoted(identifier.text); + var symbol = this.scope.find(idText, false, typespace); + if(symbol == null && isDynamicModuleName) { + symbol = this.checker.findSymbolForDynamicModule(idText, this.currentScript.locationInfo.filename, function (id) { + return _this.scope.find(id, false, typespace); + }); + } + if(!symbol) { + if(!identifier.isMissing()) { + this.checker.errorReporter.unresolvedSymbol(identifier, identifier.text); + } + identifier.type = this.anyType; + } else { + if(TypeScript.optimizeModuleCodeGen && symbol && symbol.isType()) { + var symType = symbol.getType(); + if(symType && (symbol).aliasLink && (symbol).onlyReferencedAsTypeRef) { + var modDecl = symType.symbol.declAST; + if(modDecl && TypeScript.hasFlag(modDecl.modFlags, TypeScript.ModuleFlags.IsDynamic)) { + (symbol).onlyReferencedAsTypeRef = this.inTypeRefTypeCheck; + } + } + } + if(symbol.declAST && symbol.declAST.nodeType == TypeScript.NodeType.FuncDecl && !(symbol.declAST).returnTypeAnnotation && (symbol.declAST).signature.typeCheckStatus == TypeScript.TypeCheckStatus.Started) { + (symbol.declAST).type.symbol.flags |= TypeScript.SymbolFlags.RecursivelyReferenced; + (symbol.declAST).signature.returnType.type = this.anyType; + } + this.setTypeFromSymbol(ast, symbol); + identifier.sym = symbol; + if(this.thisFnc) { + if(this.thisFnc.type && symbol.container != this.thisFnc.type.symbol) { + this.thisFnc.freeVariables[this.thisFnc.freeVariables.length] = symbol; + } + } + } + } + return ast; + }; + TypeFlow.prototype.typeCheckScript = function (script) { + this.checker.locationInfo = script.locationInfo; + this.scope = this.checker.globalScope; + if(!script.topLevelMod) { + this.addLocalsFromScope(this.scope, this.checker.gloMod, script.vars, this.checker.globals, true); + } + this.currentScript = script; + script.bod = this.typeCheck(script.bod); + this.currentScript = null; + return script; + }; + TypeFlow.prototype.typeCheckBitNot = function (ast) { + var unex = ast; + unex.operand = this.typeCheck(unex.operand); + unex.type = this.doubleType; + return unex; + }; + TypeFlow.prototype.typeCheckUnaryNumberOperator = function (ast) { + var unex = ast; + unex.operand = this.typeCheck(unex.operand); + unex.type = this.doubleType; + return ast; + }; + TypeFlow.prototype.typeCheckLogNot = function (ast) { + var unex = ast; + unex.operand = this.typeCheck(unex.operand); + unex.type = this.booleanType; + return unex; + }; + TypeFlow.prototype.astIsWriteable = function (ast) { + return TypeScript.hasFlag(ast.flags, TypeScript.ASTFlags.Writeable); + }; + TypeFlow.prototype.typeCheckIncOrDec = function (ast) { + var unex = ast; + var lval = unex.operand; + if(!this.astIsWriteable(unex)) { + this.checker.errorReporter.valueCannotBeModified(unex); + unex.type = this.doubleType; + } else { + unex = this.typeCheckUnaryNumberOperator(ast); + if(unex.operand.type != this.checker.numberType && unex.operand.type != this.checker.anyType && !(unex.operand.type.typeFlags & TypeScript.TypeFlags.IsEnum)) { + this.checker.errorReporter.simpleError(ast, "'++' and '--' may only be applied to operands of type 'number' or 'any'"); + } + } + return unex; + }; + TypeFlow.prototype.typeCheckBitwiseOperator = function (ast, assignment) { + var binex = ast; + var resultType = null; + binex.operand1 = this.typeCheck(binex.operand1); + binex.operand2 = this.typeCheck(binex.operand2); + var leftType = binex.operand1.type; + var rightType = binex.operand2.type; + if(assignment && (!this.astIsWriteable(binex))) { + this.checker.errorReporter.valueCannotBeModified(binex); + } + if(this.checker.styleSettings.bitwise) { + this.checker.errorReporter.styleError(ast, "use of " + TypeScript.nodeTypeTable[binex.nodeType]); + } + if(this.checker.sourceIsSubtypeOfTarget(leftType, this.doubleType) && (this.checker.sourceIsSubtypeOfTarget(rightType, this.doubleType))) { + resultType = this.doubleType; + } else { + if((leftType == this.booleanType) && (rightType == this.booleanType)) { + resultType = this.booleanType; + } else { + if(leftType == this.anyType) { + if((rightType == this.anyType) || (rightType == this.doubleType) || (rightType == this.booleanType)) { + resultType = this.anyType; + } + } else { + if(rightType == this.anyType) { + if((leftType == this.anyType) || (leftType == this.doubleType) || (leftType == this.booleanType)) { + resultType = this.anyType; + } + } + } + } + } + if(resultType == null) { + resultType = this.anyType; + this.checker.errorReporter.incompatibleTypes(binex, leftType, rightType, binex.printLabel(), this.scope); + } + binex.type = resultType; + return binex; + }; + TypeFlow.prototype.typeCheckArithmeticOperator = function (ast, assignment) { + var binex = ast; + binex.operand1 = this.typeCheck(binex.operand1); + binex.operand2 = this.typeCheck(binex.operand2); + var leftType = binex.operand1.type; + var rightType = binex.operand2.type; + if(assignment && (!this.astIsWriteable(binex.operand1))) { + this.checker.errorReporter.valueCannotBeModified(binex); + } + if(this.checker.styleSettings.bitwise && ((binex.nodeType == TypeScript.NodeType.And) || (binex.nodeType == TypeScript.NodeType.Or) || (binex.nodeType == TypeScript.NodeType.AsgAnd) || (binex.nodeType == TypeScript.NodeType.AsgOr))) { + this.checker.errorReporter.styleError(ast, "use of " + TypeScript.nodeTypeTable[binex.nodeType]); + } + if(leftType == null || rightType == null) { + this.checker.errorReporter.simpleError(binex, "Could not typecheck arithmetic operation. Possible recursive typecheck error?"); + binex.type = this.anyType; + return binex; + } + var nodeType = binex.nodeType; + if(this.checker.isNullOrUndefinedType(leftType)) { + leftType = rightType; + } + if(this.checker.isNullOrUndefinedType(rightType)) { + rightType = leftType; + } + leftType = this.checker.widenType(leftType); + rightType = this.checker.widenType(rightType); + if(nodeType == TypeScript.NodeType.Add || nodeType == TypeScript.NodeType.AsgAdd) { + if(leftType == this.checker.stringType || rightType == this.checker.stringType) { + binex.type = this.checker.stringType; + } else { + if(leftType == this.checker.numberType && rightType == this.checker.numberType) { + binex.type = this.checker.numberType; + } else { + if(this.checker.sourceIsSubtypeOfTarget(leftType, this.checker.numberType) && this.checker.sourceIsSubtypeOfTarget(rightType, this.checker.numberType)) { + binex.type = this.checker.numberType; + } else { + if(leftType == this.checker.anyType || rightType == this.checker.anyType) { + binex.type = this.checker.anyType; + } else { + binex.type = this.anyType; + this.checker.errorReporter.incompatibleTypes(binex, leftType, rightType, binex.printLabel(), this.scope); + } + } + } + } + } else { + if(leftType == this.checker.numberType && rightType == this.checker.numberType) { + binex.type = this.checker.numberType; + } else { + if(this.checker.sourceIsSubtypeOfTarget(leftType, this.checker.numberType) && this.checker.sourceIsSubtypeOfTarget(rightType, this.checker.numberType)) { + binex.type = this.checker.numberType; + } else { + if(leftType == this.checker.anyType || rightType == this.checker.anyType) { + binex.type = this.checker.numberType; + } else { + binex.type = this.anyType; + this.checker.errorReporter.incompatibleTypes(binex, leftType, rightType, binex.printLabel(), this.scope); + } + } + } + } + return binex; + }; + TypeFlow.prototype.typeCheckDotOperator = function (ast) { + var binex = ast; + var leftIsFnc = false; + binex.operand1 = this.typeCheck(binex.operand1); + var leftType = binex.operand1.type; + var leftScope = null; + if(leftType) { + if(leftType == this.anyType) { + binex.type = this.anyType; + return binex; + } else { + if(leftType == this.stringType) { + if(this.stringInterfaceType) { + leftScope = this.stringInterfaceType.memberScope; + } else { + binex.type = this.anyType; + return binex; + } + } else { + if(leftType == this.doubleType) { + if(this.numberInterfaceType) { + leftScope = this.numberInterfaceType.memberScope; + } else { + binex.type = this.anyType; + return binex; + } + } else { + if(leftType == this.booleanType) { + if(this.booleanInterfaceType) { + leftScope = this.booleanInterfaceType.memberScope; + } else { + binex.type = this.anyType; + return binex; + } + } else { + if((leftType.call || leftType.construct) && leftType.members == null) { + if(this.functionInterfaceType) { + leftScope = this.functionInterfaceType.memberScope; + } else { + binex.type = this.anyType; + return binex; + } + } else { + if(leftType.elementType) { + if(this.arrayInterfaceType) { + var arrInstType = leftType.elementType.getArrayBase(this.arrayInterfaceType, this.checker); + leftScope = arrInstType.memberScope; + } else { + binex.type = this.anyType; + return binex; + } + } else { + leftScope = leftType.memberScope; + } + } + } + } + } + } + } + if(leftScope == null) { + this.checker.errorReporter.expectedClassOrInterface(binex); + binex.type = this.anyType; + } else { + var propertyName = binex.operand2; + var lhsIsEnclosingType = (this.thisClassNode && binex.operand1.type == this.thisClassNode.type.instanceType) || this.inTypeRefTypeCheck; + var symbol = leftScope.find(propertyName.text, !lhsIsEnclosingType, this.inTypeRefTypeCheck); + if(!symbol) { + if(this.objectInterfaceType && leftType) { + if(leftType.isReferenceType()) { + symbol = this.objectInterfaceType.memberScope.find(propertyName.text, false, this.inTypeRefTypeCheck); + } + if(!symbol) { + if(this.functionInterfaceType && (leftType.call || leftType.construct)) { + symbol = this.functionInterfaceType.memberScope.find(propertyName.text, false, this.inTypeRefTypeCheck); + } + } + } + } + if(!symbol || (!symbol.visible(leftScope, this.checker))) { + binex.type = this.anyType; + if(symbol == null) { + this.checker.errorReporter.simpleError(propertyName, "The property '" + propertyName.actualText + "' does not exist on value of type '" + leftType.getScopedTypeName(this.scope) + "'"); + } else { + if(!this.inTypeRefTypeCheck) { + this.checker.errorReporter.simpleError(binex, "The property '" + propertyName.actualText + " on type '" + leftType.getScopedTypeName(this.scope) + "' is not visible"); + } + } + } else { + if(symbol.isVariable()) { + if(symbol.isInferenceSymbol()) { + var infSym = symbol; + if(infSym.declAST && !this.checker.typeStatusIsFinished(infSym.typeCheckStatus)) { + this.inScopeTypeCheckDecl(infSym.declAST); + } + } + } + propertyName.sym = symbol; + binex.type = symbol.getType(); + } + } + if(binex.type == null) { + binex.type = this.anyType; + } + return binex; + }; + TypeFlow.prototype.typeCheckBooleanOperator = function (ast) { + var binex = ast; + binex.operand1 = this.typeCheck(binex.operand1); + binex.operand2 = this.typeCheck(binex.operand2); + var leftType = binex.operand1.type; + var rightType = binex.operand2.type; + if((!(this.checker.sourceIsAssignableToTarget(leftType, rightType))) && (!(this.checker.sourceIsAssignableToTarget(rightType, leftType)))) { + this.checker.errorReporter.incompatibleTypes(binex, leftType, rightType, binex.printLabel(), this.scope); + } + binex.type = this.booleanType; + return binex; + }; + TypeFlow.prototype.typeCheckAsgOperator = function (ast) { + var binex = ast; + var applyTargetType = !binex.operand2.isParenthesized; + binex.operand1 = this.typeCheck(binex.operand1); + this.checker.typeCheckWithContextualType(binex.operand1.type, this.checker.inProvisionalTypecheckMode(), applyTargetType, binex.operand2); + var leftType = binex.operand1.type; + var rightType = binex.operand2.type; + if(!(this.astIsWriteable(binex.operand1))) { + this.checker.errorReporter.valueCannotBeModified(binex); + } + if(binex.operand1.nodeType == TypeScript.NodeType.Call) { + var callEx = binex.operand1; + } + var preserveScope = false; + var preservedContainedScope = null; + if(binex.operand2.type) { + preservedContainedScope = binex.operand2.type.containedScope; + preserveScope = true; + } + binex.operand2 = this.castWithCoercion(binex.operand2, leftType, applyTargetType && !this.checker.inProvisionalTypecheckMode(), false); + if(preserveScope && binex.operand2.type.containedScope == null) { + binex.operand2.type.containedScope = preservedContainedScope; + } + binex.type = rightType; + return binex; + }; + TypeFlow.prototype.typeCheckIndex = function (ast) { + var binex = ast; + binex.operand1 = this.typeCheck(binex.operand1); + binex.operand2 = this.typeCheck(binex.operand2); + if(!this.checker.styleSettings.literalSubscript) { + if(binex.operand2.nodeType == TypeScript.NodeType.QString) { + this.checker.errorReporter.styleError(ast, "use literal subscript ('.') notation instead)"); + } + } + var objExprType = binex.operand1.type; + var indexExprType = binex.operand2.type; + if(objExprType.elementType) { + if(indexExprType == this.checker.anyType || indexExprType == this.checker.numberType || TypeScript.hasFlag(indexExprType.typeFlags, TypeScript.TypeFlags.IsEnum)) { + binex.type = objExprType.elementType; + } else { + if(indexExprType == this.checker.stringType) { + binex.type = this.checker.anyType; + } else { + this.checker.errorReporter.simpleError(binex, "Illegal property access"); + binex.type = this.checker.anyType; + } + } + } else { + if(objExprType.index) { + if(indexExprType == this.checker.anyType || !((objExprType.index.flags & TypeScript.SignatureFlags.IsStringIndexer) || (objExprType.index.flags & TypeScript.SignatureFlags.IsNumberIndexer)) || ((objExprType.index.flags & TypeScript.SignatureFlags.IsStringIndexer) && indexExprType == this.checker.stringType) || ((objExprType.index.flags & TypeScript.SignatureFlags.IsNumberIndexer) && (indexExprType == this.checker.numberType || TypeScript.hasFlag(indexExprType.typeFlags, TypeScript.TypeFlags.IsEnum)))) { + var sig = this.resolveOverload(ast, objExprType.index); + if(sig) { + binex.type = sig.returnType.type; + } else { + binex.type = this.checker.anyType; + } + } else { + if(indexExprType == this.checker.stringType) { + binex.type = this.checker.anyType; + } else { + this.checker.errorReporter.simpleError(binex, "Illegal property access"); + binex.type = this.checker.anyType; + } + } + } else { + if((objExprType == this.checker.anyType || objExprType == this.checker.stringType || objExprType == this.checker.numberType || objExprType == this.checker.booleanType || objExprType.isReferenceType()) && (indexExprType == this.checker.anyType || indexExprType == this.checker.stringType || (indexExprType == this.checker.numberType || TypeScript.hasFlag(indexExprType.typeFlags, TypeScript.TypeFlags.IsEnum)))) { + binex.type = this.checker.anyType; + } else { + this.checker.errorReporter.simpleError(binex, "Illegal property access"); + binex.type = this.checker.anyType; + } + } + } + return binex; + }; + TypeFlow.prototype.typeCheckInOperator = function (binex) { + binex.operand1 = this.cast(this.typeCheck(binex.operand1), this.stringType); + binex.operand2 = this.typeCheck(binex.operand2); + if(!((binex.operand1.type == this.checker.anyType || binex.operand1.type == this.checker.stringType) && (binex.operand2.type == this.anyType || this.checker.sourceIsSubtypeOfTarget(binex.operand2.type, this.objectInterfaceType)))) { + this.checker.errorReporter.simpleError(binex, "The in operator requires the left operand to be of type Any or the String primitive type, and the right operand to be of type Any or an object type"); + } + binex.type = this.booleanType; + return binex; + }; + TypeFlow.prototype.typeCheckShift = function (binex, assignment) { + binex.operand1 = this.cast(this.typeCheck(binex.operand1), this.doubleType); + binex.operand2 = this.cast(this.typeCheck(binex.operand2), this.doubleType); + if(assignment && (!(this.astIsWriteable(binex.operand1)))) { + this.checker.errorReporter.valueCannotBeModified(binex); + } + binex.type = this.doubleType; + return binex; + }; + TypeFlow.prototype.typeCheckQMark = function (trinex) { + trinex.operand1 = this.typeCheck(trinex.operand1); + trinex.operand2 = this.typeCheck(trinex.operand2); + trinex.operand3 = this.typeCheck(trinex.operand3); + var leftType = trinex.operand2.type; + var rightType = trinex.operand3.type; + if(leftType == rightType) { + trinex.type = leftType; + } else { + if(this.checker.sourceIsSubtypeOfTarget(leftType, rightType)) { + trinex.type = rightType; + } else { + if(this.checker.sourceIsSubtypeOfTarget(rightType, leftType)) { + trinex.type = leftType; + } else { + trinex.type = this.anyType; + this.checker.errorReporter.incompatibleTypes(trinex, leftType, rightType, trinex.printLabel(), this.scope); + } + } + } + return trinex; + }; + TypeFlow.prototype.addFormals = function (container, signature, table) { + var len = signature.parameters.length; + for(var i = 0; i < len; i++) { + var symbol = signature.parameters[i]; + symbol.container = container; + table.add(symbol.name, symbol); + } + }; + TypeFlow.prototype.addLocalsFromScope = function (scope, container, vars, table, isModContainer) { + var len = vars.members.length; + var hasArgsDef = false; + for(var i = 0; i < len; i++) { + var local = vars.members[i]; + if(((local.sym == null) || (local.sym.kind() != TypeScript.SymbolKind.Field))) { + var result = null; + if((result = table.lookup(local.id.text)) == null) { + var localVar = new TypeScript.ValueLocation(); + localVar.typeLink = new TypeScript.TypeLink(); + var varSym = null; + if(TypeScript.hasFlag(local.varFlags, TypeScript.VarFlags.Static)) { + local.varFlags |= TypeScript.VarFlags.LocalStatic; + varSym = new TypeScript.FieldSymbol(local.id.text, local.minChar, this.checker.locationInfo.unitIndex, true, localVar); + } else { + varSym = new TypeScript.VariableSymbol(local.id.text, local.minChar, this.checker.locationInfo.unitIndex, localVar); + } + varSym.transferVarFlags(local.varFlags); + localVar.symbol = varSym; + varSym.declAST = local; + localVar.typeLink.ast = local.typeExpr; + this.checker.resolveTypeLink(scope, localVar.typeLink, false); + if((local.type == null) && (local.init == null)) { + local.type = this.anyType; + } + localVar.typeLink.type = local.type; + localVar.symbol.container = container; + local.sym = localVar.symbol; + table.add(local.id.text, varSym); + if(local.id.text == "arguments") { + hasArgsDef = true; + } + } else { + local.type = result.getType(); + local.sym = result; + } + } + } + if(!isModContainer) { + if(!hasArgsDef) { + var argLoc = new TypeScript.ValueLocation(); + argLoc.typeLink = new TypeScript.TypeLink(); + var theArgSym = new TypeScript.VariableSymbol("arguments", vars.minChar, this.checker.locationInfo.unitIndex, argLoc); + if(!this.iargumentsInterfaceType) { + var argumentsSym = scope.find("IArguments", false, true); + if(argumentsSym) { + argumentsSym.flags |= TypeScript.SymbolFlags.CompilerGenerated; + this.iargumentsInterfaceType = argumentsSym.getType(); + } else { + this.iargumentsInterfaceType = this.anyType; + } + } + argLoc.typeLink.type = this.iargumentsInterfaceType; + table.add("arguments", theArgSym); + } + } + }; + TypeFlow.prototype.addConstructorLocalArgs = function (container, args, table, isClass) { + if(args) { + var len = args.members.length; + for(var i = 0; i < len; i++) { + var local = args.members[i]; + if((local.sym == null) || (isClass || (local.sym.kind() != TypeScript.SymbolKind.Field))) { + var result = null; + if((result = table.lookup(local.id.text)) == null) { + this.resolveBoundDecl(local); + var localVar = new TypeScript.ValueLocation(); + localVar.typeLink = new TypeScript.TypeLink(); + var varSym = new TypeScript.ParameterSymbol(local.id.text, local.minChar, this.checker.locationInfo.unitIndex, localVar); + varSym.declAST = local; + localVar.symbol = varSym; + localVar.typeLink.type = local.type; + localVar.symbol.container = container; + local.sym = localVar.symbol; + table.add(local.id.text, varSym); + } else { + local.type = result.getType(); + local.sym = result; + } + } + } + } + }; + TypeFlow.prototype.checkInitSelf = function (funcDecl) { + if(!funcDecl.isMethod()) { + var freeVars = funcDecl.freeVariables; + for(var k = 0, len = freeVars.length; k < len; k++) { + var sym = freeVars[k]; + if(sym.isInstanceProperty()) { + return true; + } + } + } + var fns = funcDecl.scopes; + var fnsLen = fns.members.length; + for(var j = 0; j < fnsLen; j++) { + var fn = fns.members[j]; + if(this.checkInitSelf(fn)) { + return true; + } + } + return false; + }; + TypeFlow.prototype.checkPromoteFreeVars = function (funcDecl, constructorSym) { + var freeVars = funcDecl.freeVariables; + for(var k = 0, len = freeVars.length; k < len; k++) { + var sym = freeVars[k]; + if((!sym.isInstanceProperty()) && (sym.container == constructorSym)) { + TypeScript.instanceFilter.reset(); + if(this.scope.search(TypeScript.instanceFilter, sym.name, false, false)) { + this.checker.errorReporter.simpleError(funcDecl, "Constructor-local variable shadows class property '" + sym.name + "'. To access the class property, use 'self." + sym.name + "'"); + } + this.checker.errorReporter.simpleError(funcDecl, "Constructor-local variables may not be accessed from instance method bodies. Consider changing local variable '" + sym.name + "' to a class property"); + } + } + }; + TypeFlow.prototype.allReturnsAreVoid = function (funcDecl) { + var allReturnsAreVoid = true; + if(funcDecl.signature.returnType.type == null) { + var preFindReturnExpressionTypes = function (ast, parent, walker) { + var go = true; + switch(ast.nodeType) { + case TypeScript.NodeType.FuncDecl: { + go = false; + break; + + } + case TypeScript.NodeType.Return: { + var returnStmt = ast; + if(returnStmt.returnExpression) { + allReturnsAreVoid = false; + go = false; + } + + } + default: { + break; + + } + } + walker.options.goChildren = go; + walker.options.goNextSibling = go; + return ast; + }; + TypeScript.getAstWalkerFactory().walk(funcDecl.bod, preFindReturnExpressionTypes); + } + return allReturnsAreVoid; + }; + TypeFlow.prototype.classConstructorHasSuperCall = function (funcDecl) { + var foundSuper = false; + var preFindSuperCall = function (ast, parent, walker) { + var go = true; + switch(ast.nodeType) { + case TypeScript.NodeType.FuncDecl: { + go = false; + break; + + } + case TypeScript.NodeType.Call: { + var call = ast; + if(call.target.nodeType == TypeScript.NodeType.Super) { + go = false; + foundSuper = true; + break; + } + break; + + } + default: { + break; + + } + } + walker.options.goChildren = go; + return ast; + }; + TypeScript.getAstWalkerFactory().walk(funcDecl.bod, preFindSuperCall); + return foundSuper; + }; + TypeFlow.prototype.baseListPrivacyErrorReporter = function (bases, i, declSymbol, extendsList, typeName, isModuleName) { + var baseSymbol = bases.members[i].type.symbol; + var declTypeString = (declSymbol.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) ? "interface" : "class"; + var baseListTypeString = extendsList ? "extends" : "implements"; + var baseTypeString = (baseSymbol.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) ? "interface" : "class"; + var typestring = ""; + if(isModuleName) { + var quotestring = ""; + if(!TypeScript.isQuoted(typeName)) { + quotestring = "'"; + } + typestring = " is using inaccessible module "; + baseTypeString = " " + baseTypeString + " from private module " + quotestring + typeName + quotestring; + } else { + baseTypeString = " private " + baseTypeString + " '" + typeName + "'"; + } + this.checker.errorReporter.simpleError(bases.members[i], "exported " + declTypeString + " '" + declSymbol.name + "' " + baseListTypeString + baseTypeString); + }; + TypeFlow.prototype.typeCheckBaseListPrivacy = function (bases, declSymbol, extendsList) { + var _this = this; + if(bases) { + var basesLen = bases.members.length; + for(var i = 0; i < basesLen; i++) { + if(!bases.members[i].type || bases.members[i].type == this.checker.anyType) { + continue; + } + this.checkSymbolPrivacy(bases.members[i].type.symbol, declSymbol, function (typeName, isModuleName) { + return _this.baseListPrivacyErrorReporter(bases, i, declSymbol, extendsList, typeName, isModuleName); + }); + } + } + }; + TypeFlow.prototype.checkSymbolPrivacy = function (typeSymbol, declSymbol, errorCallback) { + var externalModuleSymbol = null; + var declSymbolPath = null; + if(typeSymbol.isExternallyVisible(this.checker)) { + var typeSymbolPath = typeSymbol.pathToRoot(); + declSymbolPath = declSymbol.pathToRoot(); + var typeSymbolLength = typeSymbolPath.length; + var declSymbolPathLength = declSymbolPath.length; + if(typeSymbolLength > 0) { + if(typeSymbolPath[typeSymbolLength - 1].getType().isModuleType() && (typeSymbolPath[typeSymbolLength - 1]).isDynamic && typeSymbolPath[typeSymbolLength - 1] != declSymbolPath[declSymbolPathLength - 1]) { + externalModuleSymbol = typeSymbolPath[typeSymbolLength - 1]; + } else { + if(typeSymbolLength > 1) { + if(typeSymbolPath[typeSymbolLength - 2].getType().isModuleType() && (typeSymbolPath[typeSymbolLength - 2]).isDynamic && (declSymbolPathLength == 1 || typeSymbolPath[typeSymbolLength - 2] != declSymbolPath[declSymbolPathLength - 2])) { + externalModuleSymbol = typeSymbolPath[typeSymbolLength - 2]; + } + } + } + } + if(externalModuleSymbol == null) { + return; + } + } + var interfaceDecl = declSymbol.getInterfaceDeclFromSymbol(this.checker); + if(interfaceDecl && !TypeScript.hasFlag(interfaceDecl.varFlags, TypeScript.VarFlags.Exported)) { + return; + } + var checkVisibilitySymbol = declSymbol; + var varDecl = declSymbol.getVarDeclFromSymbol(); + if(varDecl) { + if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Private)) { + return; + } else { + if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Public)) { + checkVisibilitySymbol = declSymbol.container; + } + } + } + if(checkVisibilitySymbol.isExternallyVisible(this.checker)) { + var privateSymbolName = typeSymbol.name; + if(externalModuleSymbol != null) { + var prettyName = externalModuleSymbol.getPrettyNameOfDynamicModule(declSymbolPath); + if(prettyName != null) { + this.currentScript.AddExternallyVisibleImportedSymbol(prettyName.symbol, this.checker); + return; + } else { + privateSymbolName = externalModuleSymbol.prettyName; + } + } + errorCallback(privateSymbolName, typeSymbol.name != privateSymbolName); + } + }; + TypeFlow.prototype.checkTypePrivacy = function (type, declSymbol, errorCallback) { + var _this = this; + if(!(type && type.primitiveTypeClass == TypeScript.Primitive.None)) { + return; + } + if(type.isArray()) { + return this.checkTypePrivacy(type.elementType, declSymbol, errorCallback); + } + if(type.symbol && type.symbol.name && type.symbol.name != "_anonymous" && (((type.call == null) && (type.construct == null) && (type.index == null)) || (type.members && (!type.isClass())))) { + return this.checkSymbolPrivacy(type.symbol, declSymbol, errorCallback); + } + if(type.members) { + type.members.allMembers.map(function (key, s, unused) { + var sym = s; + if(!TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.BuiltIn)) { + _this.checkTypePrivacy(sym.getType(), declSymbol, errorCallback); + } + }, null); + } + this.checkSignatureGroupPrivacy(type.call, declSymbol, errorCallback); + this.checkSignatureGroupPrivacy(type.construct, declSymbol, errorCallback); + this.checkSignatureGroupPrivacy(type.index, declSymbol, errorCallback); + }; + TypeFlow.prototype.checkSignatureGroupPrivacy = function (sgroup, declSymbol, errorCallback) { + if(sgroup) { + var len = sgroup.signatures.length; + for(var i = 0; i < sgroup.signatures.length; i++) { + var signature = sgroup.signatures[i]; + if(len > 1 && signature == sgroup.definitionSignature) { + continue; + } + if(signature.returnType) { + this.checkTypePrivacy(signature.returnType.type, declSymbol, errorCallback); + } + var paramLen = signature.parameters.length; + for(var j = 0; j < paramLen; j++) { + var param = signature.parameters[j]; + this.checkTypePrivacy(param.getType(), declSymbol, errorCallback); + } + } + } + }; + TypeFlow.prototype.functionArgumentPrivacyErrorReporter = function (funcDecl, p, paramSymbol, typeName, isModuleName) { + var isGetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor); + var isSetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.SetAccessor); + var isPublicFunc = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Public); + var isContainerInterface = funcDecl.type.symbol.getInterfaceDeclFromSymbol(this.checker) != null; + var typestring = ""; + if(isModuleName) { + var quotestring = ""; + if(!TypeScript.isQuoted(typeName)) { + quotestring = "'"; + } + typestring = " is using inaccessible module " + quotestring + typeName + quotestring; + } else { + typestring = " has or is using private type '" + typeName + "'"; + } + if(!isContainerInterface) { + if(funcDecl.isConstructor) { + this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], "exported class's constructor parameter '" + paramSymbol.name + "'" + typestring); + } else { + if(isSetter) { + this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], (isPublicFunc ? "public" : "exported") + " setter parameter '" + paramSymbol.name + "'" + typestring); + } else { + if(!isGetter) { + this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], (isPublicFunc ? "public" : "exported") + " function parameter '" + paramSymbol.name + "'" + typestring); + } + } + } + } else { + if(funcDecl.isConstructMember()) { + this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], "exported interface's constructor parameter '" + paramSymbol.name + "'" + typestring); + } else { + if(funcDecl.isCallMember()) { + this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], "exported interface's call parameter '" + paramSymbol.name + "'" + typestring); + } else { + if(!funcDecl.isIndexerMember()) { + this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], "exported interface's function parameter '" + paramSymbol.name + "'" + typestring); + } + } + } + } + }; + TypeFlow.prototype.returnTypePrivacyError = function (astError, funcDecl, typeName, isModuleName) { + var isGetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor); + var isSetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.SetAccessor); + var isPublicFunc = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Public); + var isContainerInterface = funcDecl.type.symbol.getInterfaceDeclFromSymbol(this.checker) != null; + var typestring = ""; + if(isModuleName) { + var quotestring = ""; + if(!TypeScript.isQuoted(typeName)) { + quotestring = "'"; + } + typestring = " is using inaccessible module " + quotestring + typeName + quotestring; + } else { + typestring = " has or is using private type '" + typeName + "'"; + } + if(!isContainerInterface) { + if(isGetter) { + this.checker.errorReporter.simpleError(astError, (isPublicFunc ? "public" : "exported") + " getter return type" + typestring); + } else { + if(!isSetter) { + this.checker.errorReporter.simpleError(astError, (isPublicFunc ? "public" : "exported") + " function return type" + typestring); + } + } + } else { + if(funcDecl.isConstructMember()) { + this.checker.errorReporter.simpleError(astError, "exported interface's constructor return type" + typestring); + } else { + if(funcDecl.isCallMember()) { + this.checker.errorReporter.simpleError(astError, "exported interface's call return type" + typestring); + } else { + if(funcDecl.isIndexerMember()) { + this.checker.errorReporter.simpleError(astError, "exported interface's indexer return type" + typestring); + } else { + this.checker.errorReporter.simpleError(astError, "exported interface's function return type" + typestring); + } + } + } + } + }; + TypeFlow.prototype.functionReturnTypePrivacyErrorReporter = function (funcDecl, signature, typeName, isModuleName) { + var reportOnFuncDecl = false; + if(funcDecl.returnTypeAnnotation != null && funcDecl.returnTypeAnnotation.type == signature.returnType.type) { + this.returnTypePrivacyError(funcDecl.returnTypeAnnotation, funcDecl, typeName, isModuleName); + } + for(var i = 0; i < funcDecl.returnStatementsWithExpressions.length; i++) { + if(funcDecl.returnStatementsWithExpressions[i].type == signature.returnType.type) { + this.returnTypePrivacyError(funcDecl.returnStatementsWithExpressions[i], funcDecl, typeName, isModuleName); + } else { + reportOnFuncDecl = true; + } + } + if(reportOnFuncDecl) { + this.returnTypePrivacyError(funcDecl, funcDecl, typeName, isModuleName); + } + }; + TypeFlow.prototype.typeCheckFunction = function (funcDecl) { + var _this = this; + this.nestingLevel = 0; + var fnType = funcDecl.type; + var fgSym = fnType.symbol; + var signature = funcDecl.signature; + if(this.checker.typeStatusIsFinished(signature.typeCheckStatus)) { + return funcDecl; + } else { + if(signature.typeCheckStatus == TypeScript.TypeCheckStatus.Started) { + if(!funcDecl.returnTypeAnnotation && funcDecl.bod && !funcDecl.isSignature() && !(funcDecl.isConstructor) && this.allReturnsAreVoid(funcDecl)) { + signature.returnType.type = this.voidType; + return funcDecl; + } else { + if(funcDecl.returnTypeAnnotation == null) { + if(this.checker.styleSettings.implicitAny) { + this.checker.errorReporter.styleError(funcDecl, "type implicitly set to 'any'"); + } + signature.returnType.type = this.anyType; + fgSym.flags |= TypeScript.SymbolFlags.RecursivelyReferenced; + } + return funcDecl; + } + } + } + signature.typeCheckStatus = TypeScript.TypeCheckStatus.Started; + this.checker.addStartedPTO(signature); + var prevScope = this.scope; + var prevFnc = this.thisFnc; + var prevMethodStatus = this.enclosingFncIsMethod; + var prevClassNode = this.thisClassNode; + this.enclosingFncIsMethod = funcDecl.isMethod() || funcDecl.isConstructor; + this.thisFnc = funcDecl; + var container = funcDecl.type.symbol; + var prevThisType = this.thisType; + var prevLocationInfo = this.checker.locationInfo; + var funcTable = null; + var acceptedContextualType = false; + var targetParams = null; + var targetReturnType = null; + var isGetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor); + var isSetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.SetAccessor); + var accessorType = (isGetter || isSetter) && funcDecl.accessorSymbol ? funcDecl.accessorSymbol.getType() : null; + var prevModDecl = this.checker.currentModDecl; + if(funcDecl.isConstructor && !funcDecl.isOverload) { + if(fnType.instanceType == null) { + this.checker.errorReporter.simpleError(funcDecl, "Malformed function body (is this a class named the same as an existing interface?)"); + return funcDecl; + } + this.scope = fnType.instanceType.constructorScope; + var ssb = this.scope; + funcTable = ssb.valueMembers.allMembers; + } else { + if((funcDecl.isSpecialFn() && !(funcDecl.fncFlags & TypeScript.FncFlags.Signature)) || funcDecl.isOverload) { + funcTable = funcDecl.symbols; + if(!TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static) && fnType.containedScope) { + this.scope = fnType.containedScope; + } + } else { + if(funcDecl.bod) { + this.scope = fnType.containedScope; + } + var ssb = this.scope; + if(ssb && ssb.valueMembers) { + funcTable = ssb.valueMembers.allMembers; + } + } + } + if(funcDecl.isConstructor && funcDecl.bod && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { + var hasBaseType = TypeScript.hasFlag(funcDecl.classDecl.type.instanceType.typeFlags, TypeScript.TypeFlags.HasBaseType); + var noSuperCallAllowed = !hasBaseType || TypeScript.hasFlag(funcDecl.classDecl.type.instanceType.typeFlags, TypeScript.TypeFlags.HasBaseTypeOfObject); + var superCallMustBeFirst = TypeScript.hasFlag((funcDecl.classDecl).varFlags, TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor); + if(noSuperCallAllowed && this.classConstructorHasSuperCall(funcDecl)) { + this.checker.errorReporter.simpleError(funcDecl, "Calls to 'super' constructor are not allowed in classes that either inherit directly from 'Object' or have no base class"); + } else { + if(hasBaseType) { + if(superCallMustBeFirst) { + if(!funcDecl.bod || !funcDecl.bod.members.length || !((funcDecl.bod.members[0].nodeType == TypeScript.NodeType.Call && (funcDecl.bod.members[0]).target.nodeType == TypeScript.NodeType.Super) || (TypeScript.hasFlag(funcDecl.bod.flags, TypeScript.ASTFlags.StrictMode) && funcDecl.bod.members.length > 1 && funcDecl.bod.members[1].nodeType == TypeScript.NodeType.Call && (funcDecl.bod.members[1]).target.nodeType == TypeScript.NodeType.Super))) { + this.checker.errorReporter.simpleError(funcDecl, "If a derived class contains initialized properties or constructor parameter properties, the first statement in the constructor body must be a call to the super constructor"); + } + } else { + if(!this.classConstructorHasSuperCall(funcDecl)) { + this.checker.errorReporter.simpleError(funcDecl, "Constructors for derived classes must contain a call to the class's 'super' constructor"); + } + } + } + } + } + if(funcDecl.isMethod() && funcDecl.type.enclosingType) { + var enclosingClassNode = null; + if(funcDecl.type.enclosingType.symbol.declAST.nodeType == TypeScript.NodeType.FuncDecl) { + enclosingClassNode = (funcDecl.type.enclosingType.symbol.declAST).classDecl; + } else { + if(funcDecl.type.enclosingType.symbol.declAST.nodeType == TypeScript.NodeType.ClassDeclaration) { + enclosingClassNode = funcDecl.type.enclosingType.symbol.declAST; + } + } + if(enclosingClassNode) { + this.thisClassNode = enclosingClassNode; + } + } + if(fnType.enclosingType) { + ; ; + var enclosingSym = fnType.symbol.container; + if(enclosingSym && enclosingSym.isType() && enclosingSym.getType().isClass()) { + enclosingSym = enclosingSym.container; + } + if(enclosingSym && enclosingSym.declAST && enclosingSym.declAST.nodeType == TypeScript.NodeType.ModuleDeclaration) { + this.checker.currentModDecl = enclosingSym.declAST; + } + } + if(funcDecl.unitIndex > 0) { + if(this.checker.units && (funcDecl.unitIndex < this.checker.units.length)) { + this.checker.locationInfo = this.checker.units[funcDecl.unitIndex]; + } else { + this.checker.locationInfo = TypeScript.unknownLocationInfo; + } + } + if(fnType.enclosingType) { + this.thisType = fnType.enclosingType; + } else { + this.thisType = prevThisType; + } + var paramLen = signature.parameters.length; + if(!funcDecl.isConstructor && funcDecl.bod && !funcDecl.isSignature()) { + var tmpParamScope = this.scope; + var ssb = this.scope; + if(!funcDecl.isMethod() && funcDecl.returnTypeAnnotation == null) { + if(prevScope && funcDecl.name && !funcDecl.name.isMissing()) { + var considerSym = prevScope.findAmbient(funcDecl.name.text, false, false); + if(considerSym && considerSym.declAST && considerSym.declAST.type) { + this.checker.setContextualType(considerSym.declAST.type, false); + } + } + if(this.checker.hasTargetType()) { + var candidateTypeContext = this.checker.getTargetTypeContext(); + var candidateType = candidateTypeContext.contextualType; + if(this.checker.canContextuallyTypeFunction(candidateType, funcDecl, true)) { + var candidateSigs = candidateType.construct ? candidateType.construct : candidateType.call; + candidateTypeContext.targetSig = candidateSigs.signatures[0]; + var candidateParams = candidateTypeContext.targetSig.parameters; + targetParams = candidateParams; + targetReturnType = candidateTypeContext.targetSig.returnType.type; + if(candidateTypeContext.targetSig.declAST) { + if(candidateTypeContext.targetSig.declAST.isConstructor) { + funcDecl.isTargetTypedAsMethod = true; + } else { + if(candidateTypeContext.targetSig.declAST.isMethod()) { + funcDecl.isTargetTypedAsMethod = true; + } + } + } + fgSym.type = candidateTypeContext.contextualType; + acceptedContextualType = true; + } else { + if(candidateType && funcDecl.isAccessor()) { + accessorType = candidateType; + candidateTypeContext.targetAccessorType = accessorType; + } else { + this.checker.killCurrentContextualType(); + } + } + } + } + var paramTable = ssb.valueMembers; + this.scope = new TypeScript.SymbolScopeBuilder(paramTable, null, null, null, prevScope, container); + for(var p = 0; p < paramLen; p++) { + var symbol = signature.parameters[p]; + var ast = symbol.declAST; + if(this.checker.hasTargetType() && (targetParams && (this.checker.getTargetTypeContext().targetSig.hasVariableArgList || p < targetParams.length))) { + var candidateTypeContext = this.checker.getTargetTypeContext(); + var hasVarArgList = candidateTypeContext.targetSig.hasVariableArgList; + ast.type = hasVarArgList && p >= targetParams.length - 1 ? targetParams[targetParams.length - 1].getType().elementType : targetParams[p].getType(); + ast.sym.setType(ast.type); + (ast.sym).typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); + } else { + this.typeCheck(ast); + } + if(isSetter && accessorType) { + ast = this.cast(ast, accessorType); + } + symbol.container = container; + this.checkTypePrivacy(symbol.getType(), container, function (typeName, isModuleName) { + return _this.functionArgumentPrivacyErrorReporter(funcDecl, p, symbol, typeName, isModuleName); + }); + paramTable.publicMembers.add(symbol.name, symbol); + } + this.scope = tmpParamScope; + } else { + this.typeCheck(funcDecl.arguments); + for(var p = 0; p < paramLen; p++) { + signature.parameters[p].parameter.typeLink.type = funcDecl.arguments.members[p].type; + this.checkTypePrivacy(signature.parameters[p].getType(), container, function (typeName, isModuleName) { + return _this.functionArgumentPrivacyErrorReporter(funcDecl, p, signature.parameters[p], typeName, isModuleName); + }); + if((funcDecl.arguments.members[p]).parameterPropertySym) { + (funcDecl.arguments.members[p]).parameterPropertySym.setType(funcDecl.arguments.members[p].type); + } + } + if((funcDecl.fncFlags & TypeScript.FncFlags.IndexerMember)) { + if(!paramLen || paramLen > 1) { + this.checker.errorReporter.simpleError(funcDecl, "Index signatures may take one and only one parameter"); + } else { + if(funcDecl.arguments.members[0].type == this.checker.numberType) { + fnType.index.flags |= TypeScript.SignatureFlags.IsNumberIndexer; + } else { + if(funcDecl.arguments.members[0].type == this.checker.stringType) { + fnType.index.flags |= TypeScript.SignatureFlags.IsStringIndexer; + } else { + this.checker.errorReporter.simpleError(funcDecl.arguments.members[0], "Index signatures may only take 'string' or 'number' as their parameter"); + } + } + } + } + } + if(funcDecl.bod && (!funcDecl.isSignature())) { + if(!(funcDecl.isConstructor)) { + this.addFormals(container, signature, funcTable); + } else { + this.addConstructorLocalArgs(funcDecl.type.symbol, funcDecl.arguments, funcTable, TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)); + if(this.thisClassNode && this.thisClassNode.extendsList) { + var tmpScope = this.scope; + var funcMembers = new TypeScript.ScopedMembers(funcTable); + this.scope = new TypeScript.FilteredSymbolScopeBuilder(funcMembers, prevScope, funcDecl.type.symbol, function (sym) { + return sym.kind() == TypeScript.SymbolKind.Parameter; + }); + this.typeCheckBaseCalls(this.thisClassNode.extendsList); + this.scope = tmpScope; + } + } + var prevMod = this.checker.currentModDecl; + if(funcDecl.type && funcDecl.type.symbol && !funcDecl.isMethod() && funcDecl.type.symbol.declModule) { + this.checker.currentModDecl = funcDecl.type.symbol.declModule; + } + if(acceptedContextualType) { + this.checker.setContextualType(null, this.checker.inProvisionalTypecheckMode()); + } + this.typeCheck(funcDecl.bod); + if(acceptedContextualType) { + this.checker.unsetContextualType(); + } + this.checker.currentModDecl = prevMod; + if(this.checker.checkControlFlow) { + var cfg = funcDecl.buildControlFlow(); + if(this.checker.printControlFlowGraph) { + cfg.print(this.checker.errorReporter.outfile); + } + cfg.reportUnreachable(this.checker.errorReporter); + if(this.checker.checkControlFlowUseDef) { + cfg.useDef(this.checker.errorReporter, funcDecl.type.symbol); + } + } + if(funcDecl.isConstructor) { + var fns = funcDecl.scopes; + var fnsLen = fns.members.length; + var freeVars; + var sym; + var j = 0; + for(; j < fnsLen; j++) { + var fn = fns.members[j]; + if(!fn.isSignature()) { + if(TypeScript.hasFlag(fn.fncFlags, TypeScript.FncFlags.Method) && (!TypeScript.hasFlag(fn.fncFlags, TypeScript.FncFlags.Static))) { + this.checkPromoteFreeVars(fn, funcDecl.type.symbol); + } + } + } + } + } + this.scope = prevScope; + this.thisFnc = prevFnc; + this.thisClassNode = prevClassNode; + this.enclosingFncIsMethod = prevMethodStatus; + this.thisType = prevThisType; + this.checker.locationInfo = prevLocationInfo; + this.checker.currentModDecl = prevModDecl; + signature.typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); + if(funcDecl.returnTypeAnnotation) { + this.checkForVoidConstructor(funcDecl.returnTypeAnnotation.type, funcDecl.returnTypeAnnotation); + if(signature.returnType.type == null) { + this.checker.resolveTypeLink(this.scope, signature.returnType, false); + } + } else { + if(targetReturnType) { + signature.returnType.type = targetReturnType; + } + } + if(!(fgSym.flags & TypeScript.SymbolFlags.RecursivelyReferenced) && funcDecl.returnStatementsWithExpressions.length > 0) { + var collection = { + getLength: function () { + return funcDecl.returnStatementsWithExpressions.length; + }, + setTypeAtIndex: function (index, type) { + funcDecl.returnStatementsWithExpressions[index].type = type; + }, + getTypeAtIndex: function (index) { + return funcDecl.returnStatementsWithExpressions[index].type; + } + }; + var bestCommonReturnType = funcDecl.returnStatementsWithExpressions[0].type; + bestCommonReturnType = this.checker.findBestCommonType(bestCommonReturnType, null, collection, true); + if(bestCommonReturnType) { + signature.returnType.type = this.checker.widenType(bestCommonReturnType); + } else { + for(var i = 0; i < funcDecl.returnStatementsWithExpressions.length; i++) { + this.checker.errorReporter.simpleError(funcDecl.returnStatementsWithExpressions[i], "Incompatible return type"); + } + signature.returnType.type = this.anyType; + } + } + var onlyHasThrow = false; + if(signature.returnType.type == null) { + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.HasReturnExpression)) { + if(this.checker.styleSettings.implicitAny) { + this.checker.errorReporter.styleError(funcDecl, "type implicitly set to 'any'"); + } + signature.returnType.type = this.anyType; + } else { + signature.returnType.type = this.voidType; + } + } else { + if(signature.returnType.type == this.nullType || signature.returnType.type == this.checker.undefinedType) { + signature.returnType.type = this.anyType; + } else { + if((signature.returnType.type != this.voidType && signature.returnType.type != this.checker.undefinedType && signature.returnType.type != this.anyType)) { + if(!funcDecl.isSignature() && !funcDecl.isConstructor && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.HasReturnExpression) && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { + onlyHasThrow = (funcDecl.bod.members.length > 0) && (funcDecl.bod.members[0].nodeType == TypeScript.NodeType.Throw); + if(!onlyHasThrow) { + this.checker.errorReporter.simpleError(funcDecl.returnTypeAnnotation || funcDecl, "Function declared a non-void return type, but has no return expression"); + } + } + this.checkTypePrivacy(signature.returnType.type, container, function (typeName, isModuleName) { + return _this.functionReturnTypePrivacyErrorReporter(funcDecl, signature, typeName, isModuleName); + }); + } + } + } + if(funcDecl.accessorSymbol) { + var accessorType = funcDecl.accessorSymbol.getType(); + if(!onlyHasThrow && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor) && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.HasReturnExpression)) { + this.checker.errorReporter.simpleError(funcDecl, "Getters must return a value"); + } + if(accessorType) { + if((TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor) && accessorType != signature.returnType.type) || (funcDecl.arguments.members.length > 0 && accessorType != funcDecl.arguments.members[0].type)) { + this.checker.errorReporter.simpleError(funcDecl, "Getter and setter types do not agree"); + } + } else { + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { + funcDecl.accessorSymbol.setType(signature.returnType.type); + } else { + if(funcDecl.arguments.members.length != 1) { + this.checker.errorReporter.simpleError(funcDecl, "Setters may have one and only one argument"); + } else { + funcDecl.accessorSymbol.setType(funcDecl.arguments.members[0].type); + } + } + } + } + this.typeCheckOverloadSignatures(fnType, funcDecl); + return funcDecl; + }; + TypeFlow.prototype.typeCheckBases = function (type) { + var seenInterface = false; + var bases = type.extendsList; + var baseLinks = type.extendsTypeLinks; + if(bases) { + var len = bases.length; + if(len > 0) { + type.typeFlags |= TypeScript.TypeFlags.HasBaseType; + } + for(var i = 0; i < len; i++) { + if(bases[i] == this.checker.anyType) { + baseLinks[i].type = null; + var oldErrors = this.checker.errorReporter.getCapturedErrors(); + TypeScript.CompilerDiagnostics.assert(oldErrors.length == 0, "There shouldnt be any contextual errors when typechecking base type names"); + this.checker.errorReporter.pushToErrorSink = true; + bases[i] = this.checker.resolveBaseTypeLink(baseLinks[i], type.containedScope); + this.checker.errorReporter.pushToErrorSink = false; + this.checker.errorReporter.freeCapturedErrors(); + } + var base = bases[i]; + var baseRef = baseLinks[i].ast; + var baseTypeOfObject = base.symbol && base.symbol.name == "Object" && base.symbol.container == this.checker.gloMod; + if(baseTypeOfObject) { + type.typeFlags |= TypeScript.TypeFlags.HasBaseTypeOfObject; + } + if(base.isClassInstance()) { + if(!(type.isClassInstance())) { + this.checker.errorReporter.simpleError(baseRef, "Interface base type must be interface"); + } else { + if(seenInterface) { + this.checker.errorReporter.simpleError(baseRef, "Class may not follow interface as base type"); + } + } + } else { + if(base.isModuleType()) { + this.checker.errorReporter.simpleError(baseRef, "Types may not be derived from module types"); + } else { + if(base.members) { + if(!seenInterface) { + seenInterface = true; + } + } else { + if(!(type.isClassInstance())) { + this.checker.errorReporter.simpleError(baseRef, "Interface base type must be interface"); + } else { + this.checker.errorReporter.simpleError(baseRef, "Base type must be interface or class"); + } + break; + } + } + } + } + } + }; + TypeFlow.prototype.checkMembersImplementInterfaces = function (implementingType) { + var instanceType = implementingType.getInstanceType(); + if(instanceType.implementsList) { + var len = instanceType.implementsList.length; + for(var i = 0; i < len; i++) { + var interfaceType = instanceType.implementsList[i]; + var comparisonInfo = new TypeScript.TypeComparisonInfo(); + if(!this.checker.sourceIsSubtypeOfTarget(instanceType, interfaceType, comparisonInfo)) { + var emsg = "Class '" + instanceType.getTypeName() + "' declares interface '" + interfaceType.getTypeName() + "' but does not implement it"; + if(!comparisonInfo.message) { + this.checker.errorReporter.simpleErrorFromSym(instanceType.symbol, emsg); + } else { + this.checker.errorReporter.simpleErrorFromSym(instanceType.symbol, emsg + ": " + comparisonInfo.message); + } + } + } + } + }; + TypeFlow.prototype.typeCheckBaseCalls = function (bases) { + if(bases == null) { + return; + } + var basesLen = bases.members.length; + for(var i = 0; i < basesLen; i++) { + var baseExpr = bases.members[i]; + var baseSymbol = null; + if(baseExpr.nodeType == TypeScript.NodeType.Call) { + this.typeCheckNew(baseExpr); + } + } + }; + TypeFlow.prototype.assertUniqueNamesInBaseTypes = function (names, type, classDecl, checkUnique) { + var _this = this; + if(type) { + if(type.members) { + type.members.publicMembers.map(function (key, s, c) { + var sym = s; + var dup = names.lookup(sym.name); + if(dup) { + if(checkUnique) { + _this.checker.errorReporter.simpleError(classDecl, "duplicate member name in bases for " + classDecl.name.actualText + ": " + type.symbol.name + " and " + dup.container.name + " both contain member with name " + sym.name); + } + } else { + names.add(sym.name, sym); + } + }, null); + } + if(type.extendsList) { + var len = type.extendsList.length; + for(var i = 0; i < len; i++) { + if(!(type.extendsList[i].symbol.flags & TypeScript.SymbolFlags.RecursivelyReferenced)) { + this.assertUniqueNamesInBaseTypes(names, type.extendsList[i], classDecl, checkUnique); + } + } + } + } + }; + TypeFlow.prototype.checkBaseTypeMemberInheritance = function (derivedType, derivedTypeDecl) { + var _this = this; + var instanceType = derivedType.getInstanceType(); + if(instanceType.extendsList == null) { + return; + } + var len = instanceType.extendsList.length; + if(len > 0) { + var names = new TypeScript.StringHashTable(); + if(instanceType.isClassInstance()) { + for(var i = 0; i < len; i++) { + this.assertUniqueNamesInBaseTypes(names, instanceType.extendsList[i], derivedTypeDecl, i > 0); + } + } + if(instanceType.members) { + instanceType.members.publicMembers.map(function (key, s, c) { + var sym = s; + for(var j = 0; j < len; j++) { + var base = instanceType.extendsList[j]; + if(base.memberScope == null) { + _this.checker.errorReporter.simpleError(derivedTypeDecl, "Base type '" + base.symbol.name + "' lacks an implementation."); + } else { + var bSym = base.memberScope.find(sym.name, false, false); + if(bSym) { + var aType = sym.getType(); + var bType = bSym.getType(); + if(!(_this.checker.sourceIsSubtypeOfTarget(aType, bType))) { + _this.checker.errorReporter.simpleErrorFromSym(sym, "Type of overridden member '" + sym.name + "' is not subtype of original member defined by type '" + bSym.container.name + "'"); + } else { + if((sym.kind() == TypeScript.SymbolKind.Type) && (bSym.kind() == TypeScript.SymbolKind.Field)) { + _this.checker.errorReporter.simpleErrorFromSym(sym, "Cannot override field '" + sym.name + "' with method"); + } + } + } + } + } + }, null); + } + } + }; + TypeFlow.prototype.typeCheckClass = function (classDecl) { + var typeSymbol = classDecl.type.symbol; + if(typeSymbol.typeCheckStatus == TypeScript.TypeCheckStatus.Finished) { + return classDecl; + } else { + if(typeSymbol.typeCheckStatus == TypeScript.TypeCheckStatus.Started) { + return classDecl; + } else { + typeSymbol.typeCheckStatus = TypeScript.TypeCheckStatus.Started; + this.checker.addStartedPTO(typeSymbol); + } + } + var prevScope = this.scope; + var svClassNode = this.thisClassNode; + this.thisClassNode = classDecl; + var classType = classDecl.type; + this.typeCheckBases(classType.instanceType); + this.typeCheckBaseListPrivacy(classDecl.extendsList, typeSymbol, true); + this.typeCheckBaseListPrivacy(classDecl.implementsList, typeSymbol, false); + var prevThisType = this.thisType; + this.thisType = classType.instanceType; + this.scope = classType.instanceType.containedScope; + if(classDecl.constructorDecl) { + this.scope = classType.instanceType.constructorScope; + var ssb = this.scope; + var funcTable = ssb.valueMembers.allMembers; + this.addConstructorLocalArgs(classDecl.constructorDecl.type.symbol, classDecl.constructorDecl.arguments, funcTable, true); + } + this.typeCheck(classDecl.members); + typeSymbol.typeCheckStatus = TypeScript.TypeCheckStatus.Finished; + this.checkBaseTypeMemberInheritance(classType, classDecl); + this.checkMembersImplementInterfaces(classType); + this.typeCheckOverloadSignatures(classType, classDecl); + this.typeCheckOverloadSignatures(classType.instanceType, classDecl); + if(!classDecl.constructorDecl) { + if(classDecl.extendsList && classDecl.extendsList.members.length && classDecl.extendsList.members[0].type && classDecl.extendsList.members[0].type.symbol.type.isClass()) { + TypeScript.cloneParentConstructGroupForChildType(classDecl.type, classDecl.extendsList.members[0].type.symbol.type); + } + } + this.thisType = prevThisType; + this.thisClassNode = svClassNode; + this.scope = prevScope; + return classDecl; + }; + TypeFlow.prototype.typeCheckOverloadSignatures = function (type, ast) { + if(type.call) { + type.call.typeCheck(this.checker, ast, type.construct != null); + } + if(type.construct) { + type.construct.typeCheck(this.checker, ast, false); + } + if(type.index) { + type.index.typeCheck(this.checker, ast, false); + } + }; + TypeFlow.prototype.typeCheckInterface = function (interfaceDecl) { + this.typeCheckBases(interfaceDecl.type); + this.typeCheckBaseListPrivacy(interfaceDecl.extendsList, interfaceDecl.type.symbol, true); + this.typeCheck(interfaceDecl.members); + this.checkBaseTypeMemberInheritance(interfaceDecl.type, interfaceDecl); + if(interfaceDecl.extendsList) { + for(var i = 0; i < interfaceDecl.extendsList.members.length; i++) { + if(interfaceDecl.extendsList.members[i].type.call) { + if(interfaceDecl.type.call) { + interfaceDecl.type.call.signatures = interfaceDecl.type.call.signatures.concat(interfaceDecl.extendsList.members[i].type.call.signatures); + } else { + interfaceDecl.type.call = interfaceDecl.extendsList.members[i].type.call; + } + } + if(interfaceDecl.extendsList.members[i].type.construct) { + if(interfaceDecl.type.construct) { + interfaceDecl.type.construct.signatures = interfaceDecl.type.construct.signatures.concat(interfaceDecl.extendsList.members[i].type.construct.signatures); + } else { + interfaceDecl.type.construct = interfaceDecl.extendsList.members[i].type.construct; + } + } + if(interfaceDecl.extendsList.members[i].type.index) { + if(interfaceDecl.type.index) { + interfaceDecl.type.index.signatures = interfaceDecl.type.index.signatures.concat(interfaceDecl.extendsList.members[i].type.index.signatures); + } else { + interfaceDecl.type.index = interfaceDecl.extendsList.members[i].type.index; + } + } + } + } + return interfaceDecl; + }; + TypeFlow.prototype.typeCheckImportDecl = function (importDecl) { + var mod = importDecl.alias.type; + var sym = null; + var prevInImportTC = this.inImportTypeCheck; + this.inImportTypeCheck = true; + this.typeCheck(importDecl.alias); + mod = importDecl.alias.type; + if(mod == null) { + this.checker.errorReporter.simpleError(importDecl.alias, "Could not resolve module alias '" + importDecl.id.actualText + "'"); + mod = this.checker.anyType; + (importDecl.id.sym).type = mod; + } + importDecl.id.type = mod; + sym = mod.symbol; + if(!mod.isModuleType()) { + this.checker.errorReporter.simpleError(importDecl.alias, "A module cannot be aliased to a non-module type"); + } else { + sym.type = mod; + if(this.checker.typeFlow.currentScript && this.checker.typeFlow.currentScript.topLevelMod && this.checker.typeFlow.currentScript.topLevelMod.mod) { + this.checker.typeFlow.currentScript.topLevelMod.mod.importedModules.push(importDecl); + } + (importDecl.id.sym).type = mod; + if(mod.symbol && mod.symbol.declAST) { + (mod.symbol.declAST).modFlags &= ~TypeScript.ModuleFlags.ShouldEmitModuleDecl; + } + } + this.inImportTypeCheck = prevInImportTC; + return importDecl; + }; + TypeFlow.prototype.typeCheckModule = function (moduleDecl) { + if(!moduleDecl.mod) { + return moduleDecl; + } + if(this.currentScript) { + this.currentScript.requiresGlobal = true; + } + var mod = moduleDecl.mod; + var sym = null; + var prevScope = this.scope; + var prevThisType = this.thisType; + var prevCurrentModDecl = this.checker.currentModDecl; + this.checker.currentModDecl = moduleDecl; + this.thisType = null; + this.scope = mod.containedScope; + this.typeCheck(moduleDecl.members); + sym = mod.symbol; + this.checker.currentModDecl = prevCurrentModDecl; + this.thisType = prevThisType; + this.scope = prevScope; + moduleDecl.type = mod; + if(sym) { + sym.typeCheckStatus = TypeScript.TypeCheckStatus.Finished; + } + return moduleDecl; + }; + TypeFlow.prototype.typeCheckFor = function (forStmt) { + forStmt.init = this.typeCheck(forStmt.init); + this.nestingLevel++; + forStmt.cond = this.typeCheck(forStmt.cond); + this.typeCheckCondExpr(forStmt.cond); + forStmt.incr = this.typeCheck(forStmt.incr); + this.nestingLevel--; + forStmt.body = this.typeCheck(forStmt.body); + this.typeCheckCompoundStmtBlock(forStmt.body, "for statement"); + forStmt.type = this.voidType; + return forStmt; + }; + TypeFlow.prototype.typeCheckWith = function (withStmt) { + if(this.checker.errorsOnWith) { + this.checker.errorReporter.simpleError(withStmt.expr, "All symbols within a 'with' block will be typed as 'any'"); + } + withStmt.expr = this.typeCheck(withStmt.expr); + this.checker.inWith = true; + withStmt.body = this.typeCheck(withStmt.body); + this.typeCheckCompoundStmtBlock(withStmt.body, "with statement"); + this.checker.inWith = false; + return withStmt; + }; + TypeFlow.prototype.typeCheckForIn = function (forInStmt) { + forInStmt.obj = this.typeCheck(forInStmt.obj); + forInStmt.lval = this.cast(this.typeCheck(forInStmt.lval), this.checker.stringType); + if(forInStmt.lval.nodeType == TypeScript.NodeType.VarDecl) { + var varDecl = forInStmt.lval; + if(varDecl.typeExpr) { + this.checker.errorReporter.simpleError(varDecl, "Variable declarations for for/in expressions may not contain a type annotation"); + } + if(varDecl.sym) { + varDecl.sym.setType(this.checker.stringType); + } + } + forInStmt.body = this.typeCheck(forInStmt.body); + this.typeCheckCompoundStmtBlock(forInStmt.body, "for in statement"); + return forInStmt; + }; + TypeFlow.prototype.typeCheckWhile = function (whileStmt) { + whileStmt.cond = this.typeCheck(whileStmt.cond); + this.typeCheckCondExpr(whileStmt.cond); + whileStmt.body = this.typeCheck(whileStmt.body); + this.typeCheckCompoundStmtBlock(whileStmt.body, "while statement"); + whileStmt.type = this.voidType; + return whileStmt; + }; + TypeFlow.prototype.typeCheckDoWhile = function (doWhileStmt) { + doWhileStmt.cond = this.typeCheck(doWhileStmt.cond); + this.typeCheckCondExpr(doWhileStmt.cond); + doWhileStmt.body = this.typeCheck(doWhileStmt.body); + this.typeCheckCompoundStmtBlock(doWhileStmt.body, "do while statement"); + doWhileStmt.type = this.voidType; + return doWhileStmt; + }; + TypeFlow.prototype.typeCheckCondExpr = function (cond) { + if(this.checker.styleSettings.assignmentInCond) { + if((cond !== null) && (cond.nodeType >= TypeScript.NodeType.Asg) && (cond.nodeType <= TypeScript.NodeType.LastAsg)) { + this.checker.errorReporter.simpleError(cond, "top-level assignment statement in conditional expression"); + } + } + }; + TypeFlow.prototype.typeCheckCompoundStmtBlock = function (stmts, stmtType) { + if(this.checker.styleSettings.blockInCompoundStmt && stmts) { + if(stmts.nodeType != TypeScript.NodeType.Block) { + this.checker.errorReporter.styleError(stmts, stmtType + " requires a block"); + } + } + }; + TypeFlow.prototype.typeCheckIf = function (ifStmt) { + ifStmt.cond = this.typeCheck(ifStmt.cond); + this.typeCheckCondExpr(ifStmt.cond); + ifStmt.thenBod = this.typeCheck(ifStmt.thenBod); + ifStmt.elseBod = this.typeCheck(ifStmt.elseBod); + this.typeCheckCompoundStmtBlock(ifStmt.thenBod, "if statement"); + this.typeCheckCompoundStmtBlock(ifStmt.elseBod, "if statement"); + ifStmt.type = this.voidType; + return ifStmt; + }; + TypeFlow.prototype.typeFromAccessorFuncDecl = function (funcDecl) { + if(!funcDecl.isAccessor()) { + return null; + } + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { + return funcDecl.type.call.signatures[0].returnType.type; + } else { + return funcDecl.type.call.signatures[0].parameters[0].getType(); + } + }; + TypeFlow.prototype.typeCheckObjectLit = function (objectLit) { + var resultType = new TypeScript.Type(); + resultType.symbol = new TypeScript.TypeSymbol(this.checker.anon, objectLit.minChar, objectLit.limChar - objectLit.minChar, this.checker.locationInfo.unitIndex, resultType); + resultType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + resultType.memberScope = new TypeScript.SymbolTableScope(resultType.members, null, null, null, null); + var aggScope = new TypeScript.SymbolAggregateScope(resultType.symbol); + aggScope.addParentScope(resultType.memberScope); + aggScope.addParentScope(this.scope); + resultType.containedScope = aggScope; + var memberDecls = objectLit.operand; + var prevThisType = this.thisType; + var acceptTargetType = false; + var targetType = null; + if(this.checker.hasTargetType()) { + targetType = this.checker.getTargetTypeContext().contextualType; + if(targetType && targetType.symbol && !this.checker.typeStatusIsFinished(targetType.symbol.typeCheckStatus)) { + if(targetType.symbol.declAST) { + this.typeCheck(targetType.symbol.declAST); + } + } + acceptTargetType = true; + } + if(memberDecls) { + for(var i = 0, len = memberDecls.members.length; i < len; i++) { + var binex = memberDecls.members[i]; + var id = binex.operand1; + var text; + var targetMember = null; + var fieldSymbol = null; + if(id.nodeType == TypeScript.NodeType.Name) { + text = (id).text; + } else { + if(id.nodeType == TypeScript.NodeType.QString) { + var idText = (id).text; + text = idText.substring(1, idText.length - 1); + } else { + this.checker.errorReporter.simpleError(objectLit, "malformed object literal"); + resultType = this.anyType; + break; + } + } + if(acceptTargetType && targetType.memberScope) { + targetMember = targetType.memberScope.find(text, false, false); + } + if(binex.operand2.nodeType == TypeScript.NodeType.FuncDecl && (binex.operand2).isAccessor()) { + var funcDecl = binex.operand2; + var accessorSym = resultType.members.publicMembers.lookup(text); + accessorSym = this.checker.createAccessorSymbol(funcDecl, accessorSym, resultType, true, false, resultType.memberScope, null); + funcDecl.accessorSymbol = accessorSym; + fieldSymbol = accessorSym; + if(id.nodeType == TypeScript.NodeType.Name) { + (id).sym = accessorSym; + } + } + this.checker.typeCheckWithContextualType(acceptTargetType && targetMember ? targetMember.getType() : null, false, acceptTargetType, binex.operand2); + if(acceptTargetType && targetMember) { + if((binex.operand2.type == this.anyType || this.checker.sourceIsAssignableToTarget(binex.operand2.type, targetMember.getType())) || (binex.operand2.nodeType == TypeScript.NodeType.FuncDecl && (binex.operand2).isAccessor() && this.typeFromAccessorFuncDecl(binex.operand2) == targetMember.getType())) { + binex.operand1.type = targetMember.getType(); + } + } else { + binex.operand2.type = binex.operand2.type == this.checker.undefinedType ? this.anyType : binex.operand2.type; + } + if(fieldSymbol == null) { + var memberType = binex.operand2.type; + var field = new TypeScript.ValueLocation(); + fieldSymbol = new TypeScript.FieldSymbol(text, id.minChar, this.checker.locationInfo.unitIndex, true, field); + fieldSymbol.flags |= TypeScript.SymbolFlags.Property; + field.symbol = fieldSymbol; + fieldSymbol.typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); + field.typeLink = new TypeScript.TypeLink(); + field.typeLink.type = memberType; + resultType.members.publicMembers.add(text, fieldSymbol); + } + fieldSymbol.isObjectLitField = true; + } + } + this.thisType = prevThisType; + objectLit.type = resultType; + if(targetType) { + objectLit.targetType = targetType; + } + }; + TypeFlow.prototype.typeCheckArrayLit = function (arrayLit) { + var elements = arrayLit.operand; + var elementType = this.anyType; + var targetElementType = null; + var comparisonInfo = new TypeScript.TypeComparisonInfo(); + comparisonInfo.onlyCaptureFirstError = true; + if(this.checker.hasTargetType()) { + var targetType = this.checker.getTargetTypeContext().contextualType; + if(targetType.elementType) { + targetElementType = targetType.elementType; + } + } + if(elements) { + var prevInArrayElemTypeCheck = this.inArrayElementTypeCheck; + this.inArrayElementTypeCheck = true; + this.checker.typeCheckWithContextualType(targetElementType, this.checker.inProvisionalTypecheckMode(), targetElementType != null, elements); + this.inArrayElementTypeCheck = prevInArrayElemTypeCheck; + elementType = elements.members[0].type; + var collection = { + getLength: function () { + return elements.members.length; + }, + setTypeAtIndex: function (index, type) { + elements.members[index].type = type; + }, + getTypeAtIndex: function (index) { + return elements.members[index].type; + } + }; + elementType = this.checker.findBestCommonType(elementType, targetElementType, collection, false, comparisonInfo); + if(elementType == this.checker.undefinedType || (!prevInArrayElemTypeCheck && elementType == this.nullType)) { + elementType = this.anyType; + } + } + if(!elementType) { + var emsg = "Incompatible types in array literal expression"; + if(!comparisonInfo.message) { + this.checker.errorReporter.simpleError(arrayLit, emsg); + } else { + this.checker.errorReporter.simpleError(arrayLit, emsg + ": " + comparisonInfo.message); + } + elementType = this.anyType; + } else { + if(targetElementType) { + if(this.checker.sourceIsAssignableToTarget(elementType, targetElementType)) { + elementType = targetElementType; + } + } + } + arrayLit.type = this.checker.makeArrayType(elementType); + }; + TypeFlow.prototype.checkForVoidConstructor = function (type, ast) { + if(type && type.construct && type.construct.signatures.length > 0) { + for(var i = 0; i < type.construct.signatures.length; i++) { + if(type.construct.signatures[i].returnType.type == this.checker.voidType) { + this.checker.errorReporter.simpleError(ast, "Constructors may not have a return type of 'void'"); + break; + } + } + } + }; + TypeFlow.prototype.typeCheckReturn = function (returnStmt) { + if(this.thisFnc) { + var targetType = null; + if(this.checker.hasTargetType()) { + var tcContext = this.checker.getTargetTypeContext(); + var accessorType = tcContext.targetAccessorType; + if(accessorType) { + targetType = accessorType; + } else { + var targetSig = this.checker.getTargetTypeContext().targetSig; + if(targetSig && targetSig.returnType.type != this.voidType) { + targetType = targetSig.returnType.type; + } + } + } + if(returnStmt.returnExpression) { + this.thisFnc.fncFlags |= TypeScript.FncFlags.HasReturnExpression; + if(targetType == null && this.thisFnc.returnTypeAnnotation && this.thisFnc.returnTypeAnnotation.type && this.thisFnc.returnTypeAnnotation.type != this.voidType) { + targetType = this.thisFnc.returnTypeAnnotation.type; + } + this.checker.typeCheckWithContextualType(targetType, this.checker.inProvisionalTypecheckMode(), targetType != null, returnStmt.returnExpression); + var expectedReturnType = (this.thisFnc.returnTypeAnnotation && this.thisFnc.returnTypeAnnotation.type) ? this.thisFnc.returnTypeAnnotation.type : targetType; + if(expectedReturnType) { + if(expectedReturnType == this.voidType && returnStmt.returnExpression.type != this.voidType) { + this.checker.errorReporter.simpleError(returnStmt, "Return with value expression in void function"); + returnStmt.type = returnStmt.returnExpression.type; + } else { + returnStmt.returnExpression = this.cast(returnStmt.returnExpression, expectedReturnType); + returnStmt.type = expectedReturnType; + } + } else { + if(targetType) { + if(returnStmt.returnExpression.type != this.voidType) { + returnStmt.returnExpression = this.cast(returnStmt.returnExpression, targetType); + } else { + returnStmt.returnExpression.type = targetType; + } + } + returnStmt.type = returnStmt.returnExpression.type; + } + this.thisFnc.returnStatementsWithExpressions[this.thisFnc.returnStatementsWithExpressions.length] = returnStmt; + } else { + returnStmt.type = targetType == null ? this.checker.voidType : targetType; + } + } + return returnStmt; + }; + TypeFlow.prototype.typeCheckInstOf = function (ast) { + var binex = ast; + binex.operand1 = this.typeCheck(binex.operand1); + binex.operand2 = this.typeCheck(binex.operand2); + if(!((binex.operand1.type == this.checker.anyType || this.checker.sourceIsSubtypeOfTarget(binex.operand1.type, this.objectInterfaceType)) && (binex.operand2.type == this.anyType || this.checker.sourceIsSubtypeOfTarget(binex.operand2.type, this.functionInterfaceType)))) { + this.checker.errorReporter.simpleError(ast, "The instanceof operator requires the left operand to be of type Any or an object type, and the right operand to be of type Any or a subtype of the Function interface type"); + } + binex.type = this.booleanType; + return binex; + }; + TypeFlow.prototype.typeCheckCommaOperator = function (ast) { + var binex = ast; + binex.operand1 = this.typeCheck(binex.operand1); + binex.operand2 = this.typeCheck(binex.operand2); + binex.type = binex.operand2.type; + return binex; + }; + TypeFlow.prototype.typeCheckLogOr = function (binex) { + binex.operand1 = this.typeCheck(binex.operand1); + binex.operand2 = this.typeCheck(binex.operand2); + var leftType = binex.operand1.type; + var rightType = binex.operand2.type; + if(leftType == this.checker.anyType || rightType == this.checker.anyType) { + binex.type = this.checker.anyType; + } else { + if(leftType == this.checker.booleanType) { + if(rightType == this.checker.booleanType) { + binex.type = this.checker.booleanType; + } else { + binex.type = this.checker.anyType; + } + } else { + if(leftType == this.checker.numberType) { + if(rightType == this.checker.numberType) { + binex.type = this.checker.numberType; + } else { + binex.type = this.checker.anyType; + } + } else { + if(leftType == this.checker.stringType) { + if(rightType == this.checker.stringType) { + binex.type = this.checker.stringType; + } else { + binex.type = this.checker.anyType; + } + } else { + if(this.checker.sourceIsSubtypeOfTarget(leftType, rightType)) { + binex.type = rightType; + } else { + if(this.checker.sourceIsSubtypeOfTarget(rightType, leftType)) { + binex.type = leftType; + } else { + binex.type = this.checker.anyType; + } + } + } + } + } + } + return binex; + }; + TypeFlow.prototype.typeCheckLogAnd = function (binex) { + binex.operand1 = this.typeCheck(binex.operand1); + binex.operand2 = this.typeCheck(binex.operand2); + binex.type = binex.operand2.type; + return binex; + }; + TypeFlow.prototype.tryAddCandidates = function (signature, actuals, exactCandidates, conversionCandidates, comparisonInfo) { + var lowerBound = signature.nonOptionalParameterCount; + var upperBound = signature.parameters.length; + var formalLen = lowerBound; + var acceptable = false; + if((actuals.length >= lowerBound) && (signature.hasVariableArgList || actuals.length <= upperBound)) { + formalLen = (signature.hasVariableArgList ? signature.parameters.length : actuals.length); + acceptable = true; + } + var repeatType = null; + if(acceptable || signature.hasVariableArgList) { + if(signature.hasVariableArgList) { + formalLen -= 1; + repeatType = (signature.parameters[formalLen]).parameter.typeLink.type; + repeatType = repeatType.elementType; + acceptable = actuals.length >= formalLen; + } + var len = actuals.length; + var exact = acceptable; + var convert = acceptable; + for(var i = 0; i < len; i++) { + var typeA; + if(i < formalLen) { + typeA = (signature.parameters[i]).parameter.typeLink.type; + } else { + typeA = repeatType; + } + var typeB = actuals[i]; + if(!typeA || !typeB || !(this.checker.typesAreIdentical(typeA, typeB))) { + exact = false; + } + if(!this.checker.sourceIsAssignableToTarget(typeB, typeA, comparisonInfo)) { + convert = false; + } + if(!(exact || convert)) { + break; + } + } + if(exact) { + exactCandidates[exactCandidates.length] = signature; + } else { + if(convert && (exactCandidates.length == 0)) { + conversionCandidates[conversionCandidates.length] = signature; + } + } + } + }; + TypeFlow.prototype.resolveOverload = function (application, group) { + var rd = this.resolutionDataCache.getResolutionData(); + var actuals = rd.actuals; + var exactCandidates = rd.exactCandidates; + var conversionCandidates = rd.conversionCandidates; + var candidate = null; + var hasOverloads = group.signatures.length > 1; + var comparisonInfo = new TypeScript.TypeComparisonInfo(); + var args = null; + var target = null; + if(application.nodeType == TypeScript.NodeType.Call || application.nodeType == TypeScript.NodeType.New) { + var callEx = application; + args = callEx.arguments; + target = callEx.target; + if(callEx.arguments) { + var len = callEx.arguments.members.length; + for(var i = 0; i < len; i++) { + actuals[i] = callEx.arguments.members[i].type; + } + } + } else { + if(application.nodeType == TypeScript.NodeType.Index) { + var binExp = application; + target = binExp.operand1; + args = new TypeScript.ASTList(); + args.members[0] = binExp.operand2; + actuals[0] = binExp.operand2.type; + } + } + for(var j = 0, groupLen = group.signatures.length; j < groupLen; j++) { + var signature = group.signatures[j]; + if(hasOverloads && signature == group.definitionSignature && !this.checker.canCallDefinitionSignature) { + continue; + } + if(!signature.returnType.type && signature.declAST && (signature.typeCheckStatus != TypeScript.TypeCheckStatus.Finished)) { + this.typeCheckFunction(signature.declAST); + } + this.tryAddCandidates(signature, actuals, exactCandidates, conversionCandidates, comparisonInfo); + } + if(exactCandidates.length == 0) { + var applicableCandidates = this.checker.getApplicableSignatures(conversionCandidates, args, comparisonInfo); + if(applicableCandidates.length > 0) { + var candidateInfo = this.checker.findMostApplicableSignature(applicableCandidates, args); + if(candidateInfo.ambiguous) { + this.checker.errorReporter.simpleError(target, "Ambiguous call expression - could not choose overload"); + } + candidate = candidateInfo.sig; + } else { + var emsg = "Supplied parameters do not match any signature of call target"; + if(comparisonInfo.message) { + this.checker.errorReporter.simpleError(target, emsg + ":\n\t" + comparisonInfo.message); + } else { + this.checker.errorReporter.simpleError(target, emsg); + } + } + } else { + if(exactCandidates.length > 1) { + var applicableSigs = []; + for(var i = 0; i < exactCandidates.length; i++) { + applicableSigs[i] = { + signature: exactCandidates[i], + hadProvisionalErrors: false + }; + } + var candidateInfo = this.checker.findMostApplicableSignature(applicableSigs, args); + if(candidateInfo.ambiguous) { + this.checker.errorReporter.simpleError(target, "Ambiguous call expression - could not choose overload"); + } + candidate = candidateInfo.sig; + } else { + candidate = exactCandidates[0]; + } + } + this.resolutionDataCache.returnResolutionData(rd); + return candidate; + }; + TypeFlow.prototype.typeCheckNew = function (ast) { + var callEx = ast; + callEx.target = this.typeCheck(callEx.target); + var target = callEx.target; + if(target.type.construct || target.type.call) { + this.preTypeCheckCallArgs(callEx.arguments); + } else { + callEx.arguments = this.typeCheck(callEx.arguments); + } + if(target.type == this.anyType) { + callEx.type = this.anyType; + callEx.arguments = this.typeCheck(callEx.arguments); + } else { + if(target.type.construct) { + var signature = this.resolveOverload(callEx, target.type.construct); + if(signature == null) { + callEx.type = this.anyType; + } else { + if(signature.returnType.type == this.voidType) { + callEx.type = this.anyType; + callEx.signature = signature; + } else { + callEx.type = signature.returnType.type; + callEx.signature = signature; + } + } + } else { + if(target.type.call) { + var signature = this.resolveOverload(callEx, target.type.call); + if(signature == null) { + callEx.type = this.anyType; + } else { + if((signature.returnType.type == this.voidType) || (signature.returnType.type == this.anyType)) { + callEx.type = this.anyType; + callEx.signature = signature; + } else { + this.checker.errorReporter.simpleError(callEx.target, "new expression only valid on constructors"); + } + } + } else { + if(target.type.elementType) { + callEx.type = target.type; + } else { + this.checker.errorReporter.invalidCall(callEx, callEx.nodeType, this.scope); + callEx.type = this.anyType; + } + } + } + } + this.postTypeCheckCallArgs(callEx); + return callEx; + }; + TypeFlow.prototype.preTypeCheckCallArgs = function (args) { + if(!args) { + return; + } + for(var i = 0; i < args.members.length; i++) { + switch(args.members[i].nodeType) { + case TypeScript.NodeType.FuncDecl: + case TypeScript.NodeType.ObjectLit: + case TypeScript.NodeType.ArrayLit: { + continue; + + } + default: { + this.typeCheck(args.members[i]); + break; + + } + } + } + }; + TypeFlow.prototype.postTypeCheckCallArgs = function (callEx) { + var acceptedTargetType = false; + var i = 0; + if(callEx.target && callEx.target.type && callEx.signature && callEx.arguments) { + var sig = callEx.signature; + if(sig && callEx.arguments.members.length >= sig.nonOptionalParameterCount) { + acceptedTargetType = true; + var targetType = null; + var nonVarArgFormalParamLength = sig.hasVariableArgList ? sig.parameters.length - 1 : sig.parameters.length; + var nonVarArgActualParamLength = callEx.arguments.members.length < nonVarArgFormalParamLength ? callEx.arguments.members.length : nonVarArgFormalParamLength; + for(i = 0; i < nonVarArgActualParamLength; i++) { + targetType = sig.parameters[i].getType(); + switch(callEx.arguments.members[i].nodeType) { + case TypeScript.NodeType.FuncDecl: + case TypeScript.NodeType.ObjectLit: + case TypeScript.NodeType.ArrayLit: { + this.checker.typeCheckWithContextualType(targetType, this.checker.inProvisionalTypecheckMode(), !sig.parameters[i].declAST.isParenthesized, callEx.arguments.members[i]); + break; + + } + } + } + if(sig.hasVariableArgList) { + var varArgParamIndex = sig.nonOptionalParameterCount - 1; + targetType = sig.parameters[varArgParamIndex].getType(); + if(targetType) { + targetType = targetType.elementType; + } + var isParenthesized = !sig.parameters[varArgParamIndex].declAST.isParenthesized; + for(i = nonVarArgActualParamLength; i < callEx.arguments.members.length; i++) { + switch(callEx.arguments.members[i].nodeType) { + case TypeScript.NodeType.FuncDecl: + case TypeScript.NodeType.ObjectLit: + case TypeScript.NodeType.ArrayLit: { + this.checker.typeCheckWithContextualType(targetType, this.checker.inProvisionalTypecheckMode(), isParenthesized, callEx.arguments.members[i]); + break; + + } + } + } + } + } + } + if(!acceptedTargetType && callEx.arguments) { + this.checker.killCurrentContextualType(); + for(i = 0; i < callEx.arguments.members.length; i++) { + switch(callEx.arguments.members[i].nodeType) { + case TypeScript.NodeType.FuncDecl: + case TypeScript.NodeType.ObjectLit: + case TypeScript.NodeType.ArrayLit: { + this.typeCheck(callEx.arguments.members[i]); + break; + + } + default: { + continue; + + } + } + } + } + }; + TypeFlow.prototype.typeCheckCall = function (ast) { + var callEx = ast; + if(this.checker.styleSettings.newMustBeUsed && (ast.nodeType == TypeScript.NodeType.New)) { + if(TypeScript.hasFlag(ast.flags, TypeScript.ASTFlags.IsStatement)) { + this.checker.errorReporter.styleError(ast, "use of new expression as a statement"); + } + } else { + if((!this.checker.styleSettings.evalOK) && (ast.nodeType == TypeScript.NodeType.Call)) { + if((callEx.target.nodeType == TypeScript.NodeType.Name) && ((callEx.target).text == "eval")) { + this.checker.errorReporter.styleError(callEx, "eval not permitted"); + } + } + } + if(callEx.target.nodeType == TypeScript.NodeType.FuncDecl) { + (callEx.target).isInlineCallLiteral = true; + } + var prevInSuperCall = this.inSuperCall; + if(callEx.target.nodeType == TypeScript.NodeType.Super) { + this.inSuperCall = true; + } + callEx.target = this.typeCheck(callEx.target); + this.preTypeCheckCallArgs(callEx.arguments); + var target = callEx.target; + if((target.type == null) || (target.type == this.anyType) || (this.functionInterfaceType && target.type == this.functionInterfaceType)) { + callEx.type = this.anyType; + } else { + var fnType = target.type; + if(fnType.call) { + var signature = this.resolveOverload(callEx, fnType.call); + if(signature == null) { + callEx.type = this.anyType; + } else { + callEx.type = signature.returnType.type; + callEx.signature = signature; + } + } else { + if(callEx.target.nodeType == TypeScript.NodeType.Super && this.thisFnc && this.thisFnc.isConstructor && TypeScript.hasFlag(this.thisFnc.fncFlags, TypeScript.FncFlags.ClassMethod)) { + var signature = fnType.symbol.type.construct ? this.resolveOverload(callEx, fnType.symbol.type.construct) : null; + if(signature == null) { + callEx.type = this.anyType; + } else { + callEx.flags |= TypeScript.ASTFlags.ClassBaseConstructorCall; + callEx.type = signature.returnType.type; + callEx.signature = signature; + } + } else { + callEx.type = this.anyType; + this.checker.errorReporter.invalidCall(callEx, callEx.nodeType, this.scope); + } + } + } + this.postTypeCheckCallArgs(callEx); + this.inSuperCall = prevInSuperCall; + return callEx; + }; + TypeFlow.prototype.assignScopes = function (ast) { + var script = ast; + this.checker.locationInfo = script.locationInfo; + var globalChain = new ScopeChain(this.checker.gloMod, null, this.globalScope); + var context = new TypeScript.AssignScopeContext(globalChain, this, [ + this.checker.currentModDecl + ]); + TypeScript.getAstWalkerFactory().walk(ast, TypeScript.preAssignScopes, TypeScript.postAssignScopes, null, context); + }; + TypeFlow.prototype.findMemberScope = function (enclosingScopeContext, matchFlag) { + var enclosingScope = enclosingScopeContext.getScope(); + var pos = enclosingScopeContext.pos - enclosingScopeContext.getScriptFragmentPosition(); + var scriptFragment = enclosingScopeContext.getScriptFragment(); + var memContext = new TypeScript.MemberScopeContext(this, pos, matchFlag); + memContext.scope = enclosingScope; + if(scriptFragment.nodeType == TypeScript.NodeType.Name) { + return scriptFragment.type.getMemberScope(this); + } else { + TypeScript.getAstWalkerFactory().walk(scriptFragment, TypeScript.preFindMemberScope, null, null, memContext); + if(memContext.ast && enclosingScopeContext.enclosingClassDecl && memContext.ast.type == enclosingScopeContext.enclosingClassDecl.type.instanceType) { + enclosingScopeContext.publicsOnly = false; + } + if(memContext.type) { + return memContext.type.getMemberScope(this); + } else { + return null; + } + } + }; + TypeFlow.prototype.findMemberScopeAt = function (enclosingScopeContext) { + return this.findMemberScope(enclosingScopeContext, TypeScript.ASTFlags.DotLHS); + }; + TypeFlow.prototype.findMemberScopeAtFullAst = function (enclosingScopeContext) { + var matchFlag = TypeScript.ASTFlags.DotLHS; + var pos = enclosingScopeContext.pos; + var astResult = null; + var preFindMemberScopeFullAst = function (ast, parent, walker) { + if(TypeScript.isValidAstNode(ast)) { + if(TypeScript.hasFlag(ast.flags, matchFlag) && (pos == ast.limChar || (pos - 1) == ast.limChar)) { + astResult = ast; + walker.options.stopWalk(); + } + walker.options.goChildren = (ast.minChar <= pos) && (pos <= ast.limChar); + } + return ast; + }; + var preFindMemberScopeFullAstFuzy = function (ast, parent, walker) { + if(TypeScript.isValidAstNode(ast)) { + if(TypeScript.hasFlag(ast.flags, matchFlag) && ((ast.minChar < pos) && (pos <= ast.limChar))) { + astResult = ast; + } + walker.options.goChildren = (ast.minChar <= pos) && (pos <= ast.limChar); + } + return ast; + }; + TypeScript.getAstWalkerFactory().walk(enclosingScopeContext.script, preFindMemberScopeFullAst); + if(astResult == null) { + TypeScript.getAstWalkerFactory().walk(enclosingScopeContext.script, preFindMemberScopeFullAstFuzy); + } + if(astResult && enclosingScopeContext.enclosingClassDecl && astResult.type == enclosingScopeContext.enclosingClassDecl.type.instanceType) { + enclosingScopeContext.publicsOnly = false; + } + if(astResult && astResult.type) { + return astResult.type.getMemberScope(this); + } else { + return null; + } + }; + return TypeFlow; + })(); + TypeScript.TypeFlow = TypeFlow; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Primitive) { + Primitive._map = []; + Primitive.None = 0; + Primitive.Void = 1; + Primitive.Double = 2; + Primitive.String = 4; + Primitive.Boolean = 8; + Primitive.Any = 16; + Primitive.Null = 32; + Primitive.Undefined = 64; + })(TypeScript.Primitive || (TypeScript.Primitive = {})); + var Primitive = TypeScript.Primitive; + var MemberName = (function () { + function MemberName() { + this.prefix = ""; + this.suffix = ""; + } + MemberName.prototype.isString = function () { + return false; + }; + MemberName.prototype.isArray = function () { + return false; + }; + MemberName.prototype.toString = function () { + return MemberName.memberNameToString(this); + }; + MemberName.memberNameToString = function memberNameToString(memberName) { + var result = memberName.prefix; + if(memberName.isString()) { + result += (memberName).text; + } else { + var ar = memberName; + for(var index = 0; index < ar.entries.length; index++) { + result += MemberName.memberNameToString(ar.entries[index]); + result += ar.delim; + } + } + result += memberName.suffix; + return result; + } + MemberName.create = function create(arg1, arg2, arg3) { + if(typeof arg1 == "string") { + return new MemberNameString(arg1); + } else { + var result = new MemberNameArray(); + if(arg2) { + result.prefix = arg2; + } + if(arg3) { + result.suffix = arg3; + } + result.entries.push(arg1); + return result; + } + } + return MemberName; + })(); + TypeScript.MemberName = MemberName; + var MemberNameString = (function (_super) { + __extends(MemberNameString, _super); + function MemberNameString(text) { + _super.call(this); + this.text = text; + } + MemberNameString.prototype.isString = function () { + return true; + }; + return MemberNameString; + })(MemberName); + TypeScript.MemberNameString = MemberNameString; + var MemberNameArray = (function (_super) { + __extends(MemberNameArray, _super); + function MemberNameArray() { + _super.apply(this, arguments); + + this.delim = ""; + this.entries = []; + } + MemberNameArray.prototype.isArray = function () { + return true; + }; + MemberNameArray.prototype.add = function (entry) { + this.entries.push(entry); + }; + MemberNameArray.prototype.addAll = function (entries) { + for(var i = 0; i < entries.length; i++) { + this.entries.push(entries[i]); + } + }; + return MemberNameArray; + })(MemberName); + TypeScript.MemberNameArray = MemberNameArray; + var currentTypeID = -1; + var Type = (function () { + function Type() { + this.typeID = currentTypeID++; + this.construct = null; + this.call = null; + this.index = null; + this.passTypeCreated = TypeScript.CompilerDiagnostics.analysisPass; + this.primitiveTypeClass = Primitive.None; + this.typeFlags = TypeScript.TypeFlags.None; + } + Type.prototype.baseClass = function () { + if(this.extendsList && (this.extendsList.length > 0)) { + return this.extendsList[0]; + } else { + return null; + } + }; + Type.prototype.getArrayBase = function (arrInstType, checker) { + return this.arrayCache.specialize(arrInstType, checker); + }; + Type.prototype.isClass = function () { + return this.instanceType != null; + }; + Type.prototype.isArray = function () { + return this.elementType != null; + }; + Type.prototype.isClassInstance = function () { + return this.symbol && !this.elementType && (this.symbol).type.isClass(); + }; + Type.prototype.getInstanceType = function () { + if(this.isClass()) { + return this.instanceType; + } else { + return this; + } + }; + Type.prototype.hasImplementation = function () { + return TypeScript.hasFlag(this.typeFlags, TypeScript.TypeFlags.HasImplementation); + }; + Type.prototype.setHasImplementation = function () { + this.typeFlags |= TypeScript.TypeFlags.HasImplementation; + }; + Type.prototype.isDouble = function () { + return TypeScript.hasFlag(this.primitiveTypeClass, Primitive.Double); + }; + Type.prototype.isString = function () { + return TypeScript.hasFlag(this.primitiveTypeClass, Primitive.String); + }; + Type.prototype.isBoolean = function () { + return TypeScript.hasFlag(this.primitiveTypeClass, Primitive.Boolean); + }; + Type.prototype.isNull = function () { + return TypeScript.hasFlag(this.primitiveTypeClass, Primitive.Null); + }; + Type.prototype.getTypeName = function () { + return this.getMemberTypeName("", true, false, null); + }; + Type.prototype.getScopedTypeName = function (scope) { + return this.getMemberTypeName("", true, false, scope); + }; + Type.prototype.getScopedTypeNameEx = function (scope) { + return this.getMemberTypeNameEx("", true, false, scope); + }; + Type.prototype.callCount = function () { + var total = 0; + if(this.call) { + total += this.call.signatures.length; + } + if(this.construct) { + total += this.construct.signatures.length; + } + if(this.index) { + total += this.index.signatures.length; + } + return total; + }; + Type.prototype.getMemberTypeName = function (prefix, topLevel, isElementType, scope) { + var memberName = this.getMemberTypeNameEx(prefix, topLevel, isElementType, scope); + return memberName.toString(); + }; + Type.prototype.getMemberTypeNameEx = function (prefix, topLevel, isElementType, scope) { + if(this.elementType) { + return MemberName.create(this.elementType.getMemberTypeNameEx(prefix, false, true, scope), "", "[]"); + } else { + if(this.symbol && this.symbol.name && this.symbol.name != "_anonymous" && (((this.call == null) && (this.construct == null) && (this.index == null)) || (TypeScript.hasFlag(this.typeFlags, TypeScript.TypeFlags.BuildingName)) || (this.members && (!this.isClass())))) { + var tn = this.symbol.scopeRelativeName(scope); + return MemberName.create(tn == "null" ? "any" : tn); + } else { + if(this.members || this.call || this.construct) { + if(TypeScript.hasFlag(this.typeFlags, TypeScript.TypeFlags.BuildingName)) { + return MemberName.create("this"); + } + this.typeFlags |= TypeScript.TypeFlags.BuildingName; + var builder = ""; + var allMemberNames = new MemberNameArray(); + var curlies = isElementType || this.index != null; + var memCount = 0; + var delim = "; "; + if(this.members) { + this.members.allMembers.map(function (key, s, unused) { + var sym = s; + if(!TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.BuiltIn)) { + var typeNameMember = sym.getTypeNameEx(scope); + if(typeNameMember.isArray() && (typeNameMember).delim == delim) { + allMemberNames.addAll((typeNameMember).entries); + } else { + allMemberNames.add(typeNameMember); + } + memCount++; + curlies = true; + } + }, null); + } + var signatureCount = this.callCount(); + var j; + var len = 0; + var shortform = !curlies && signatureCount == 1 && topLevel; + if(this.call) { + allMemberNames.addAll(this.call.toStrings(prefix, shortform, scope)); + } + if(this.construct) { + allMemberNames.addAll(this.construct.toStrings("new", shortform, scope)); + } + if(this.index) { + allMemberNames.addAll(this.index.toStrings("", shortform, scope)); + } + if((curlies) || ((signatureCount > 1) && topLevel)) { + allMemberNames.prefix = "{ "; + allMemberNames.suffix = "}"; + allMemberNames.delim = delim; + } else { + if(allMemberNames.entries.length > 1) { + allMemberNames.delim = delim; + } + } + this.typeFlags &= (~TypeScript.TypeFlags.BuildingName); + if((signatureCount == 0) && (memCount == 0)) { + return MemberName.create("{}"); + } else { + return allMemberNames; + } + } else { + return MemberName.create("{}"); + } + } + } + }; + Type.prototype.checkDecl = function (checker) { + if(this.isClassInstance() || this.isClass()) { + if(this.symbol.declAST) { + checker.typeFlow.inScopeTypeCheckDecl(this.symbol.declAST); + } + } + }; + Type.prototype.getMemberScope = function (flow) { + if(this == flow.anyType) { + return null; + } else { + if(this.isDouble()) { + if(flow.numberInterfaceType) { + return flow.numberInterfaceType.memberScope; + } else { + return null; + } + } else { + if(this.isBoolean()) { + if(flow.booleanInterfaceType) { + return flow.booleanInterfaceType.memberScope; + } else { + return null; + } + } else { + if(this == flow.stringType) { + if(flow.stringInterfaceType) { + return flow.stringInterfaceType.memberScope; + } else { + return null; + } + } else { + if(this.elementType) { + if(flow.arrayInterfaceType) { + var arrInstType = this.elementType.getArrayBase(flow.arrayInterfaceType, flow.checker); + return arrInstType.memberScope; + } else { + return null; + } + } else { + return this.memberScope; + } + } + } + } + } + }; + Type.prototype.isReferenceType = function () { + return this.members || this.extendsList || this.construct || this.call || this.index || this.elementType; + }; + Type.prototype.specializeType = function (pattern, replacement, checker, membersOnly) { + if(pattern == this) { + return replacement; + } + var result = this; + if(membersOnly) { + if(this.isReferenceType()) { + result = new Type(); + if(this.members) { + result.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + this.members.publicMembers.map(function (key, s, unused) { + var sym = s; + var bSym = sym.specializeType(pattern, replacement, checker); + result.members.addPublicMember(bSym.name, bSym); + }, null); + this.members.privateMembers.map(function (key, s, unused) { + var sym = s; + var bSym = sym.specializeType(pattern, replacement, checker); + result.members.addPrivateMember(bSym.name, bSym); + }, null); + } + if(this.ambientMembers) { + result.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + this.ambientMembers.publicMembers.map(function (key, s, unused) { + var sym = s; + var bSym = sym.specializeType(pattern, replacement, checker); + result.ambientMembers.addPublicMember(bSym.name, bSym); + }, null); + this.ambientMembers.privateMembers.map(function (key, s, unused) { + var sym = s; + var bSym = sym.specializeType(pattern, replacement, checker); + result.ambientMembers.addPrivateMember(bSym.name, bSym); + }, null); + } + result.containedScope = checker.scopeOf(result); + result.memberScope = result.containedScope; + } + } else { + if(this.elementType) { + if(this.elementType == pattern) { + result = checker.makeArrayType(replacement); + } else { + if(this.elementType.elementType == pattern) { + result = checker.makeArrayType(checker.makeArrayType(replacement)); + } + } + } else { + if(this.call) { + result = new Type(); + result.call = this.call.specializeType(pattern, replacement, checker); + } + } + } + return result; + }; + Type.prototype.hasBase = function (baseType) { + if(baseType == this) { + return true; + } else { + if(this.extendsList) { + for(var i = 0, len = this.extendsList.length; i < len; i++) { + if(this.extendsList[i].hasBase(baseType)) { + return true; + } + } + } + } + return false; + }; + Type.prototype.mergeOrdered = function (b, checker, acceptVoid, comparisonInfo) { + if((this == checker.anyType) || (b == checker.anyType)) { + return checker.anyType; + } else { + if(this == b) { + return this; + } else { + if((b == checker.nullType) && this != checker.nullType) { + return this; + } else { + if((this == checker.nullType) && (b != checker.nullType)) { + return b; + } else { + if(acceptVoid && (b == checker.voidType) && this != checker.voidType) { + return this; + } else { + if(acceptVoid && (this == checker.voidType) && (b != checker.voidType)) { + return b; + } else { + if((b == checker.undefinedType) && this != checker.undefinedType) { + return this; + } else { + if((this == checker.undefinedType) && (b != checker.undefinedType)) { + return b; + } else { + if(this.elementType && b.elementType) { + if(this.elementType == b.elementType) { + return this; + } else { + var mergedET = this.elementType.mergeOrdered(b.elementType, checker, acceptVoid, comparisonInfo); + if(mergedET == null) { + return checker.makeArrayType(checker.anyType); + } else { + return checker.makeArrayType(mergedET); + } + } + } else { + if(checker.sourceIsSubtypeOfTarget(this, b, comparisonInfo)) { + return b; + } else { + if(checker.sourceIsSubtypeOfTarget(b, this, comparisonInfo)) { + return this; + } else { + return null; + } + } + } + } + } + } + } + } + } + } + } + }; + Type.prototype.isModuleType = function () { + return false; + }; + Type.prototype.hasMembers = function () { + return this.members != null; + }; + Type.prototype.getAllEnclosedTypes = function () { + return null; + }; + Type.prototype.getAllAmbientEnclosedTypes = function () { + return null; + }; + Type.prototype.getPublicEnclosedTypes = function () { + return null; + }; + Type.prototype.getpublicAmbientEnclosedTypes = function () { + return null; + }; + Type.prototype.getDocComments = function () { + if(this.elementType || !this.symbol) { + return []; + } + if(this.isClassInstance() || this.isClass()) { + if(this.symbol.declAST.nodeType == TypeScript.NodeType.FuncDecl) { + return (this.symbol.declAST).classDecl.getDocComments(); + } else { + return this.symbol.getDocComments(); + } + } + if(this.symbol.name && this.symbol.name != "_anonymous" && (((this.call == null) && (this.construct == null) && (this.index == null)) || this.members)) { + return this.symbol.getDocComments(); + } + return []; + }; + return Type; + })(); + TypeScript.Type = Type; + var ModuleType = (function (_super) { + __extends(ModuleType, _super); + function ModuleType(enclosedTypes, ambientEnclosedTypes) { + _super.call(this); + this.enclosedTypes = enclosedTypes; + this.ambientEnclosedTypes = ambientEnclosedTypes; + this.importedModules = []; + } + ModuleType.prototype.isModuleType = function () { + return true; + }; + ModuleType.prototype.hasMembers = function () { + return this.members != null || this.enclosedTypes != null; + }; + ModuleType.prototype.getAllEnclosedTypes = function () { + return this.enclosedTypes; + }; + ModuleType.prototype.getAllAmbientEnclosedTypes = function () { + return this.ambientEnclosedTypes; + }; + ModuleType.prototype.getPublicEnclosedTypes = function () { + return null; + }; + ModuleType.prototype.getpublicAmbientEnclosedTypes = function () { + return null; + }; + ModuleType.findDynamicModuleNameInHashTable = function findDynamicModuleNameInHashTable(moduleType, members) { + var moduleName = null; + members.map(function (key, s, c) { + if(moduleName == null && !TypeScript.isQuoted(key)) { + var symbol = s; + var type = symbol.getType(); + if(type == moduleType) { + moduleName = { + name: key, + symbol: symbol + }; + } + } + }, null); + return moduleName; + } + ModuleType.prototype.findDynamicModuleName = function (moduleType) { + var moduleName = null; + moduleName = ModuleType.findDynamicModuleNameInHashTable(moduleType, this.members.allMembers); + if(moduleName == null) { + moduleName = ModuleType.findDynamicModuleNameInHashTable(moduleType, this.ambientMembers.allMembers); + } + return moduleName; + }; + return ModuleType; + })(Type); + TypeScript.ModuleType = ModuleType; + var TypeLink = (function () { + function TypeLink() { + this.type = null; + this.ast = null; + } + return TypeLink; + })(); + TypeScript.TypeLink = TypeLink; + function getTypeLink(ast, checker, autoVar) { + var result = new TypeLink(); + result.ast = ast; + if((ast == null) && (autoVar)) { + result.type = checker.anyType; + } else { + result.type = null; + } + return result; + } + TypeScript.getTypeLink = getTypeLink; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + function stripQuotes(str) { + return str.replace("\"", "").replace("'", "").replace("'", "").replace("\"", ""); + } + TypeScript.stripQuotes = stripQuotes; + function isQuoted(str) { + return str.indexOf("\"") != -1 || str.indexOf("'") != -1 || str.indexOf("'") != -1 || str.indexOf("\"") != -1; + } + TypeScript.isQuoted = isQuoted; + function quoteStr(str) { + return "\"" + str + "\""; + } + TypeScript.quoteStr = quoteStr; + function swapQuotes(str) { + if(str.indexOf("\"") != -1) { + str = str.replace("\"", "'"); + str = str.replace("\"", "'"); + } else { + str = str.replace("'", "\""); + str = str.replace("'", "\""); + } + return str; + } + TypeScript.swapQuotes = swapQuotes; + function switchToForwardSlashes(path) { + return path.replace(/\\/g, "/"); + } + TypeScript.switchToForwardSlashes = switchToForwardSlashes; + function trimModName(modName) { + if(modName.length > 6 && modName.substring(modName.length - 6, modName.length) == ".d.str") { + return modName.substring(0, modName.length - 6); + } + if(modName.length > 4 && modName.substring(modName.length - 4, modName.length) == ".str") { + return modName.substring(0, modName.length - 4); + } + if(modName.length > 5 && modName.substring(modName.length - 5, modName.length) == ".d.ts") { + return modName.substring(0, modName.length - 5); + } + if(modName.length > 3 && modName.substring(modName.length - 3, modName.length) == ".ts") { + return modName.substring(0, modName.length - 3); + } + if(modName.length > 3 && modName.substring(modName.length - 3, modName.length) == ".js") { + return modName.substring(0, modName.length - 3); + } + return modName; + } + TypeScript.trimModName = trimModName; + function getDeclareFilePath(fname) { + return isSTRFile(fname) ? changePathToDSTR(fname) : isTSFile(fname) ? changePathToDTS(fname) : changePathToDTS(fname); + } + TypeScript.getDeclareFilePath = getDeclareFilePath; + function isFileOfExtension(fname, ext) { + var invariantFname = fname.toLocaleUpperCase(); + var invariantExt = ext.toLocaleUpperCase(); + var extLength = invariantExt.length; + return invariantFname.length > extLength && invariantFname.substring(invariantFname.length - extLength, invariantFname.length) == invariantExt; + } + function isJSFile(fname) { + return isFileOfExtension(fname, ".js"); + } + TypeScript.isJSFile = isJSFile; + function isSTRFile(fname) { + return isFileOfExtension(fname, ".str"); + } + TypeScript.isSTRFile = isSTRFile; + function isTSFile(fname) { + return isFileOfExtension(fname, ".ts"); + } + TypeScript.isTSFile = isTSFile; + function isDSTRFile(fname) { + return isFileOfExtension(fname, ".d.str"); + } + TypeScript.isDSTRFile = isDSTRFile; + function isDTSFile(fname) { + return isFileOfExtension(fname, ".d.ts"); + } + TypeScript.isDTSFile = isDTSFile; + function getPrettyName(modPath, quote, treatAsFileName) { + if (typeof quote === "undefined") { quote = true; } + if (typeof treatAsFileName === "undefined") { treatAsFileName = false; } + var modName = treatAsFileName ? switchToForwardSlashes(modPath) : trimModName(stripQuotes(modPath)); + var components = this.getPathComponents(modName); + return components.length ? (quote ? quoteStr(components[components.length - 1]) : components[components.length - 1]) : modPath; + } + TypeScript.getPrettyName = getPrettyName; + function getPathComponents(path) { + return path.split("/"); + } + TypeScript.getPathComponents = getPathComponents; + function getRelativePathToFixedPath(fixedModFilePath, absoluteModPath) { + absoluteModPath = switchToForwardSlashes(absoluteModPath); + var modComponents = this.getPathComponents(absoluteModPath); + var fixedModComponents = this.getPathComponents(fixedModFilePath); + var joinStartIndex = 0; + for(; joinStartIndex < modComponents.length && joinStartIndex < fixedModComponents.length; joinStartIndex++) { + if(fixedModComponents[joinStartIndex] != modComponents[joinStartIndex]) { + break; + } + } + if(joinStartIndex != 0) { + var relativePath = ""; + var relativePathComponents = modComponents.slice(joinStartIndex, modComponents.length); + for(; joinStartIndex < fixedModComponents.length; joinStartIndex++) { + if(fixedModComponents[joinStartIndex] != "") { + relativePath = relativePath + "../"; + } + } + return relativePath + relativePathComponents.join("/"); + } + return absoluteModPath; + } + TypeScript.getRelativePathToFixedPath = getRelativePathToFixedPath; + function quoteBaseName(modPath) { + var modName = trimModName(stripQuotes(modPath)); + var path = getRootFilePath(modName); + if(path == "") { + return modPath; + } else { + var components = modName.split(path); + var fileIndex = components.length > 1 ? 1 : 0; + return quoteStr(components[fileIndex]); + } + } + TypeScript.quoteBaseName = quoteBaseName; + function changePathToSTR(modPath) { + return trimModName(stripQuotes(modPath)) + ".str"; + } + TypeScript.changePathToSTR = changePathToSTR; + function changePathToDSTR(modPath) { + return trimModName(stripQuotes(modPath)) + ".d.str"; + } + TypeScript.changePathToDSTR = changePathToDSTR; + function changePathToTS(modPath) { + return trimModName(stripQuotes(modPath)) + ".ts"; + } + TypeScript.changePathToTS = changePathToTS; + function changePathToDTS(modPath) { + return trimModName(stripQuotes(modPath)) + ".d.ts"; + } + TypeScript.changePathToDTS = changePathToDTS; + function isRelative(path) { + return path.charAt(0) == "."; + } + TypeScript.isRelative = isRelative; + function isRooted(path) { + return path.charAt(0) == "\\" || path.charAt(0) == "/" || (path.indexOf(":\\") != -1) || (path.indexOf(":/") != -1); + } + TypeScript.isRooted = isRooted; + function getRootFilePath(outFname) { + if(outFname == "") { + return outFname; + } else { + var isPath = outFname.indexOf("/") != -1; + return isPath ? filePath(outFname) : ""; + } + } + TypeScript.getRootFilePath = getRootFilePath; + function filePathComponents(fullPath) { + fullPath = switchToForwardSlashes(fullPath); + var components = getPathComponents(fullPath); + return components.slice(0, components.length - 1); + } + TypeScript.filePathComponents = filePathComponents; + function filePath(fullPath) { + var path = filePathComponents(fullPath); + return path.join("/") + "/"; + } + TypeScript.filePath = filePath; + function normalizeURL(url) { + var hostDomainAndPortRegex = /^(https?:\/\/[\-\w\.]+(:\d+)?\/)(.*)$/i; + var matches = hostDomainAndPortRegex.exec(url); + if(matches) { + var hostDomainAndPort = matches[1]; + var actualPath = matches[3]; + return hostDomainAndPort + normalizePath(actualPath); + } + return normalizePath(url); + } + TypeScript.normalizeURL = normalizeURL; + TypeScript.pathNormalizeRegExp = /\//g; + function normalizePath(path) { + path = switchToForwardSlashes(path); + var startedWithSep = path.charAt(0) === "/"; + var parts = this.getPathComponents(path); + for(var i = 0; i < parts.length; i++) { + if(parts[i] === "." || parts[i] === "") { + parts.splice(i, 1); + i--; + } + if(i > 0 && parts[i] === ".." && parts[i - 1] !== "..") { + parts.splice(i - 1, 2); + i -= 2; + } + } + return (startedWithSep ? "/" : "") + parts.join("/"); + } + TypeScript.normalizePath = normalizePath; + function normalizeImportPath(path) { + return normalizePath(path); + } + TypeScript.normalizeImportPath = normalizeImportPath; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SourceUnit = (function () { + function SourceUnit(path, content) { + this.path = path; + this.content = content; + this.referencedFiles = null; + } + SourceUnit.prototype.getText = function (start, end) { + return this.content.substring(start, end); + }; + SourceUnit.prototype.getLength = function () { + return this.content.length; + }; + return SourceUnit; + })(); + TypeScript.SourceUnit = SourceUnit; + var CompilationEnvironment = (function () { + function CompilationEnvironment(compilationSettings, ioHost) { + this.compilationSettings = compilationSettings; + this.ioHost = ioHost; + this.residentCode = []; + this.code = []; + } + return CompilationEnvironment; + })(); + TypeScript.CompilationEnvironment = CompilationEnvironment; + var CodeResolver = (function () { + function CodeResolver(environment) { + this.environment = environment; + this.visited = { + }; + } + CodeResolver.prototype.resolveCode = function (referencePath, parentPath, performSearch, resolutionDispatcher) { + var resolvedFile = { + content: "", + path: referencePath + }; + var ioHost = this.environment.ioHost; + var isRelativePath = TypeScript.isRelative(referencePath); + var isRootedPath = isRelativePath ? false : TypeScript.isRooted(referencePath); + var normalizedPath = isRelativePath ? ioHost.resolvePath(parentPath + "/" + referencePath) : (isRootedPath || !parentPath || performSearch ? referencePath : parentPath + "/" + referencePath); + if(!TypeScript.isSTRFile(normalizedPath) && !TypeScript.isTSFile(normalizedPath)) { + normalizedPath += ".ts"; + } + normalizedPath = TypeScript.switchToForwardSlashes(TypeScript.stripQuotes(normalizedPath)); + var absoluteModuleID = this.environment.compilationSettings.useCaseSensitiveFileResolution ? normalizedPath : normalizedPath.toLocaleUpperCase(); + if(!this.visited[absoluteModuleID]) { + if(isRelativePath || isRootedPath || !performSearch) { + try { + TypeScript.CompilerDiagnostics.debugPrint(" Reading code from " + normalizedPath); + try { + resolvedFile.content = ioHost.readFile(normalizedPath); + } catch (err) { + try { + if(TypeScript.isSTRFile(normalizedPath)) { + normalizedPath = TypeScript.changePathToTS(normalizedPath); + } else { + if(TypeScript.isTSFile(normalizedPath)) { + normalizedPath = TypeScript.changePathToSTR(normalizedPath); + } + } + TypeScript.CompilerDiagnostics.debugPrint(" Reading code from " + normalizedPath); + resolvedFile.content = ioHost.readFile(normalizedPath); + } catch (err) { + normalizedPath = TypeScript.changePathToDSTR(normalizedPath); + TypeScript.CompilerDiagnostics.debugPrint(" Reading code from " + normalizedPath); + try { + resolvedFile.content = ioHost.readFile(normalizedPath); + } catch (err) { + normalizedPath = TypeScript.changePathToDTS(normalizedPath); + TypeScript.CompilerDiagnostics.debugPrint(" Reading code from " + normalizedPath); + resolvedFile.content = ioHost.readFile(normalizedPath); + } + } + } + TypeScript.CompilerDiagnostics.debugPrint(" Found code at " + normalizedPath); + resolvedFile.path = normalizedPath; + this.visited[absoluteModuleID] = true; + } catch (err) { + TypeScript.CompilerDiagnostics.debugPrint(" Did not find code for " + referencePath); + } + } else { + resolvedFile = ioHost.findFile(parentPath, normalizedPath); + if(!resolvedFile) { + if(TypeScript.isSTRFile(normalizedPath)) { + normalizedPath = TypeScript.changePathToTS(normalizedPath); + } else { + if(TypeScript.isTSFile(normalizedPath)) { + normalizedPath = TypeScript.changePathToSTR(normalizedPath); + } + } + resolvedFile = ioHost.findFile(parentPath, normalizedPath); + } + if(!resolvedFile) { + normalizedPath = TypeScript.changePathToDTS(normalizedPath); + resolvedFile = ioHost.findFile(parentPath, normalizedPath); + if(!resolvedFile) { + normalizedPath = TypeScript.changePathToDSTR(normalizedPath); + resolvedFile = ioHost.findFile(parentPath, normalizedPath); + } + } + if(resolvedFile) { + resolvedFile.path = TypeScript.switchToForwardSlashes(TypeScript.stripQuotes(resolvedFile.path)); + TypeScript.CompilerDiagnostics.debugPrint(referencePath + " resolved to: " + resolvedFile.path); + resolvedFile.content = resolvedFile.content; + this.visited[absoluteModuleID] = true; + } else { + TypeScript.CompilerDiagnostics.debugPrint("Could not find " + referencePath); + } + } + if(resolvedFile && resolvedFile.content) { + var rootDir = ioHost.dirName(resolvedFile.path); + var sourceUnit = new SourceUnit(resolvedFile.path, resolvedFile.content); + var preProcessedFileInfo = TypeScript.preProcessFile(sourceUnit, this.environment.compilationSettings); + sourceUnit.referencedFiles = preProcessedFileInfo.referencedFiles; + for(var i = 0; i < preProcessedFileInfo.referencedFiles.length; i++) { + var referencedFile = preProcessedFileInfo.referencedFiles[i]; + var normalizedPath = TypeScript.isRooted(referencedFile.path) ? referencedFile.path : rootDir + "/" + referencedFile.path; + normalizedPath = ioHost.resolvePath(normalizedPath); + if(referencePath == normalizedPath) { + resolutionDispatcher.postResolutionError(normalizedPath, "File contains reference to itself", null); + continue; + } + this.resolveCode(referencedFile.path, rootDir, false, resolutionDispatcher); + } + for(var i = 0; i < preProcessedFileInfo.importedFiles.length; i++) { + this.resolveCode(preProcessedFileInfo.importedFiles[i].path, rootDir, true, resolutionDispatcher); + } + resolutionDispatcher.postResolution(sourceUnit.path, sourceUnit); + } + } + }; + return CodeResolver; + })(); + TypeScript.CodeResolver = CodeResolver; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var StyleSettings = (function () { + function StyleSettings() { + this.bitwise = false; + this.blockInCompoundStmt = false; + this.eqeqeq = false; + this.forin = false; + this.emptyBlocks = true; + this.newMustBeUsed = false; + this.requireSemi = false; + this.assignmentInCond = false; + this.eqnull = false; + this.evalOK = true; + this.innerScopeDeclEscape = true; + this.funcInLoop = true; + this.reDeclareLocal = true; + this.literalSubscript = true; + this.implicitAny = false; + } + StyleSettings.prototype.setOption = function (opt, val) { + var optExists = this[opt]; + if(optExists !== undefined) { + this[opt] = val; + return true; + } else { + return false; + } + }; + StyleSettings.prototype.parseOptions = function (str) { + var opts = str.split(";"); + for(var i = 0, len = opts.length; i < len; i++) { + var opt = opts[i]; + var val = true; + var colonIndex = opt.lastIndexOf(":"); + if(colonIndex >= 0) { + var valStr = opt.substring(colonIndex + 1); + opt = opt.substring(0, colonIndex); + if(valStr == "off") { + val = false; + } + } + if(!this.setOption(opt, val)) { + return false; + } + } + return true; + }; + return StyleSettings; + })(); + TypeScript.StyleSettings = StyleSettings; + var CompilationSettings = (function () { + function CompilationSettings() { + this.styleSettings = new StyleSettings(); + this.propagateConstants = false; + this.minWhitespace = false; + this.parseOnly = false; + this.errorRecovery = false; + this.emitComments = false; + this.watch = false; + this.exec = false; + this.resolve = true; + this.controlFlow = false; + this.printControlFlow = false; + this.controlFlowUseDef = false; + this.errorOnWith = true; + this.preprocess = true; + this.canCallDefinitionSignature = false; + this.inferPropertiesFromThisAssignment = false; + this.useDefaultLib = true; + this.codeGenTarget = TypeScript.CodeGenTarget.ES3; + this.moduleGenTarget = TypeScript.ModuleGenTarget.Synchronous; + this.outputOption = ""; + this.mapSourceFiles = false; + this.generateDeclarationFiles = false; + this.useCaseSensitiveFileResolution = false; + } + CompilationSettings.prototype.setStyleOptions = function (str) { + this.styleSettings.parseOptions(str); + }; + return CompilationSettings; + })(); + TypeScript.CompilationSettings = CompilationSettings; + function getFileReferenceFromReferencePath(comment) { + var referencesRegEx = /^(\/\/\/\s*/igm; + var match = referencesRegEx.exec(comment); + if(match) { + var path = TypeScript.normalizePath(match[3]); + var adjustedPath = TypeScript.normalizePath(path); + var isResident = match.length >= 7 && match[6] == "true"; + if(isResident) { + TypeScript.CompilerDiagnostics.debugPrint(path + " is resident"); + } + return { + minChar: 0, + limChar: 0, + path: TypeScript.switchToForwardSlashes(adjustedPath), + isResident: isResident + }; + } else { + return null; + } + } + function getAdditionalDependencyPath(comment) { + var amdDependencyRegEx = /^(\/\/\/\s*/igm; + var match = amdDependencyRegEx.exec(comment); + if(match) { + var path = match[3]; + return path; + } else { + return null; + } + } + TypeScript.getAdditionalDependencyPath = getAdditionalDependencyPath; + function getImplicitImport(comment) { + var implicitImportRegEx = /^(\/\/\/\s*/igm; + var match = implicitImportRegEx.exec(comment); + if(match) { + return true; + } + return false; + } + TypeScript.getImplicitImport = getImplicitImport; + function getStyleSettings(comment, styleSettings) { + var styleRegEx = /^(\/\/\/\s*/igm; + var settings = styleRegEx.exec(comment); + if(settings) { + var settingsRegEx = /^([a-zA-Z]+=['"]on['|"])/igm; + settings = settingsRegEx.exec(settings[2]); + if(settings) { + for(var i = 0; i < settings.length; i++) { + var setting = (settings[i]).split("="); + var on = "\"on\""; + switch(setting[0]) { + case "blockInCompoundStmt": { + styleSettings.blockInCompoundStmt = setting[1] == on; + break; + + } + case "eqeqeq": { + styleSettings.eqeqeq = setting[1] == on; + break; + + } + case "forin": { + styleSettings.forin = setting[1] == on; + break; + + } + case "emptyBlocks": { + styleSettings.emptyBlocks = setting[1] == on; + break; + + } + case "newMustBeUsed": { + styleSettings.newMustBeUsed = setting[1] == on; + break; + + } + case "requireSemi": { + styleSettings.requireSemi = setting[1] == on; + break; + + } + case "assignmentInCond": { + styleSettings.assignmentInCond = setting[1] == on; + break; + + } + case "eqnull": { + styleSettings.eqnull = setting[1] == on; + break; + + } + case "evalOK": { + styleSettings.evalOK = setting[1] == on; + break; + + } + case "innerScopeDeclEscape": { + styleSettings.innerScopeDeclEscape = setting[1] == on; + break; + + } + case "funcInLoop": { + styleSettings.funcInLoop = setting[1] == on; + break; + + } + case "reDeclareLocal": { + styleSettings.reDeclareLocal = setting[1] == on; + break; + + } + case "literalSubscript": { + styleSettings.literalSubscript = setting[1] == on; + break; + + } + case "implicitAny": { + styleSettings.implicitAny = setting[1] == on; + break; + + } + } + } + } + } + } + TypeScript.getStyleSettings = getStyleSettings; + function getReferencedFiles(sourceText) { + var preProcessInfo = preProcessFile(sourceText, null, false); + return preProcessInfo.referencedFiles; + } + TypeScript.getReferencedFiles = getReferencedFiles; + function preProcessFile(sourceText, options, readImportFiles) { + if (typeof options === "undefined") { options = new CompilationSettings(); } + if (typeof readImportFiles === "undefined") { readImportFiles = true; } + var scanner = new TypeScript.Scanner(); + scanner.resetComments(); + scanner.setSourceText(sourceText, TypeScript.LexMode.File); + var tok = scanner.scan(); + var comments = []; + var comment = null; + var leftCurlies = []; + var settings = options; + var referencedFiles = []; + var importedFiles = []; + var isLibFile = false; + while(tok.tokenId != TypeScript.TokenID.EndOfFile) { + if(readImportFiles && tok.tokenId == TypeScript.TokenID.Import) { + tok = scanner.scan(); + if(tok.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToID(tok, false)) { + tok = scanner.scan(); + if(tok.tokenId == TypeScript.TokenID.Equals) { + tok = scanner.scan(); + if(tok.tokenId == TypeScript.TokenID.Module) { + tok = scanner.scan(); + if(tok.tokenId == TypeScript.TokenID.OpenParen) { + tok = scanner.scan(); + if(tok.tokenId == TypeScript.TokenID.StringLiteral) { + var ref = { + minChar: scanner.startPos, + limChar: scanner.pos, + path: TypeScript.stripQuotes(TypeScript.switchToForwardSlashes(tok.getText())), + isResident: false + }; + importedFiles.push(ref); + } + } + } + } + } + } + if(tok.tokenId == TypeScript.TokenID.OpenBrace) { + leftCurlies.push(tok); + } + if(tok.tokenId == TypeScript.TokenID.CloseBrace) { + leftCurlies.pop(); + } + tok = scanner.scan(); + } + comments = scanner.getComments(); + for(var iComment = 0; iComment < comments.length; iComment++) { + comment = comments[iComment]; + if(!comment.isBlock) { + var referencedCode = getFileReferenceFromReferencePath(comment.getText()); + if(referencedCode) { + referencedCode.minChar = comment.startPos; + referencedCode.limChar = referencedCode.minChar + comment.value.length; + referencedFiles.push(referencedCode); + } + if(settings) { + getStyleSettings(comment.getText(), settings.styleSettings); + var isNoLibRegex = /^(\/\/\/\s*/igm; + var isNoLibMatch = isNoLibRegex.exec(comment.getText()); + if(isNoLibMatch) { + isLibFile = (isNoLibMatch[3] == "true"); + } + } + } + } + return { + settings: settings, + referencedFiles: referencedFiles, + importedFiles: importedFiles, + isLibFile: isLibFile + }; + } + TypeScript.preProcessFile = preProcessFile; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var IncrementalParser = (function () { + function IncrementalParser(logger) { + this.logger = logger; + this.astLogger = new TypeScript.AstLogger(this.logger); + } + IncrementalParser.prototype.getEnclosingScopeContextIfSingleScopeEdit = function (previousScript, scriptId, newSourceText, editRange) { + this.logger.log("checkEditsInsideSingleScope(\"" + scriptId + "\")"); + if(editRange === null) { + throw new Error("editRange should be valid"); + } + if(editRange.isUnknown()) { + this.logger.log(" Bailing out because edit range is unknown"); + return null; + } + var scope1 = TypeScript.findEnclosingScopeAt(this.logger, previousScript, newSourceText, editRange.minChar, false); + var scope2 = TypeScript.findEnclosingScopeAt(this.logger, previousScript, newSourceText, editRange.limChar, false); + if(scope1 == null || scope2 == null) { + this.logger.log(" Bailing out because containing scopes cannot be determined"); + return null; + } + if(scope1.scopeStartAST !== scope2.scopeStartAST) { + this.logger.log(" Bailing out because edit overlaps 2 disctint scopes"); + return null; + } + var newScopeLength = scope1.scopeStartAST.limChar - scope1.scopeStartAST.minChar + editRange.delta; + if(newScopeLength <= 0) { + this.logger.log(" Bailing out because scope has been entirely removed from new source text"); + return null; + } + return scope1; + }; + IncrementalParser.prototype.attemptIncrementalUpdateUnit = function (previousScript, scriptId, newSourceText, editRange) { + this.logger.log("attemptIncrementalUpdateUnit(\"" + scriptId + "\")"); + if(editRange === null) { + throw new Error("editRange should be valid"); + } + var scope1 = this.getEnclosingScopeContextIfSingleScopeEdit(previousScript, scriptId, newSourceText, editRange); + if(scope1 === null) { + return null; + } + var newScopeLength = scope1.scopeStartAST.limChar - scope1.scopeStartAST.minChar + editRange.delta; + if(newScopeLength >= newSourceText.getLength() / 2) { + this.logger.log(" Bailing out because range of scope to reparse (" + newScopeLength + " characters) is greater than half the size of the source text"); + return null; + } + var parseErrors = []; + var errorCapture = function (minChar, charLen, message, unitIndex) { + parseErrors.push(new TypeScript.ErrorEntry(unitIndex, minChar, minChar + charLen, message)); + }; + var quickParseResult = TypeScript.quickParse(this.logger, scope1.scopeStartAST, newSourceText, scope1.scopeStartAST.minChar, scope1.scopeStartAST.minChar + newScopeLength, errorCapture); + if(quickParseResult.endLexState != TypeScript.LexState.Start) { + this.logger.log(" Bailing out because scope contains unterminated comment"); + return null; + } + var scriptFragment = quickParseResult.Script; + if(scriptFragment.vars.members.length !== 0) { + this.logger.log(" Bailing out because new source text defines variables"); + return null; + } + if(scriptFragment.bod.members.length !== 1) { + this.logger.log(" Bailing out because new source text defines more than one scope (or none)"); + return null; + } + var oldScope = scope1.scopeStartAST; + var newScope = scriptFragment.bod.members[0]; + if(oldScope.nodeType != newScope.nodeType) { + this.logger.log(" Bailing out because new source text does not define the same scope type as the existing scope"); + return null; + } + if(!(oldScope).leftCurlyCount || !(oldScope).rightCurlyCount) { + this.logger.log(" Bailing out because sopce doesn't have left/right curly count"); + return null; + } + if((oldScope).leftCurlyCount !== (newScope).leftCurlyCount) { + this.logger.log(" Bailing out because new source text contains more (or fewer) left curly braces"); + return null; + } + if((oldScope).rightCurlyCount !== (newScope).rightCurlyCount) { + this.logger.log(" Bailing out because new source text contains more (or fewer) right curly braces"); + return null; + } + if(newScope.minChar !== 0) { + this.logger.log(" Bailing out because new function declaration does not start at position 0"); + return null; + } + if(newScope.limChar !== newScopeLength) { + this.logger.log(" Bailing out because new function declaration does not end at the new end position"); + return null; + } + return TypeScript.UpdateUnitResult.singleScopeEdits(previousScript, scriptFragment, oldScope, newScope, editRange, parseErrors); + }; + IncrementalParser.prototype.mergeTrees = function (updateResult) { + var _this = this; + TypeScript.timeFunction(this.logger, "mergeTrees()", function () { + var editRange = new TypeScript.ScriptEditRange(updateResult.scope1.minChar, updateResult.scope1.limChar, updateResult.editRange.delta); + _this.applyDeltaPosition(updateResult.script1, editRange.limChar, editRange.delta); + _this.applyDeltaPosition(updateResult.script2, 0, editRange.minChar); + _this.mergeLocationInfo(updateResult.script1, updateResult.script2, editRange); + _this.replaceAST(updateResult.script1, updateResult.scope1, updateResult.scope2); + }); + }; + IncrementalParser.prototype.replaceAST = function (script, oldAst, newAst) { + var _this = this; + var pre = function (cur, parent, walker) { + if(cur === oldAst) { + newAst.preComments = cur.preComments; + newAst.postComments = cur.postComments; + _this.logger.log("replaced old AST node with new one in script AST"); + walker.options.stopWalk(); + return newAst; + } + if(TypeScript.isValidAstNode(cur)) { + if(cur.limChar < oldAst.minChar || cur.minChar > oldAst.limChar) { + walker.options.goChildren = false; + } + } + return cur; + }; + TypeScript.getAstWalkerFactory().walk(script, pre); + }; + IncrementalParser.prototype.mergeLocationInfo = function (script, partial, editRange) { + var lineMap1 = script.locationInfo.lineMap; + var lineMap2 = partial.locationInfo.lineMap; + if(this.logger.information()) { + this.logger.log("lineMap1 (before):"); + this.astLogger.logLinemap(lineMap1); + this.logger.log("lineMap2 (quick parse):"); + this.astLogger.logLinemap(lineMap2); + this.logger.log("EditRange=" + editRange); + } + var i1 = 2; + var i2 = 2; + var len1 = lineMap1.length; + var len2 = lineMap2.length; + while(i1 < len1) { + if(lineMap1[i1] <= editRange.minChar) { + i1++; + } else { + if(lineMap1[i1] >= editRange.limChar) { + lineMap1[i1] += editRange.delta; + i1++; + } else { + if(i2 < len2) { + lineMap1.splice(i1, 0, lineMap2[i2] + editRange.minChar); + i1++; + len1++; + i2++; + } else { + lineMap1.splice(i1, 1); + len1--; + } + } + } + } + if(i2 < len2) { + if(lineMap1[len1 - 1] >= (lineMap2[i2] + editRange.minChar)) { + i1 = 2; + while(i1 < len1 && i2 < len2) { + if(lineMap1[i1] < (lineMap2[i2] + editRange.minChar)) { + i1++; + } else { + lineMap1.splice(i1, 0, lineMap2[i2] + editRange.minChar); + i1++; + len1++; + i2++; + } + } + } + for(; i2 < len2; i2++) { + lineMap1.push(lineMap2[i2] + editRange.minChar); + } + } + if(this.logger.information()) { + this.logger.log("lineMap1 (after merge):"); + this.astLogger.logLinemap(lineMap1); + } + }; + IncrementalParser.prototype.applyDeltaPosition = function (ast, start, delta) { + var applyDelta = function (ast) { + if(ast.minChar !== -1 && ast.minChar >= start) { + ast.minChar += delta; + } + if(ast.limChar !== -1 && ast.limChar >= start) { + ast.limChar += delta; + } + }; + var applyDeltaToComments = function (comments) { + if(comments && comments.length > 0) { + for(var i = 0; i < comments.length; i++) { + applyDelta(comments[i]); + } + } + }; + var pre = function (cur, parent, walker) { + if(cur.limChar !== -1 && cur.limChar < start) { + walker.options.goChildren = false; + } + applyDelta(cur); + applyDeltaToComments(cur.preComments); + applyDeltaToComments(cur.postComments); + return cur; + }; + TypeScript.getAstWalkerFactory().walk(ast, pre); + }; + return IncrementalParser; + })(); + TypeScript.IncrementalParser = IncrementalParser; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var DeclFileWriter = (function () { + function DeclFileWriter(declFile) { + this.declFile = declFile; + this.onNewLine = true; + } + DeclFileWriter.prototype.Write = function (s) { + this.declFile.Write(s); + this.onNewLine = false; + }; + DeclFileWriter.prototype.WriteLine = function (s) { + this.declFile.WriteLine(s); + this.onNewLine = true; + }; + DeclFileWriter.prototype.Close = function () { + this.declFile.Close(); + }; + return DeclFileWriter; + })(); + TypeScript.DeclFileWriter = DeclFileWriter; + var DeclarationEmitter = (function () { + function DeclarationEmitter(checker, emitOptions, errorReporter) { + this.checker = checker; + this.emitOptions = emitOptions; + this.errorReporter = errorReporter; + this.declFile = null; + this.indenter = new TypeScript.Indenter(); + this.declarationContainerStack = []; + this.isDottedModuleName = []; + this.ignoreCallbackAst = null; + this.singleDeclFile = null; + this.varListCount = 0; + } + DeclarationEmitter.prototype.getAstDeclarationContainer = function () { + return this.declarationContainerStack[this.declarationContainerStack.length - 1]; + }; + DeclarationEmitter.prototype.emitDottedModuleName = function () { + return (this.isDottedModuleName.length == 0) ? false : this.isDottedModuleName[this.isDottedModuleName.length - 1]; + }; + DeclarationEmitter.prototype.setDeclarationFile = function (file) { + this.declFile = new DeclFileWriter(file); + }; + DeclarationEmitter.prototype.Close = function () { + try { + this.declFile.Close(); + } catch (ex) { + this.errorReporter.emitterError(null, ex.message); + } + }; + DeclarationEmitter.prototype.emitDeclarations = function (script) { + TypeScript.AstWalkerWithDetailCallback.walk(script, this); + }; + DeclarationEmitter.prototype.getIndentString = function (declIndent) { + if (typeof declIndent === "undefined") { declIndent = false; } + if(this.emitOptions.minWhitespace) { + return ""; + } else { + return this.indenter.getIndent(); + } + }; + DeclarationEmitter.prototype.emitIndent = function () { + this.declFile.Write(this.getIndentString()); + }; + DeclarationEmitter.prototype.canEmitSignature = function (declFlags, canEmitGlobalAmbientDecl, useDeclarationContainerTop) { + if (typeof canEmitGlobalAmbientDecl === "undefined") { canEmitGlobalAmbientDecl = true; } + if (typeof useDeclarationContainerTop === "undefined") { useDeclarationContainerTop = true; } + var container; + if(useDeclarationContainerTop) { + container = this.getAstDeclarationContainer(); + } else { + container = this.declarationContainerStack[this.declarationContainerStack.length - 2]; + } + if(container.nodeType == TypeScript.NodeType.ModuleDeclaration && !TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Exported)) { + return false; + } + if(!canEmitGlobalAmbientDecl && container.nodeType == TypeScript.NodeType.Script && TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Ambient)) { + return false; + } + return true; + }; + DeclarationEmitter.prototype.canEmitPrePostAstSignature = function (declFlags, astWithPrePostCallback, preCallback) { + if(this.ignoreCallbackAst) { + TypeScript.CompilerDiagnostics.assert(this.ignoreCallbackAst != astWithPrePostCallback, "Ignore Callback AST mismatch"); + this.ignoreCallbackAst = null; + return false; + } else { + if(preCallback && !this.canEmitSignature(declFlags, true, preCallback)) { + this.ignoreCallbackAst = astWithPrePostCallback; + return false; + } + } + return true; + }; + DeclarationEmitter.prototype.getDeclFlagsString = function (declFlags, typeString) { + var result = this.getIndentString(); + var accessorString = ""; + if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.GetAccessor)) { + accessorString = "get "; + } else { + if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.SetAccessor)) { + accessorString = "set "; + } + } + var container = this.getAstDeclarationContainer(); + if(container.nodeType == TypeScript.NodeType.ModuleDeclaration && TypeScript.hasFlag((container).modFlags, TypeScript.ModuleFlags.IsWholeFile) && TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Exported)) { + result += "export "; + } + if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.LocalStatic) || TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Static)) { + result += "static " + accessorString; + } else { + if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Private)) { + result += "private " + accessorString; + } else { + if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Public)) { + result += "public " + accessorString; + } else { + if(accessorString == "") { + result += typeString + " "; + } else { + result += accessorString; + } + } + } + } + return result; + }; + DeclarationEmitter.prototype.emitDeclFlags = function (declFlags, typeString) { + this.declFile.Write(this.getDeclFlagsString(declFlags, typeString)); + }; + DeclarationEmitter.prototype.canEmitTypeAnnotationSignature = function (declFlag) { + if (typeof declFlag === "undefined") { declFlag = TypeScript.DeclFlags.None; } + return !TypeScript.hasFlag(declFlag, TypeScript.DeclFlags.Private); + }; + DeclarationEmitter.prototype.pushDeclarationContainer = function (ast) { + this.declarationContainerStack.push(ast); + }; + DeclarationEmitter.prototype.popDeclarationContainer = function (ast) { + TypeScript.CompilerDiagnostics.assert(ast != this.getAstDeclarationContainer(), 'Declaration container mismatch'); + this.declarationContainerStack.pop(); + }; + DeclarationEmitter.prototype.emitTypeNamesMember = function (memberName, emitIndent) { + if (typeof emitIndent === "undefined") { emitIndent = false; } + if(memberName.prefix == "{ ") { + if(emitIndent) { + this.emitIndent(); + } + this.declFile.WriteLine("{"); + this.indenter.increaseIndent(); + emitIndent = true; + } else { + if(memberName.prefix != "") { + if(emitIndent) { + this.emitIndent(); + } + this.declFile.Write(memberName.prefix); + emitIndent = false; + } + } + if(memberName.isString()) { + if(emitIndent) { + this.emitIndent(); + } + this.declFile.Write((memberName).text); + } else { + var ar = memberName; + for(var index = 0; index < ar.entries.length; index++) { + this.emitTypeNamesMember(ar.entries[index], emitIndent); + if(ar.delim == "; ") { + this.declFile.WriteLine(";"); + } + } + } + if(memberName.suffix == "}") { + this.indenter.decreaseIndent(); + this.emitIndent(); + this.declFile.Write(memberName.suffix); + } else { + this.declFile.Write(memberName.suffix); + } + }; + DeclarationEmitter.prototype.emitTypeSignature = function (type) { + var containingScope = null; + var declarationContainerAst = this.getAstDeclarationContainer(); + switch(declarationContainerAst.nodeType) { + case TypeScript.NodeType.ModuleDeclaration: + case TypeScript.NodeType.InterfaceDeclaration: + case TypeScript.NodeType.FuncDecl: { + if(declarationContainerAst.type) { + containingScope = declarationContainerAst.type.containedScope; + } + break; + + } + case TypeScript.NodeType.Script: { + var script = declarationContainerAst; + if(script.bod) { + containingScope = script.bod.enclosingScope; + } + break; + + } + case TypeScript.NodeType.ClassDeclaration: { + if(declarationContainerAst.type) { + containingScope = declarationContainerAst.type.instanceType.containedScope; + } + break; + + } + default: { + TypeScript.CompilerDiagnostics.debugPrint("Unknown containing scope"); + + } + } + var typeNameMembers = type.getScopedTypeNameEx(containingScope); + this.emitTypeNamesMember(typeNameMembers); + }; + DeclarationEmitter.prototype.emitComment = function (comment) { + var text = comment.getText(); + if(this.declFile.onNewLine) { + this.emitIndent(); + } else { + if(!comment.isBlockComment) { + this.declFile.WriteLine(""); + this.emitIndent(); + } + } + this.declFile.Write(text[0]); + for(var i = 1; i < text.length; i++) { + this.declFile.WriteLine(""); + this.emitIndent(); + this.declFile.Write(text[i]); + } + if(comment.endsLine || !comment.isBlockComment) { + this.declFile.WriteLine(""); + } else { + this.declFile.Write(" "); + } + }; + DeclarationEmitter.prototype.emitDeclarationComments = function (astOrSymbol, endLine) { + if (typeof endLine === "undefined") { endLine = true; } + if(!this.emitOptions.emitComments) { + return; + } + var declComments = astOrSymbol.getDocComments(); + if(declComments.length > 0) { + for(var i = 0; i < declComments.length; i++) { + this.emitComment(declComments[i]); + } + if(endLine) { + if(!this.declFile.onNewLine) { + this.declFile.WriteLine(""); + } + } else { + if(this.declFile.onNewLine) { + this.emitIndent(); + } + } + } + }; + DeclarationEmitter.prototype.VarDeclCallback = function (pre, varDecl) { + if(pre && this.canEmitSignature(TypeScript.ToDeclFlags(varDecl.varFlags), false)) { + var interfaceMember = (this.getAstDeclarationContainer().nodeType == TypeScript.NodeType.InterfaceDeclaration); + this.emitDeclarationComments(varDecl); + if(!interfaceMember) { + if(this.varListCount >= 0) { + this.emitDeclFlags(TypeScript.ToDeclFlags(varDecl.varFlags), "var"); + this.varListCount = -this.varListCount; + } + this.declFile.Write(varDecl.id.text); + } else { + this.emitIndent(); + this.declFile.Write(varDecl.id.text); + if(TypeScript.hasFlag(varDecl.id.flags, TypeScript.ASTFlags.OptionalName)) { + this.declFile.Write("?"); + } + } + var type = null; + if(varDecl.typeExpr && varDecl.typeExpr.type) { + type = varDecl.typeExpr.type; + } else { + if(varDecl.sym) { + type = (varDecl.sym).getType(); + if(type == this.checker.anyType) { + type = null; + } + } + } + if(type && this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(varDecl.varFlags))) { + this.declFile.Write(": "); + this.emitTypeSignature(type); + } + if(this.varListCount > 0) { + this.varListCount--; + } else { + if(this.varListCount < 0) { + this.varListCount++; + } + } + if(this.varListCount < 0) { + this.declFile.Write(", "); + } else { + this.declFile.WriteLine(";"); + } + } + return false; + }; + DeclarationEmitter.prototype.BlockCallback = function (pre, block) { + if(!block.isStatementBlock) { + if(pre) { + this.varListCount = block.statements.members.length; + } else { + this.varListCount = 0; + } + return true; + } + return false; + }; + DeclarationEmitter.prototype.emitArgDecl = function (argDecl, funcDecl) { + this.emitDeclarationComments(argDecl, false); + this.declFile.Write(argDecl.id.text); + if(argDecl.isOptionalArg()) { + this.declFile.Write("?"); + } + if((argDecl.typeExpr || argDecl.type != this.checker.anyType) && this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(funcDecl.fncFlags))) { + this.declFile.Write(": "); + this.emitTypeSignature(argDecl.type); + } + }; + DeclarationEmitter.prototype.FuncDeclCallback = function (pre, funcDecl) { + if(!pre) { + return false; + } + if(funcDecl.isAccessor()) { + return this.emitPropertyAccessorSignature(funcDecl); + } + var isInterfaceMember = (this.getAstDeclarationContainer().nodeType == TypeScript.NodeType.InterfaceDeclaration); + if(funcDecl.bod) { + if(funcDecl.isConstructor) { + if(funcDecl.type.construct && funcDecl.type.construct.signatures.length > 1) { + return false; + } + } else { + if(funcDecl.type.call && funcDecl.type.call.signatures.length > 1) { + return false; + } + } + } else { + if(!isInterfaceMember && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Private) && funcDecl.type.call && funcDecl.type.call.signatures.length > 1) { + var signatures = funcDecl.type.call.signatures; + var firstSignature = signatures[0].declAST; + if(firstSignature.bod) { + firstSignature = signatures[1].declAST; + } + if(firstSignature != funcDecl) { + return false; + } + } + } + if(!this.canEmitSignature(TypeScript.ToDeclFlags(funcDecl.fncFlags), false)) { + return false; + } + this.emitDeclarationComments(funcDecl); + if(funcDecl.isConstructor) { + this.emitIndent(); + this.declFile.Write("constructor"); + } else { + var id = funcDecl.getNameText(); + if(!isInterfaceMember) { + this.emitDeclFlags(TypeScript.ToDeclFlags(funcDecl.fncFlags), "function"); + this.declFile.Write(id); + } else { + this.emitIndent(); + if(funcDecl.isConstructMember()) { + this.declFile.Write("new"); + } else { + if(!funcDecl.isCallMember() && !funcDecl.isIndexerMember()) { + this.declFile.Write(id); + if(TypeScript.hasFlag(funcDecl.name.flags, TypeScript.ASTFlags.OptionalName)) { + this.declFile.Write("? "); + } + } + } + } + } + if(!funcDecl.isIndexerMember()) { + this.declFile.Write("("); + } else { + this.declFile.Write("["); + } + this.indenter.increaseIndent(); + if(funcDecl.arguments) { + var argsLen = funcDecl.arguments.members.length; + if(funcDecl.variableArgList) { + argsLen--; + } + for(var i = 0; i < argsLen; i++) { + var argDecl = funcDecl.arguments.members[i]; + this.emitArgDecl(argDecl, funcDecl); + if(i < (argsLen - 1)) { + this.declFile.Write(", "); + } + } + } + if(funcDecl.variableArgList) { + var lastArg = funcDecl.arguments.members[funcDecl.arguments.members.length - 1]; + if(funcDecl.arguments.members.length > 1) { + this.declFile.Write(", ..."); + } else { + this.declFile.Write("..."); + } + this.emitArgDecl(lastArg, funcDecl); + } + this.indenter.decreaseIndent(); + if(!funcDecl.isIndexerMember()) { + this.declFile.Write(")"); + } else { + this.declFile.Write("]"); + } + if(!funcDecl.isConstructor && (funcDecl.returnTypeAnnotation || funcDecl.signature.returnType.type != this.checker.anyType) && this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(funcDecl.fncFlags))) { + this.declFile.Write(": "); + this.emitTypeSignature(funcDecl.signature.returnType.type); + } + this.declFile.WriteLine(";"); + return false; + }; + DeclarationEmitter.prototype.emitBaseList = function (bases, qual) { + if(bases && (bases.members.length > 0)) { + this.declFile.Write(" " + qual + " "); + var basesLen = bases.members.length; + for(var i = 0; i < basesLen; i++) { + var baseExpr = bases.members[i]; + var baseSymbol = baseExpr.type.symbol; + var baseType = baseExpr.type; + if(i > 0) { + this.declFile.Write(", "); + } + this.emitTypeSignature(baseType); + } + } + }; + DeclarationEmitter.prototype.emitPropertyAccessorSignature = function (funcDecl) { + var accessorSymbol = funcDecl.accessorSymbol; + if(accessorSymbol.getter && accessorSymbol.getter.declAST != funcDecl) { + return false; + } + this.emitDeclarationComments(accessorSymbol); + this.emitDeclFlags(TypeScript.ToDeclFlags(accessorSymbol.flags), "var"); + this.declFile.Write(funcDecl.name.text); + var propertyType = accessorSymbol.getType(); + if(this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(accessorSymbol.flags))) { + this.declFile.Write(" : "); + this.emitTypeSignature(propertyType); + } + this.declFile.WriteLine(";"); + return false; + }; + DeclarationEmitter.prototype.emitClassMembersFromConstructorDefinition = function (funcDecl) { + if(funcDecl.arguments) { + var argsLen = funcDecl.arguments.members.length; + if(funcDecl.variableArgList) { + argsLen--; + } + for(var i = 0; i < argsLen; i++) { + var argDecl = funcDecl.arguments.members[i]; + if(TypeScript.hasFlag(argDecl.varFlags, TypeScript.VarFlags.Property)) { + this.emitDeclarationComments(argDecl); + this.emitDeclFlags(TypeScript.ToDeclFlags(argDecl.varFlags), "var"); + this.declFile.Write(argDecl.id.text); + if(argDecl.typeExpr && this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(argDecl.varFlags))) { + this.declFile.Write(": "); + this.emitTypeSignature(argDecl.type); + } + this.declFile.WriteLine(";"); + } + } + } + }; + DeclarationEmitter.prototype.ClassDeclarationCallback = function (pre, classDecl) { + if(!this.canEmitPrePostAstSignature(TypeScript.ToDeclFlags(classDecl.varFlags), classDecl, pre)) { + return false; + } + if(pre) { + var className = classDecl.name.text; + this.emitDeclarationComments(classDecl); + this.emitDeclFlags(TypeScript.ToDeclFlags(classDecl.varFlags), "class"); + this.declFile.Write(className); + this.emitBaseList(classDecl.extendsList, "extends"); + this.emitBaseList(classDecl.implementsList, "implements"); + this.declFile.WriteLine(" {"); + this.pushDeclarationContainer(classDecl); + this.indenter.increaseIndent(); + if(classDecl.constructorDecl) { + this.emitClassMembersFromConstructorDefinition(classDecl.constructorDecl); + } + } else { + this.indenter.decreaseIndent(); + this.popDeclarationContainer(classDecl); + this.emitIndent(); + this.declFile.WriteLine("}"); + } + return true; + }; + DeclarationEmitter.prototype.InterfaceDeclarationCallback = function (pre, interfaceDecl) { + if(!this.canEmitPrePostAstSignature(TypeScript.ToDeclFlags(interfaceDecl.varFlags), interfaceDecl, pre)) { + return false; + } + if(pre) { + var interfaceName = interfaceDecl.name.text; + this.emitDeclarationComments(interfaceDecl); + this.emitDeclFlags(TypeScript.ToDeclFlags(interfaceDecl.varFlags), "interface"); + this.declFile.Write(interfaceName); + this.emitBaseList(interfaceDecl.extendsList, "extends"); + this.declFile.WriteLine(" {"); + this.indenter.increaseIndent(); + this.pushDeclarationContainer(interfaceDecl); + } else { + this.indenter.decreaseIndent(); + this.popDeclarationContainer(interfaceDecl); + this.emitIndent(); + this.declFile.WriteLine("}"); + } + return true; + }; + DeclarationEmitter.prototype.ImportDeclarationCallback = function (pre, importDecl) { + if(pre) { + if((this.declarationContainerStack[0]).isExternallyVisibleSymbol(importDecl.id.sym)) { + this.emitDeclarationComments(importDecl); + this.emitIndent(); + this.declFile.Write("import "); + this.declFile.Write(importDecl.id.text + " = "); + if(importDecl.isDynamicImport) { + this.declFile.WriteLine("module (" + importDecl.getAliasName() + ");"); + } else { + this.declFile.WriteLine(importDecl.getAliasName() + ";"); + } + } + } + return false; + }; + DeclarationEmitter.prototype.emitEnumSignature = function (moduleDecl) { + if(!this.canEmitSignature(TypeScript.ToDeclFlags(moduleDecl.modFlags))) { + return false; + } + this.emitDeclarationComments(moduleDecl); + this.emitDeclFlags(TypeScript.ToDeclFlags(moduleDecl.modFlags), "enum"); + this.declFile.WriteLine(moduleDecl.name.text + " {"); + this.indenter.increaseIndent(); + var membersLen = moduleDecl.members.members.length; + for(var j = 1; j < membersLen; j++) { + var memberDecl = moduleDecl.members.members[j]; + if(memberDecl.nodeType == TypeScript.NodeType.VarDecl) { + this.emitDeclarationComments(memberDecl); + this.emitIndent(); + this.declFile.WriteLine((memberDecl).id.text + ","); + } else { + TypeScript.CompilerDiagnostics.assert(memberDecl.nodeType != TypeScript.NodeType.Asg, "We want to catch this"); + } + } + this.indenter.decreaseIndent(); + this.emitIndent(); + this.declFile.WriteLine("}"); + return false; + }; + DeclarationEmitter.prototype.ModuleDeclarationCallback = function (pre, moduleDecl) { + if(TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsWholeFile)) { + if(TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsDynamic)) { + if(pre) { + if(!this.emitOptions.outputMany) { + this.singleDeclFile = this.declFile; + TypeScript.CompilerDiagnostics.assert(this.indenter.indentAmt == 0, "Indent has to be 0 when outputing new file"); + var declareFileName = this.emitOptions.mapOutputFileName(TypeScript.stripQuotes(moduleDecl.name.sym.name), TypeScript.TypeScriptCompiler.mapToDTSFileName); + var useUTF8InOutputfile = moduleDecl.containsUnicodeChar || (this.emitOptions.emitComments && moduleDecl.containsUnicodeCharInComment); + try { + this.declFile = new DeclFileWriter(this.emitOptions.ioHost.createFile(declareFileName, useUTF8InOutputfile)); + } catch (ex) { + this.errorReporter.emitterError(null, ex.message); + } + } + this.pushDeclarationContainer(moduleDecl); + } else { + if(!this.emitOptions.outputMany) { + TypeScript.CompilerDiagnostics.assert(this.singleDeclFile != this.declFile, "singleDeclFile cannot be null as we are going to revert back to it"); + TypeScript.CompilerDiagnostics.assert(this.indenter.indentAmt == 0, "Indent has to be 0 when outputing new file"); + try { + this.declFile.Close(); + } catch (ex) { + this.errorReporter.emitterError(null, ex.message); + } + this.declFile = this.singleDeclFile; + } + this.popDeclarationContainer(moduleDecl); + } + } + return true; + } + if(moduleDecl.isEnum()) { + if(pre) { + this.emitEnumSignature(moduleDecl); + } + return false; + } + if(!this.canEmitPrePostAstSignature(TypeScript.ToDeclFlags(moduleDecl.modFlags), moduleDecl, pre)) { + return false; + } + if(pre) { + if(this.emitDottedModuleName()) { + this.dottedModuleEmit += "."; + } else { + this.dottedModuleEmit = this.getDeclFlagsString(TypeScript.ToDeclFlags(moduleDecl.modFlags), "module"); + } + this.dottedModuleEmit += moduleDecl.name.text; + var isCurrentModuleDotted = (moduleDecl.members.members.length == 1 && moduleDecl.members.members[0].nodeType == TypeScript.NodeType.ModuleDeclaration && !(moduleDecl.members.members[0]).isEnum() && TypeScript.hasFlag((moduleDecl.members.members[0]).modFlags, TypeScript.ModuleFlags.Exported)); + var moduleDeclComments = moduleDecl.getDocComments(); + isCurrentModuleDotted = isCurrentModuleDotted && (moduleDeclComments == null || moduleDeclComments.length == 0); + this.isDottedModuleName.push(isCurrentModuleDotted); + this.pushDeclarationContainer(moduleDecl); + if(!isCurrentModuleDotted) { + this.emitDeclarationComments(moduleDecl); + this.declFile.Write(this.dottedModuleEmit); + this.declFile.WriteLine(" {"); + this.indenter.increaseIndent(); + } + } else { + if(!this.emitDottedModuleName()) { + this.indenter.decreaseIndent(); + this.emitIndent(); + this.declFile.WriteLine("}"); + } + this.popDeclarationContainer(moduleDecl); + this.isDottedModuleName.pop(); + } + return true; + }; + DeclarationEmitter.prototype.ScriptCallback = function (pre, script) { + if(pre) { + if(this.emitOptions.outputMany) { + for(var i = 0; i < script.referencedFiles.length; i++) { + var referencePath = script.referencedFiles[i].path; + var declareFileName; + if(TypeScript.isRooted(referencePath)) { + declareFileName = this.emitOptions.mapOutputFileName(referencePath, TypeScript.TypeScriptCompiler.mapToDTSFileName); + } else { + declareFileName = TypeScript.getDeclareFilePath(script.referencedFiles[i].path); + } + this.declFile.WriteLine('/// '); + } + } + this.pushDeclarationContainer(script); + } else { + this.popDeclarationContainer(script); + } + return true; + }; + DeclarationEmitter.prototype.DefaultCallback = function (pre, ast) { + return !TypeScript.hasFlag(ast.flags, TypeScript.ASTFlags.IsStatement); + }; + return DeclarationEmitter; + })(); + TypeScript.DeclarationEmitter = DeclarationEmitter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (UpdateUnitKind) { + UpdateUnitKind._map = []; + UpdateUnitKind._map[0] = "Unknown"; + UpdateUnitKind.Unknown = 0; + UpdateUnitKind._map[1] = "NoEdits"; + UpdateUnitKind.NoEdits = 1; + UpdateUnitKind._map[2] = "EditsInsideSingleScope"; + UpdateUnitKind.EditsInsideSingleScope = 2; + })(TypeScript.UpdateUnitKind || (TypeScript.UpdateUnitKind = {})); + var UpdateUnitKind = TypeScript.UpdateUnitKind; + var ScriptEditRange = (function () { + function ScriptEditRange(minChar, limChar, delta) { + this.minChar = minChar; + this.limChar = limChar; + this.delta = delta; + } + ScriptEditRange.unknown = function unknown() { + return new ScriptEditRange(-1, -1, -1); + } + ScriptEditRange.prototype.isUnknown = function () { + return this.minChar === -1 && this.limChar === -1 && this.delta === -1; + }; + ScriptEditRange.prototype.containsPosition = function (pos) { + return (this.minChar <= pos && pos < this.limChar) || (this.minChar <= pos && pos < this.limChar + this.delta); + }; + ScriptEditRange.prototype.toString = function () { + return "editRange(minChar=" + this.minChar + ", limChar=" + this.limChar + ", delta=" + this.delta + ")"; + }; + return ScriptEditRange; + })(); + TypeScript.ScriptEditRange = ScriptEditRange; + var UpdateUnitResult = (function () { + function UpdateUnitResult(kind, unitIndex, script1, script2) { + this.kind = kind; + this.unitIndex = unitIndex; + this.script1 = script1; + this.script2 = script2; + this.scope1 = null; + this.scope2 = null; + this.editRange = null; + this.parseErrors = []; + } + UpdateUnitResult.noEdits = function noEdits(unitIndex) { + return new UpdateUnitResult(UpdateUnitKind.NoEdits, unitIndex, null, null); + } + UpdateUnitResult.unknownEdits = function unknownEdits(script1, script2, parseErrors) { + var result = new UpdateUnitResult(UpdateUnitKind.Unknown, script1.locationInfo.unitIndex, script1, script2); + result.parseErrors = parseErrors; + return result; + } + UpdateUnitResult.singleScopeEdits = function singleScopeEdits(script1, script2, scope1, scope2, editRange, parseErrors) { + var result = new UpdateUnitResult(UpdateUnitKind.EditsInsideSingleScope, script1.locationInfo.unitIndex, script1, script2); + result.scope1 = scope1; + result.scope2 = scope2; + result.editRange = editRange; + result.parseErrors = parseErrors; + return result; + } + return UpdateUnitResult; + })(); + TypeScript.UpdateUnitResult = UpdateUnitResult; + var ErrorEntry = (function () { + function ErrorEntry(unitIndex, minChar, limChar, message) { + this.unitIndex = unitIndex; + this.minChar = minChar; + this.limChar = limChar; + this.message = message; + } + return ErrorEntry; + })(); + TypeScript.ErrorEntry = ErrorEntry; + TypeScript.defaultSettings = new TypeScript.CompilationSettings(); + var TypeScriptCompiler = (function () { + function TypeScriptCompiler(errorOutput, logger, settings) { + if (typeof logger === "undefined") { logger = new TypeScript.NullLogger(); } + if (typeof settings === "undefined") { settings = TypeScript.defaultSettings; } + this.errorOutput = errorOutput; + this.logger = logger; + this.settings = settings; + this.parser = new TypeScript.Parser(); + this.typeFlow = null; + this.scripts = new TypeScript.ASTList(); + this.units = new Array(); + this.errorReporter = new TypeScript.ErrorReporter(this.errorOutput); + this.persistentTypeState = new TypeScript.PersistentGlobalTypeState(this.errorReporter); + this.errorReporter.parser = this.parser; + this.initTypeChecker(this.errorOutput); + this.parser.style_requireSemi = this.settings.styleSettings.requireSemi; + this.parser.style_funcInLoop = this.settings.styleSettings.funcInLoop; + this.parser.inferPropertiesFromThisAssignment = this.settings.inferPropertiesFromThisAssignment; + this.emitSettings = new TypeScript.EmitOptions(this.settings); + TypeScript.codeGenTarget = settings.codeGenTarget; + } + TypeScriptCompiler.prototype.timeFunction = function (funcDescription, func) { + return TypeScript.timeFunction(this.logger, funcDescription, func); + }; + TypeScriptCompiler.prototype.initTypeChecker = function (errorOutput) { + this.persistentTypeState.refreshPersistentState(); + this.typeChecker = new TypeScript.TypeChecker(this.persistentTypeState); + this.typeChecker.errorReporter = this.errorReporter; + this.typeChecker.checkControlFlow = this.settings.controlFlow; + this.typeChecker.checkControlFlowUseDef = this.settings.controlFlowUseDef; + this.typeChecker.printControlFlowGraph = this.settings.printControlFlow; + this.typeChecker.errorsOnWith = this.settings.errorOnWith; + this.typeChecker.styleSettings = this.settings.styleSettings; + this.typeChecker.canCallDefinitionSignature = this.settings.canCallDefinitionSignature; + this.errorReporter.checker = this.typeChecker; + this.setErrorOutput(this.errorOutput); + }; + TypeScriptCompiler.prototype.setErrorOutput = function (outerr) { + this.errorOutput = outerr; + this.errorReporter.setErrOut(outerr); + this.parser.outfile = outerr; + }; + TypeScriptCompiler.prototype.emitCommentsToOutput = function () { + this.emitSettings = new TypeScript.EmitOptions(this.settings); + }; + TypeScriptCompiler.prototype.setErrorCallback = function (fn) { + this.parser.errorCallback = fn; + }; + TypeScriptCompiler.prototype.updateUnit = function (prog, filename, setRecovery) { + return this.updateSourceUnit(new TypeScript.StringSourceText(prog), filename, setRecovery); + }; + TypeScriptCompiler.prototype.updateSourceUnit = function (sourceText, filename, setRecovery) { + var _this = this; + return this.timeFunction("updateSourceUnit(" + filename + ")", function () { + var updateResult = _this.partialUpdateUnit(sourceText, filename, setRecovery); + return _this.applyUpdateResult(updateResult); + }); + }; + TypeScriptCompiler.prototype.applyUpdateResult = function (updateResult) { + switch(updateResult.kind) { + case UpdateUnitKind.NoEdits: { + return false; + + } + case UpdateUnitKind.Unknown: { + this.scripts.members[updateResult.unitIndex] = updateResult.script2; + this.units[updateResult.unitIndex] = updateResult.script2.locationInfo; + for(var i = 0, len = updateResult.parseErrors.length; i < len; i++) { + var e = updateResult.parseErrors[i]; + if(this.parser.errorCallback) { + this.parser.errorCallback(e.minChar, e.limChar - e.minChar, e.message, e.unitIndex); + } + } + return true; + + } + case UpdateUnitKind.EditsInsideSingleScope: { + new TypeScript.IncrementalParser(this.logger).mergeTrees(updateResult); + return true; + + } + } + }; + TypeScriptCompiler.prototype.partialUpdateUnit = function (sourceText, filename, setRecovery) { + var _this = this; + return this.timeFunction("partialUpdateUnit(" + filename + ")", function () { + for(var i = 0, len = _this.units.length; i < len; i++) { + if(_this.units[i].filename == filename) { + if((_this.scripts.members[i]).isResident) { + return UpdateUnitResult.noEdits(i); + } + if(setRecovery) { + _this.parser.setErrorRecovery(null); + } + var updateResult; + var parseErrors = []; + var errorCapture = function (minChar, charLen, message, unitIndex) { + parseErrors.push(new ErrorEntry(unitIndex, minChar, minChar + charLen, message)); + }; + var svErrorCallback = _this.parser.errorCallback; + if(svErrorCallback) { + _this.parser.errorCallback = errorCapture; + } + var oldScript = _this.scripts.members[i]; + var newScript = _this.parser.parse(sourceText, filename, i); + if(svErrorCallback) { + _this.parser.errorCallback = svErrorCallback; + } + updateResult = UpdateUnitResult.unknownEdits(oldScript, newScript, parseErrors); + return updateResult; + } + } + throw new Error("Unknown file \"" + filename + "\""); + }); + }; + TypeScriptCompiler.prototype.addUnit = function (prog, filename, keepResident, referencedFiles) { + if (typeof keepResident === "undefined") { keepResident = false; } + if (typeof referencedFiles === "undefined") { referencedFiles = []; } + return this.addSourceUnit(new TypeScript.StringSourceText(prog), filename, keepResident, referencedFiles); + }; + TypeScriptCompiler.prototype.addSourceUnit = function (sourceText, filename, keepResident, referencedFiles) { + if (typeof referencedFiles === "undefined") { referencedFiles = []; } + var _this = this; + return this.timeFunction("addSourceUnit(" + filename + ", " + keepResident + ")", function () { + var script = _this.parser.parse(sourceText, filename, _this.units.length, TypeScript.AllowedElements.Global); + script.referencedFiles = referencedFiles; + script.isResident = keepResident; + _this.persistentTypeState.setCollectionMode(keepResident ? TypeScript.TypeCheckCollectionMode.Resident : TypeScript.TypeCheckCollectionMode.Transient); + var index = _this.units.length; + _this.units[index] = script.locationInfo; + _this.typeChecker.collectTypes(script); + _this.scripts.append(script); + return script; + }); + }; + TypeScriptCompiler.prototype.parseUnit = function (prog, filename) { + return this.parseSourceUnit(new TypeScript.StringSourceText(prog), filename); + }; + TypeScriptCompiler.prototype.parseSourceUnit = function (sourceText, filename) { + this.parser.setErrorRecovery(this.errorOutput); + var script = this.parser.parse(sourceText, filename, 0); + var index = this.units.length; + this.units[index] = script.locationInfo; + this.typeChecker.collectTypes(script); + this.scripts.append(script); + }; + TypeScriptCompiler.prototype.typeCheck = function () { + var _this = this; + return this.timeFunction("typeCheck()", function () { + var binder = new TypeScript.Binder(_this.typeChecker); + _this.typeChecker.units = _this.units; + binder.bind(_this.typeChecker.globalScope, _this.typeChecker.globals); + binder.bind(_this.typeChecker.globalScope, _this.typeChecker.ambientGlobals); + binder.bind(_this.typeChecker.globalScope, _this.typeChecker.globalTypes); + binder.bind(_this.typeChecker.globalScope, _this.typeChecker.ambientGlobalTypes); + _this.typeFlow = new TypeScript.TypeFlow(_this.logger, _this.typeChecker.globalScope, _this.parser, _this.typeChecker); + var i = 0; + var script = null; + var len = _this.scripts.members.length; + _this.persistentTypeState.setCollectionMode(TypeScript.TypeCheckCollectionMode.Resident); + for(i = 0; i < len; i++) { + script = _this.scripts.members[i]; + if(!script.isResident || script.hasBeenTypeChecked) { + continue; + } + _this.typeFlow.assignScopes(script); + _this.typeFlow.initLibs(); + } + for(i = 0; i < len; i++) { + script = _this.scripts.members[i]; + if(!script.isResident || script.hasBeenTypeChecked) { + continue; + } + _this.typeFlow.typeCheck(script); + script.hasBeenTypeChecked = true; + } + _this.persistentTypeState.setCollectionMode(TypeScript.TypeCheckCollectionMode.Transient); + len = _this.scripts.members.length; + for(i = 0; i < len; i++) { + script = _this.scripts.members[i]; + if(script.isResident) { + continue; + } + _this.typeFlow.assignScopes(script); + _this.typeFlow.initLibs(); + } + for(i = 0; i < len; i++) { + script = _this.scripts.members[i]; + if(script.isResident) { + continue; + } + _this.typeFlow.typeCheck(script); + } + return null; + }); + }; + TypeScriptCompiler.prototype.cleanASTTypesForReTypeCheck = function (ast) { + function cleanASTType(ast, parent) { + ast.type = null; + if(ast.nodeType == TypeScript.NodeType.VarDecl) { + var vardecl = ast; + vardecl.sym = null; + } else { + if(ast.nodeType == TypeScript.NodeType.ArgDecl) { + var argdecl = ast; + argdecl.sym = null; + } else { + if(ast.nodeType == TypeScript.NodeType.Name) { + var name = ast; + name.sym = null; + } else { + if(ast.nodeType == TypeScript.NodeType.FuncDecl) { + var funcdecl = ast; + funcdecl.signature = null; + funcdecl.freeVariables = new Array(); + funcdecl.symbols = null; + funcdecl.accessorSymbol = null; + funcdecl.scopeType = null; + } else { + if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { + var modDecl = ast; + modDecl.mod = null; + } else { + if(ast.nodeType == TypeScript.NodeType.With) { + (ast).withSym = null; + } else { + if(ast.nodeType == TypeScript.NodeType.Catch) { + (ast).containedScope = null; + } + } + } + } + } + } + } + return ast; + } + TypeScript.getAstWalkerFactory().walk(ast, cleanASTType); + }; + TypeScriptCompiler.prototype.cleanTypesForReTypeCheck = function () { + var _this = this; + return this.timeFunction("cleanTypesForReTypeCheck()", function () { + for(var i = 0, len = _this.scripts.members.length; i < len; i++) { + var script = _this.scripts.members[i]; + if((script).isResident) { + continue; + } + _this.cleanASTTypesForReTypeCheck(script); + _this.typeChecker.collectTypes(script); + } + return null; + }); + }; + TypeScriptCompiler.prototype.attemptIncrementalTypeCheck = function (updateResult) { + return this.timeFunction("attemptIncrementalTypeCheck()", function () { + return false; + }); + }; + TypeScriptCompiler.prototype.reTypeCheck = function () { + var _this = this; + return this.timeFunction("reTypeCheck()", function () { + TypeScript.CompilerDiagnostics.analysisPass++; + _this.initTypeChecker(_this.errorOutput); + _this.persistentTypeState.setCollectionMode(TypeScript.TypeCheckCollectionMode.Transient); + _this.cleanTypesForReTypeCheck(); + return _this.typeCheck(); + }); + }; + TypeScriptCompiler.prototype.isDynamicModuleCompilation = function () { + for(var i = 0, len = this.scripts.members.length; i < len; i++) { + var script = this.scripts.members[i]; + if(!script.isDeclareFile && script.topLevelMod != null) { + return true; + } + } + return false; + }; + TypeScriptCompiler.prototype.updateCommonDirectoryPath = function () { + var commonComponents = []; + var commonComponentsLength = -1; + for(var i = 0, len = this.scripts.members.length; i < len; i++) { + var script = this.scripts.members[i]; + if(script.emitRequired(this.emitSettings)) { + var fileName = script.locationInfo.filename; + var fileComponents = TypeScript.filePathComponents(fileName); + if(commonComponentsLength == -1) { + commonComponents = fileComponents; + commonComponentsLength = commonComponents.length; + } else { + var updatedPath = false; + for(var j = 0; j < commonComponentsLength && j < fileComponents.length; j++) { + if(commonComponents[j] != fileComponents[j]) { + commonComponentsLength = j; + updatedPath = true; + if(j == 0) { + this.errorReporter.emitterError(null, "Cannot find the common subdirectory path for the input files"); + return; + } + break; + } + } + if(!updatedPath && fileComponents.length < commonComponentsLength) { + commonComponentsLength = fileComponents.length; + } + } + } + } + this.emitSettings.commonDirectoryPath = commonComponents.slice(0, commonComponentsLength).join("/") + "/"; + if(this.emitSettings.outputOption.charAt(this.emitSettings.outputOption.length - 1) != "/") { + this.emitSettings.outputOption += "/"; + } + }; + TypeScriptCompiler.prototype.parseEmitOption = function (ioHost) { + this.emitSettings.ioHost = ioHost; + if(this.emitSettings.outputOption == "") { + this.emitSettings.outputMany = true; + this.emitSettings.commonDirectoryPath = ""; + return; + } + this.emitSettings.outputOption = TypeScript.switchToForwardSlashes(this.emitSettings.ioHost.resolvePath(this.emitSettings.outputOption)); + if(this.emitSettings.ioHost.directoryExists(this.emitSettings.outputOption)) { + this.emitSettings.outputMany = true; + } else { + if(this.emitSettings.ioHost.fileExists(this.emitSettings.outputOption)) { + this.emitSettings.outputMany = false; + } else { + this.emitSettings.outputMany = !TypeScript.isJSFile(this.emitSettings.outputOption); + } + } + if(this.isDynamicModuleCompilation() && !this.emitSettings.outputMany) { + this.errorReporter.emitterError(null, "Cannot compile dynamic modules when emitting into single file"); + } + if(this.emitSettings.outputMany) { + this.updateCommonDirectoryPath(); + } + }; + TypeScriptCompiler.prototype.useUTF8ForFile = function (script) { + if(this.emitSettings.outputMany) { + return this.outputScriptToUTF8(script); + } else { + return this.outputScriptsToUTF8((this.scripts.members)); + } + }; + TypeScriptCompiler.mapToDTSFileName = function mapToDTSFileName(fileName, wholeFileNameReplaced) { + return TypeScript.getDeclareFilePath(fileName); + } + TypeScriptCompiler.prototype.canEmitDeclarations = function (script) { + if(!this.settings.generateDeclarationFiles) { + return false; + } + if(!!script && (script.isDeclareFile || script.isResident || script.bod == null)) { + return false; + } + return true; + }; + TypeScriptCompiler.prototype.emitDeclarationsUnit = function (script, reuseEmitter, declarationEmitter) { + if(!this.canEmitDeclarations(script)) { + return null; + } + if(!declarationEmitter) { + var declareFileName = this.emitSettings.mapOutputFileName(script.locationInfo.filename, TypeScriptCompiler.mapToDTSFileName); + var declareFile = this.createFile(declareFileName, this.useUTF8ForFile(script)); + declarationEmitter = new TypeScript.DeclarationEmitter(this.typeChecker, this.emitSettings, this.errorReporter); + declarationEmitter.setDeclarationFile(declareFile); + } + declarationEmitter.emitDeclarations(script); + if(!reuseEmitter) { + declarationEmitter.Close(); + return null; + } else { + return declarationEmitter; + } + }; + TypeScriptCompiler.prototype.emitDeclarations = function () { + if(!this.canEmitDeclarations()) { + return; + } + if(this.errorReporter.hasErrors) { + return; + } + if(this.scripts.members.length == 0) { + return; + } + var declarationEmitter = null; + for(var i = 0, len = this.scripts.members.length; i < len; i++) { + var script = this.scripts.members[i]; + if(this.emitSettings.outputMany || declarationEmitter == null) { + declarationEmitter = this.emitDeclarationsUnit(script, !this.emitSettings.outputMany); + } else { + this.emitDeclarationsUnit(script, true, declarationEmitter); + } + } + if(declarationEmitter) { + declarationEmitter.Close(); + } + }; + TypeScriptCompiler.mapToFileNameExtension = function mapToFileNameExtension(extension, fileName, wholeFileNameReplaced) { + if(wholeFileNameReplaced) { + return fileName; + } else { + var splitFname = fileName.split("."); + splitFname.pop(); + return splitFname.join(".") + extension; + } + } + TypeScriptCompiler.mapToJSFileName = function mapToJSFileName(fileName, wholeFileNameReplaced) { + return TypeScriptCompiler.mapToFileNameExtension(".js", fileName, wholeFileNameReplaced); + } + TypeScriptCompiler.prototype.emitUnit = function (script, reuseEmitter, emitter) { + if(!script.emitRequired(this.emitSettings)) { + return null; + } + var fname = script.locationInfo.filename; + if(!emitter) { + var outFname = this.emitSettings.mapOutputFileName(fname, TypeScriptCompiler.mapToJSFileName); + var outFile = this.createFile(outFname, this.useUTF8ForFile(script)); + emitter = new TypeScript.Emitter(this.typeChecker, outFname, outFile, this.emitSettings, this.errorReporter); + if(this.settings.mapSourceFiles) { + emitter.setSourceMappings(new TypeScript.SourceMapper(fname, outFname, outFile, this.createFile(outFname + TypeScript.SourceMapper.MapFileExtension, false), this.errorReporter)); + } + } else { + if(this.settings.mapSourceFiles) { + emitter.setSourceMappings(new TypeScript.SourceMapper(fname, emitter.emittingFileName, emitter.outfile, emitter.sourceMapper.sourceMapOut, this.errorReporter)); + } + } + this.typeChecker.locationInfo = script.locationInfo; + emitter.emitJavascript(script, TypeScript.TokenID.Comma, false); + if(!reuseEmitter) { + emitter.Close(); + return null; + } else { + return emitter; + } + }; + TypeScriptCompiler.prototype.emit = function (ioHost) { + this.parseEmitOption(ioHost); + var emitter = null; + for(var i = 0, len = this.scripts.members.length; i < len; i++) { + var script = this.scripts.members[i]; + if(this.emitSettings.outputMany || emitter == null) { + emitter = this.emitUnit(script, !this.emitSettings.outputMany); + } else { + this.emitUnit(script, true, emitter); + } + } + if(emitter) { + emitter.Close(); + } + }; + TypeScriptCompiler.prototype.emitToOutfile = function (outputFile) { + if(this.settings.mapSourceFiles) { + throw Error("Cannot generate source map"); + } + if(this.settings.generateDeclarationFiles) { + throw Error("Cannot generate declaration files"); + } + if(this.settings.outputOption != "") { + throw Error("Cannot parse output option"); + } + var emitter = emitter = new TypeScript.Emitter(this.typeChecker, "stdout", outputFile, this.emitSettings, this.errorReporter); + ; ; + for(var i = 0, len = this.scripts.members.length; i < len; i++) { + var script = this.scripts.members[i]; + this.typeChecker.locationInfo = script.locationInfo; + emitter.emitJavascript(script, TypeScript.TokenID.Comma, false); + } + }; + TypeScriptCompiler.prototype.emitAST = function (ioHost) { + this.parseEmitOption(ioHost); + var outFile = null; + var context = null; + for(var i = 0, len = this.scripts.members.length; i < len; i++) { + var script = this.scripts.members[i]; + if(this.emitSettings.outputMany || context == null) { + var fname = this.units[i].filename; + var mapToTxtFileName = function (fileName, wholeFileNameReplaced) { + return TypeScriptCompiler.mapToFileNameExtension(".txt", fileName, wholeFileNameReplaced); + }; + var outFname = this.emitSettings.mapOutputFileName(fname, mapToTxtFileName); + outFile = this.createFile(outFname, this.useUTF8ForFile(script)); + context = new TypeScript.PrintContext(outFile, this.parser); + } + TypeScript.getAstWalkerFactory().walk(script, TypeScript.prePrintAST, TypeScript.postPrintAST, null, context); + if(this.emitSettings.outputMany) { + try { + outFile.Close(); + } catch (e) { + this.errorReporter.emitterError(null, e.message); + } + } + } + if(!this.emitSettings.outputMany) { + try { + outFile.Close(); + } catch (e) { + this.errorReporter.emitterError(null, e.message); + } + } + }; + TypeScriptCompiler.prototype.outputScriptToUTF8 = function (script) { + return script.containsUnicodeChar || (this.emitSettings.emitComments && script.containsUnicodeCharInComment); + }; + TypeScriptCompiler.prototype.outputScriptsToUTF8 = function (scripts) { + for(var i = 0, len = scripts.length; i < len; i++) { + var script = scripts[i]; + if(this.outputScriptToUTF8(script)) { + return true; + } + } + return false; + }; + TypeScriptCompiler.prototype.createFile = function (fileName, useUTF8) { + try { + return this.emitSettings.ioHost.createFile(fileName, useUTF8); + } catch (ex) { + this.errorReporter.emitterError(null, ex.message); + } + }; + return TypeScriptCompiler; + })(); + TypeScript.TypeScriptCompiler = TypeScriptCompiler; + var ScopeEntry = (function () { + function ScopeEntry(name, type, sym) { + this.name = name; + this.type = type; + this.sym = sym; + } + return ScopeEntry; + })(); + TypeScript.ScopeEntry = ScopeEntry; + var ScopeTraversal = (function () { + function ScopeTraversal(compiler) { + this.compiler = compiler; + } + ScopeTraversal.prototype.getScope = function (enclosingScopeContext) { + if(enclosingScopeContext.enclosingObjectLit && enclosingScopeContext.isMemberCompletion) { + return enclosingScopeContext.getObjectLiteralScope(); + } else { + if(enclosingScopeContext.isMemberCompletion) { + if(enclosingScopeContext.useFullAst) { + return this.compiler.typeFlow.findMemberScopeAtFullAst(enclosingScopeContext); + } else { + return this.compiler.typeFlow.findMemberScopeAt(enclosingScopeContext); + } + } else { + return enclosingScopeContext.getScope(); + } + } + }; + ScopeTraversal.prototype.getScopeEntries = function (enclosingScopeContext) { + var scope = this.getScope(enclosingScopeContext); + if(scope == null) { + return []; + } + var inScopeNames = new TypeScript.StringHashTable(); + var allSymbolNames = scope.getAllSymbolNames(enclosingScopeContext.isMemberCompletion); + for(var i = 0; i < allSymbolNames.length; i++) { + var name = allSymbolNames[i]; + if(name == TypeScript.globalId || name == "_Core" || name == "_element") { + continue; + } + inScopeNames.add(name, ""); + } + var svModuleDecl = this.compiler.typeChecker.currentModDecl; + this.compiler.typeChecker.currentModDecl = enclosingScopeContext.deepestModuleDecl; + var result = this.getTypeNamesForNames(enclosingScopeContext, inScopeNames.getAllKeys(), scope); + this.compiler.typeChecker.currentModDecl = svModuleDecl; + return result; + }; + ScopeTraversal.prototype.getTypeNamesForNames = function (enclosingScopeContext, allNames, scope) { + var result = []; + var enclosingScope = enclosingScopeContext.getScope(); + for(var i = 0; i < allNames.length; i++) { + var name = allNames[i]; + var publicsOnly = enclosingScopeContext.publicsOnly && enclosingScopeContext.isMemberCompletion; + var symbol = scope.find(name, publicsOnly, false); + if(symbol == null) { + symbol = scope.find(name, publicsOnly, true); + } + var displayThisMember = symbol && symbol.flags & TypeScript.SymbolFlags.Private ? symbol.container == scope.container : true; + if(symbol) { + if(displayThisMember && !TypeScript.isQuoted(symbol.name) && !TypeScript.isRelative(symbol.name)) { + var typeName = symbol.getType().getScopedTypeName(enclosingScope); + result.push(new ScopeEntry(name, typeName, symbol)); + } + } else { + if(name == "true" || name == "false") { + result.push(new ScopeEntry(name, "bool", this.compiler.typeChecker.booleanType.symbol)); + } + } + } + return result; + }; + return ScopeTraversal; + })(); + TypeScript.ScopeTraversal = ScopeTraversal; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (CompilerDiagnostics) { + CompilerDiagnostics.debug = false; + CompilerDiagnostics.diagnosticWriter = null; + CompilerDiagnostics.analysisPass = 0; + function Alert(output) { + if(CompilerDiagnostics.diagnosticWriter) { + CompilerDiagnostics.diagnosticWriter.Alert(output); + } + } + CompilerDiagnostics.Alert = Alert; + function debugPrint(s) { + if(CompilerDiagnostics.debug) { + Alert(s); + } + } + CompilerDiagnostics.debugPrint = debugPrint; + function assert(condition, s) { + if(CompilerDiagnostics.debug) { + if(!condition) { + Alert(s); + } + } + } + CompilerDiagnostics.assert = assert; + })(TypeScript.CompilerDiagnostics || (TypeScript.CompilerDiagnostics = {})); + var CompilerDiagnostics = TypeScript.CompilerDiagnostics; + var NullLogger = (function () { + function NullLogger() { } + NullLogger.prototype.information = function () { + return false; + }; + NullLogger.prototype.debug = function () { + return false; + }; + NullLogger.prototype.warning = function () { + return false; + }; + NullLogger.prototype.error = function () { + return false; + }; + NullLogger.prototype.fatal = function () { + return false; + }; + NullLogger.prototype.log = function (s) { + }; + return NullLogger; + })(); + TypeScript.NullLogger = NullLogger; + var LoggerAdapter = (function () { + function LoggerAdapter(logger) { + this.logger = logger; + this._information = this.logger.information(); + this._debug = this.logger.debug(); + this._warning = this.logger.warning(); + this._error = this.logger.error(); + this._fatal = this.logger.fatal(); + } + LoggerAdapter.prototype.information = function () { + return this._information; + }; + LoggerAdapter.prototype.debug = function () { + return this._debug; + }; + LoggerAdapter.prototype.warning = function () { + return this._warning; + }; + LoggerAdapter.prototype.error = function () { + return this._error; + }; + LoggerAdapter.prototype.fatal = function () { + return this._fatal; + }; + LoggerAdapter.prototype.log = function (s) { + this.logger.log(s); + }; + return LoggerAdapter; + })(); + TypeScript.LoggerAdapter = LoggerAdapter; + var BufferedLogger = (function () { + function BufferedLogger() { + this.logContents = []; + } + BufferedLogger.prototype.information = function () { + return false; + }; + BufferedLogger.prototype.debug = function () { + return false; + }; + BufferedLogger.prototype.warning = function () { + return false; + }; + BufferedLogger.prototype.error = function () { + return false; + }; + BufferedLogger.prototype.fatal = function () { + return false; + }; + BufferedLogger.prototype.log = function (s) { + this.logContents.push(s); + }; + return BufferedLogger; + })(); + TypeScript.BufferedLogger = BufferedLogger; + function timeFunction(logger, funcDescription, func) { + var start = +new Date(); + var result = func(); + var end = +new Date(); + logger.log(funcDescription + " completed in " + (end - start) + " msec"); + return result; + } + TypeScript.timeFunction = timeFunction; + function stringToLiteral(value, length) { + var result = ""; + var addChar = function (index) { + var ch = value.charCodeAt(index); + switch(ch) { + case 9: { + result += "\\t"; + break; + + } + case 10: { + result += "\\n"; + break; + + } + case 11: { + result += "\\v"; + break; + + } + case 12: { + result += "\\f"; + break; + + } + case 13: { + result += "\\r"; + break; + + } + case 34: { + result += "\\\""; + break; + + } + case 39: { + result += "\\\'"; + break; + + } + case 92: { + result += "\\"; + break; + + } + default: { + result += value.charAt(index); + + } + } + }; + var tooLong = (value.length > length); + if(tooLong) { + var mid = length >> 1; + for(var i = 0; i < mid; i++) { + addChar(i); + } + result += "(...)"; + for(var i = value.length - mid; i < value.length; i++) { + addChar(i); + } + } else { + length = value.length; + for(var i = 0; i < length; i++) { + addChar(i); + } + } + return result; + } + TypeScript.stringToLiteral = stringToLiteral; +})(TypeScript || (TypeScript = {})); diff --git a/_infrastructure/tests/typescript_0.8.3/lib.d.ts b/_infrastructure/tests/typescript_0.8.3/lib.d.ts new file mode 100644 index 0000000000..5e51f9b06e --- /dev/null +++ b/_infrastructure/tests/typescript_0.8.3/lib.d.ts @@ -0,0 +1,8264 @@ +/* ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + +/// + +//////////////// +/// ECMAScript APIs +//////////////// + +declare var NaN: number; +declare var Infinity: number; + +/** + * Evaluates JavaScript code and executes it. + * @param x A String value that contains valid JavaScript code. + */ +declare function eval(x: string): any; + +/** + * Converts A string to an integer. + * @param s A string to convert into a number. + * @param radix A value between 2 and 36 that specifies the base of the number in numString. + * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. + * All other strings are considered decimal. + */ +declare function parseInt(s: string, radix?: number): number; + +/** + * Converts a string to a floating-point number. + * @param string A string that contains a floating-point number. + */ +declare function parseFloat(string: string): number; + +/** + * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number). + * @param number A numeric value. + */ +declare function isNaN(number: number): bool; + +/** + * Determines whether a supplied number is finite. + * @param number Any numeric value. + */ +declare function isFinite(number: number): bool; + +/** + * Gets the unencoded version of an encoded Uniform Resource Identifier (URI). + * @param encodedURI A value representing an encoded URI. + */ +declare function decodeURI(encodedURI: string): string; + +/** + * Gets the unencoded version of an encoded component of a Uniform Resource Identifier (URI). + * @param encodedURIComponent A value representing an encoded URI component. + */ +declare function decodeURIComponent(encodedURIComponent: string): string; + +/** + * Encodes a text string as a valid Uniform Resource Identifier (URI) + * @param uri A value representing an encoded URI. + */ +declare function encodeURI(uri: string): string; + +/** + * Encodes a text string as a valid component of a Uniform Resource Identifier (URI). + * @param uriComponent A value representing an encoded URI component. + */ +declare function encodeURIComponent(uriComponent: string): string; + +interface PropertyDescriptor { + configurable?: bool; + enumerable?: bool; + value?: any; + writable?: bool; + get?(): any; + set?(v: any): void; +} + +interface PropertyDescriptorMap { + [s: string]: PropertyDescriptor; +} + +interface Object { + /** Returns a string representation of an object. */ + toString(): string; + + /** Returns a date converted to a string using the current locale. */ + toLocaleString(): string; + + /** Returns the primitive value of the specified object. */ + valueOf(): Object; + + /** + * Determines whether an object has a property with the specified name. + * @param v A property name. + */ + hasOwnProperty(v: string): bool; + + /** + * Determines whether an object exists in another object's prototype chain. + * @param v Another object whose prototype chain is to be checked. + */ + isPrototypeOf(v: Object): bool; + + /** + * Determines whether a specified property is enumerable. + * @param v A property name. + */ + propertyIsEnumerable(v: string): bool; + + [s: string]: any; +} + +/** + * Provides functionality common to all JavaScript objects. + */ +declare var Object: { + new (value?: any): Object; + (): any; + (value: any): any; + + /** A reference to the prototype for a class of objects. */ + prototype: Object; + + /** + * Returns the prototype of an object. + * @param o The object that references the prototype. + */ + getPrototypeOf(o: any): any; + + /** + * Gets the own property descriptor of the specified object. + * An own property descriptor is one that is defined directly on the object and is not inherited from the object's prototype. + * @param o Object that contains the property. + * @param p Name of the property. + */ + getOwnPropertyDescriptor(o: any, p: string): PropertyDescriptor; + + /** + * Returns the names of the own properties of an object. The own properties of an object are those that are defined directly + * on that object, and are not inherited from the object's prototype. The properties of an object include both fields (objects) and functions. + * @param o Object that contains the own properties. + */ + getOwnPropertyNames(o: any): string[]; + + /** + * Creates an object that has the specified prototype, and that optionally contains specified properties. + * @param o Object to use as a prototype. May be null + * @param properties JavaScript object that contains one or more property descriptors. + */ + create(o: any, properties?: PropertyDescriptorMap): any; + + /** + * Adds a property to an object, or modifies attributes of an existing property. + * @param o Object on which to add or modify the property. This can be a native JavaScript object (that is, a user-defined object or a built in object) or a DOM object. + * @param p The property name. + * @param attributes Descriptor for the property. It can be for a data property or an accessor property. + */ + defineProperty(o: any, p: string, attributes: PropertyDescriptor): any; + + /** + * Adds one or more properties to an object, and/or modifies attributes of existing properties. + * @param o Object on which to add or modify the properties. This can be a native JavaScript object or a DOM object. + * @param properties JavaScript object that contains one or more descriptor objects. Each descriptor object describes a data property or an accessor property. + */ + defineProperties(o: any, properties: PropertyDescriptorMap): any; + + /** + * Prevents the modification of attributes of existing properties, and prevents the addition of new properties. + * @param o Object on which to lock the attributes. + */ + seal(o: any): any; + + /** + * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. + * @param o Object on which to lock the attributes. + */ + freeze(o: any): any; + + /** + * Prevents the addition of new properties to an object. + * @param o Object to make non-extensible. + */ + preventExtensions(o: any): any; + + /** + * Returns true if existing property attributes cannot be modified in an object and new properties cannot be added to the object. + * @param o Object to test. + */ + isSealed(o: any): bool; + + /** + * Returns true if existing property attributes and values cannot be modified in an object, and new properties cannot be added to the object. + * @param o Object to test. + */ + isFrozen(o: any): bool; + + /** + * Returns a value that indicates whether new properties can be added to an object. + * @param o Object to test. + */ + isExtensible(o: any): bool; + + /** + * Returns the names of the enumerable properties and methods of an object. + * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. + */ + keys(o: any): string[]; +} + +/** + * Creates a new function. + */ +interface Function { + /** + * Calls the function, substituting the specified object for the this value of the function, and the specified array for the arguments of the function. + * @param thisArg The object to be used as the this object. + * @param argArray A set of arguments to be passed to the function. + */ + apply(thisArg: any, argArray?: any): any; + + /** + * Calls a method of an object, substituting another object for the current object. + * @param thisArg The object to be used as the current object. + * @param argArray A list of arguments to be passed to the method. + */ + call(thisArg: any, ...argArray: any[]): any; + + /** + * For a given function, creates a bound function that has the same body as the original function. + * The this object of the bound function is associated with the specified object, and has the specified initial parameters. + * @param thisArg An object to which the this keyword can refer inside the new function. + * @param argArray A list of arguments to be passed to the new function. + */ + bind(thisArg: any, ...argArray: any[]): any; + + prototype: any; + length: number; + + // Non-standard extensions + arguments: any; + caller: Function; +} + +declare var Function: { + /** + * Creates a new function. + * @param args A list of arguments the function accepts. + */ + new (...args: string[]): Function; + (...args: string[]): Function; + prototype: Function; +} + +interface IArguments { + [index: number]: any; + length: number; + callee: Function; +} + +interface String { + /** Returns a string representation of a string. */ + toString(): string; + + /** + * Returns the character at the specified index. + * @param pos The zero-based index of the desired character. + */ + charAt(pos: number): string; + + /** + * Returns the Unicode value of the character at the specified location. + * @param index The zero-based index of the desired character. If there is no character at the specified index, NaN is returned. + */ + charCodeAt(index: number): number; + + /** + * Returns a string that contains the concatenation of two or more strings. + * @param strings The strings to append to the end of the string. + */ + concat(...strings: string[]): string; + + /** + * Returns the position of the first occurrence of a substring. + * @param searchString The substring to search for in the string + * @param position The index at which to begin searching the String object. If omitted, search starts at the beginning of the string. + */ + indexOf(searchString: string, position?: number): number; + + /** + * Returns the last occurrence of a substring in the string. + * @param searchString The substring to search for. + * @param position The index at which to begin searching. If omitted, the search begins at the end of the string. + */ + lastIndexOf(searchString: string, position?: number): number; + + /** + * Determines whether two strings are equivalent in the current locale. + * @param that String to compare to target string + */ + localeCompare(that: string): number; + + /** + * Matches a string with a regular expression, and returns an array containing the results of that search. + * @param regexp A variable name or string literal containing the regular expression pattern and flags. + */ + match(regexp: string): string[]; + /** + * Matches a string with a regular expression, and returns an array containing the results of that search. + * @param regexp A regular expression object that contains the regular expression pattern and applicable flags. + */ + match(regexp: RegExp): string[]; + + /** + * Replaces text in a string, using a regular expression or search string. + * @param searchValue A String object or string literal that represents the regular expression + * @param replaceValue A String object or string literal containing the text to replace for every successful match of rgExp in stringObj. + */ + replace(searchValue: string, replaceValue: string): string; + /** + * Replaces text in a string, using a regular expression or search string. + * @param searchValue A String object or string literal that represents the regular expression + * @param replaceValue A function that returns the replacement text. + */ + replace(searchValue: string, replaceValue: (substring: string, ...args: any[]) => string): string; + /** + * Replaces text in a string, using a regular expression or search string. + * @param searchValue A Regular Expression object containing the regular expression pattern and applicable flags + * @param replaceValue A String object or string literal containing the text to replace for every successful match of rgExp in stringObj. + */ + replace(searchValue: RegExp, replaceValue: string): string; + /** + * Replaces text in a string, using a regular expression or search string. + * @param searchValue A Regular Expression object containing the regular expression pattern and applicable flags + * @param replaceValue A function that returns the replacement text. + */ + replace(searchValue: RegExp, replaceValue: (substring: string, ...args: any[]) => string): string; + + /** + * Finds the first substring match in a regular expression search. + * @param regexp The regular expression pattern and applicable flags. + */ + search(regexp: string): number; + /** + * Finds the first substring match in a regular expression search. + * @param regexp The regular expression pattern and applicable flags. + */ + search(regexp: RegExp): number; + + /** + * Returns a section of a string. + * @param start The index to the beginning of the specified portion of stringObj. + * @param end The index to the end of the specified portion of stringObj. The substring includes the characters up to, but not including, the character indicated by end. + * If this value is not specified, the substring continues to the end of stringObj. + */ + slice(start: number, end?: number): string; + + /** + * Split a string into substrings using the specified separator and return them as an array. + * @param separator A string that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned. + * @param limit A value used to limit the number of elements returned in the array. + */ + split(separator: string, limit?: number): string[]; + /** + * Split a string into substrings using the specified separator and return them as an array. + * @param separator A Regular Express that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned. + * @param limit A value used to limit the number of elements returned in the array. + */ + split(separator: RegExp, limit?: number): string[]; + + /** + * Returns the substring at the specified location within a String object. + * @param start The zero-based index integer indicating the beginning of the substring. + * @param end Zero-based index integer indicating the end of the substring. The substring includes the characters up to, but not including, the character indicated by end. + * If end is omitted, the characters from start through the end of the original string are returned. + */ + substring(start: number, end?: number): string; + + /** Converts all the alphabetic characters in a string to lowercase. */ + toLowerCase(): string; + + /** Converts all alphabetic characters to lowercase, taking into account the host environment's current locale. */ + toLocaleLowerCase(): string; + + /** Converts all the alphabetic characters in a string to uppercase. */ + toUpperCase(): string; + + /** Returns a string where all alphabetic characters have been converted to uppercase, taking into account the host environment's current locale. */ + toLocaleUpperCase(): string; + + /** Removes the leading and trailing white space and line terminator characters from a string. */ + trim(): string; + + /** Returns the length of a String object. */ + length: number; + + // IE extensions + /** + * Gets a substring beginning at the specified location and having the specified length. + * @param from The starting position of the desired substring. The index of the first character in the string is zero. + * @param length The number of characters to include in the returned substring. + */ + substr(from: number, length?: number): string; +} + +/** + * Allows manipulation and formatting of text strings and determination and location of substrings within strings. + */ +declare var String: { + new (value?: any): String; + (value?: any): string; + prototype: String; + fromCharCode(...codes: number[]): string; +} + +interface Boolean { +} +declare var Boolean: { + new (value?: any): Boolean; + (value?: any): bool; + prototype: Boolean; +} + +interface Number { + toString(radix?: number): string; + toFixed(fractionDigits?: number): string; + toExponential(fractionDigits?: number): string; + toPrecision(precision: number): string; +} +/** An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers. */ +declare var Number: { + new (value?: any): Number; + (value?: any): number; + prototype: Number; + /** The largest number that can be represented in JavaScript. Equal to approximately 1.79E+308. */ + MAX_VALUE: number; + /** The closest number to zero that can be represented in JavaScript. Equal to approximately 5.00E-324. */ + MIN_VALUE: number; + /** + * A value that is not a number. + * In equality comparisons, NaN does not equal any value, including itself. To test whether a value is equivalent to NaN, use the isNaN function. + */ + NaN: number; + /** + * A value that is less than the largest negative number that can be represented in JavaScript. + * JavaScript displays NEGATIVE_INFINITY values as -infinity. + */ + NEGATIVE_INFINITY: number; + /** + * A value greater than the largest number that can be represented in JavaScript. + * JavaScript displays POSITIVE_INFINITY values as infinity. + */ + POSITIVE_INFINITY: number; +} + +interface Math { + /** The mathematical constant e. This is Euler's number, the base of natural logarithms. */ + E: number; + /** The natural logarithm of 10. */ + LN10: number; + /** The natural logarithm of 2. */ + LN2: number; + /** The base-2 logarithm of e. */ + LOG2E: number; + /** The base-10 logarithm of e. */ + LOG10E: number; + /** Pi. This is the ratio of the circumference of a circle to its diameter. */ + PI: number; + /** The square root of 0.5, or, equivalently, one divided by the square root of 2. */ + SQRT1_2: number; + /** The square root of 2. */ + SQRT2: number; + /** + * Returns the absolute value of a number (the value without regard to whether it is positive or negative). + * For example, the absolute value of -5 is the same as the absolute value of 5. + * @param x A numeric expression for which the absolute value is needed. + */ + abs(x: number): number; + /** + * Returns the arc cosine (or inverse cosine) of a number. + * @param x A numeric expression. + */ + acos(x: number): number; + /** + * Returns the arcsine of a number. + * @param x A numeric expression. + */ + asin(x: number): number; + /** + * Returns the arctangent of a number. + * @param x A numeric expression for which the arctangent is needed. + */ + atan(x: number): number; + /** + * Returns the angle (in radians) from the X axis to a point (y,x). + * @param y A numeric expression representing the cartesian y-coordinate. + * @param x A numeric expression representing the cartesian x-coordinate. + */ + atan2(y: number, x: number): number; + /** + * Returns the smallest integer greater than or equal to its numeric argument. + * @param x A numeric expression. + */ + ceil(x: number): number; + /** + * Returns the cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + cos(x: number): number; + /** + * Returns e (the base of natural logarithms) raised to a power. + * @param x A numeric expression representing the power of e. + */ + exp(x: number): number; + /** + * Returns the greatest integer less than or equal to its numeric argument. + * @param x A numeric expression. + */ + floor(x: number): number; + /** + * Returns the natural logarithm (base e) of a number. + * @param x A numeric expression. + */ + log(x: number): number; + /** + * Returns the larger of a set of supplied numeric expressions. + * @param values Numeric expressions to be evaluated. + */ + max(...values: number[]): number; + /** + * Returns the smaller of a set of supplied numeric expressions. + * @param values Numeric expressions to be evaluated. + */ + min(...values: number[]): number; + /** + * Returns the value of a base expression taken to a specified power. + * @param x The base value of the expression. + * @param y The exponent value of the expression. + */ + pow(x: number, y: number): number; + /** Returns a pseudorandom number between 0 and 1. */ + random(): number; + /** + * Returns a supplied numeric expression rounded to the nearest integer. + * @param x The value to be rounded to the nearest integer. + */ + round(x: number): number; + /** + * Returns the sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + sin(x: number): number; + /** + * Returns the square root of a number. + * @param x A numeric expression. + */ + sqrt(x: number): number; + /** + * Returns the tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + tan(x: number): number; +} +/** An intrinsic object that provides basic mathematics functionality and constants. */ +declare var Math: Math; + +/** Enables basic storage and retrieval of dates and times. */ +interface Date { + /** Returns a string representation of a date. The format of the string depends on the locale. */ + toString(): string; + /** Returns a date as a string value. */ + toDateString(): string; + /** Returns a time as a string value. */ + toTimeString(): string; + toLocaleString(): string; + /** Returns a date as a string value appropriate to the host environment's current locale. */ + toLocaleDateString(): string; + /** Returns a time as a string value appropriate to the host environment's current locale. */ + toLocaleTimeString(): string; + /** Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC. */ + valueOf(): number; + /** Gets the time value in milliseconds. */ + getTime(): number; + /** Gets the year, using local time. */ + getFullYear(): number; + /** Gets the year using Universal Coordinated Time (UTC). */ + getUTCFullYear(): number; + /** Gets the month, using local time. */ + getMonth(): number; + /** Gets the month of a Date object using Universal Coordinated Time (UTC). */ + getUTCMonth(): number; + /** Gets the day-of-the-month, using local time. */ + getDate(): number; + /** Gets the day-of-the-month, using Universal Coordinated Time (UTC). */ + getUTCDate(): number; + /** Gets the day of the week, using local time. */ + getDay(): number; + /** Gets the day of the week using Universal Coordinated Time (UTC). */ + getUTCDay(): number; + /** Gets the hours in a date, using local time. */ + getHours(): number; + /** Gets the hours value in a Date object using Universal Coordinated Time (UTC). */ + getUTCHours(): number; + /** Gets the minutes of a Date object, using local time. */ + getMinutes(): number; + /** Gets the minutes of a Date object using Universal Coordinated Time (UTC). */ + getUTCMinutes(): number; + /** Gets the seconds of a Date object, using local time. */ + getSeconds(): number; + /** Gets the seconds of a Date object using Universal Coordinated Time (UTC). */ + getUTCSeconds(): number; + /** Gets the milliseconds of a Date, using local time. */ + getMilliseconds(): number; + /** Gets the milliseconds of a Date object using Universal Coordinated Time (UTC). */ + getUTCMilliseconds(): number; + /** Gets the difference in minutes between the time on the local computer and Universal Coordinated Time (UTC). */ + getTimezoneOffset(): number; + /** + * Sets the date and time value in the Date object. + * @param time A numeric value representing the number of elapsed milliseconds since midnight, January 1, 1970 GMT. + */ + setTime(time: number): void; + /** + * Sets the milliseconds value in the Date object using local time. + * @param ms A numeric value equal to the millisecond value. + */ + setMilliseconds(ms: number): void; + /** + * Sets the milliseconds value in the Date object using Universal Coordinated Time (UTC). + * @param ms A numeric value equal to the millisecond value. + */ + setUTCMilliseconds(ms: number): void; + + /** + * Sets the seconds value in the Date object using local time. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setSeconds(sec: number, ms?: number): void; + /** + * Sets the seconds value in the Date object using Universal Coordinated Time (UTC). + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setUTCSeconds(sec: number, ms?: number): void; + /** + * Sets the minutes value in the Date object using local time. + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setMinutes(min: number, sec?: number, ms?: number): void; + /** + * Sets the minutes value in the Date object using Universal Coordinated Time (UTC). + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setUTCMinutes(min: number, sec?: number, ms?: number): void; + /** + * Sets the hour value in the Date object using local time. + * @param hours A numeric value equal to the hours value. + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setHours(hours: number, min?: number, sec?: number, ms?: number): void; + /** + * Sets the hours value in the Date object using Universal Coordinated Time (UTC). + * @param hours A numeric value equal to the hours value. + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setUTCHours(hours: number, min?: number, sec?: number, ms?: number): void; + /** + * Sets the numeric day-of-the-month value of the Date object using local time. + * @param date A numeric value equal to the day of the month. + */ + setDate(date: number): void; + /** + * Sets the numeric day of the month in the Date object using Universal Coordinated Time (UTC). + * @param date A numeric value equal to the day of the month. + */ + setUTCDate(date: number): void; + /** + * Sets the month value in the Date object using local time. + * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. + * @param date A numeric value representing the day of the month. If this value is not supplied, the value from a call to the getDate method is used. + */ + setMonth(month: number, date?: number): void; + /** + * Sets the month value in the Date object using Universal Coordinated Time (UTC). + * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. + * @param date A numeric value representing the day of the month. If it is not supplied, the value from a call to the getUTCDate method is used. + */ + setUTCMonth(month: number, date?: number): void; + /** + * Sets the year of the Date object using local time. + * @param year A numeric value for the year. + * @param month A zero-based numeric value for the month (0 for January, 11 for December). Must be specified if numDate is specified. + * @param date A numeric value equal for the day of the month. + */ + setFullYear(year: number, month?: number, date?: number): void; + /** + * Sets the year value in the Date object using Universal Coordinated Time (UTC). + * @param year A numeric value equal to the year. + * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. Must be supplied if numDate is supplied. + * @param date A numeric value equal to the day of the month. + */ + setUTCFullYear(year: number, month?: number, date?: number): void; + /** Returns a date converted to a string using Universal Coordinated Time (UTC). */ + toUTCString(): string; + /** Returns a date as a string value in ISO format. */ + toISOString(): string; + /** Used by the JSON.stringify method to enable the transformation of an object's data for JavaScript Object Notation (JSON) serialization. */ + toJSON(key?: any): string; +} +/** + * Enables basic storage and retrieval of dates and times. + */ +declare var Date: { + new (): Date; + new (value: number): Date; + new (value: string): Date; + new (year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date; + (): string; + prototype: Date; + /** + * Parses a string containing a date, and returns the number of milliseconds between that date and midnight, January 1, 1970. + * @param s A date string + */ + parse(s: string): number; + /** + * Returns the number of milliseconds between midnight, January 1, 1970 Universal Coordinated Time (UTC) (or GMT) and the specified date. + * @param year The full year designation is required for cross-century date accuracy. If year is between 0 and 99 is used, then year is assumed to be 1900 + year. + * @param month The month as an integer between 0 and 11 (January to December). + * @param date The date as an integer between 1 and 31. + * @param hours Must be supplied if minutes is supplied. An integer from 0 to 23 (midnight to 11pm) that specifies the hour. + * @param minutes Must be supplied if seconds is supplied. An integer from 0 to 59 that specifies the minutes. + * @param seconds Must be supplied if milliseconds is supplied. An integer from 0 to 59 that specifies the seconds. + * @param ms An integer from 0 to 999 that specifies the milliseconds. + */ + UTC(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): number; + now(): number; +} + +interface RegExpExecArray { + [index: number]: string; + length: number; + + index: number; + input: string; + + toString(): string; + toLocaleString(): string; + concat(...items: string[][]): string[]; + join(seperator?: string): string; + pop(): string; + push(...items: string[]): number; + reverse(): string[]; + shift(): string; + slice(start: number, end?: number): string[]; + sort(compareFn?: (a: string, b: string) => number): string[]; + splice(start: number): string[]; + splice(start: number, deleteCount: number, ...items: string[]): string[]; + unshift(...items: string[]): number; + + indexOf(searchElement: string, fromIndex?: number): number; + lastIndexOf(searchElement: string, fromIndex?: number): number; + every(callbackfn: (value: string, index: number, array: string[]) => bool, thisArg?: any): bool; + some(callbackfn: (value: string, index: number, array: string[]) => bool, thisArg?: any): bool; + forEach(callbackfn: (value: string, index: number, array: string[]) => void , thisArg?: any): void; + map(callbackfn: (value: string, index: number, array: string[]) => any, thisArg?: any): any[]; + filter(callbackfn: (value: string, index: number, array: string[]) => bool, thisArg?: any): string[]; + reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: string[]) => any, initialValue?: any): any; + reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: string[]) => any, initialValue?: any): any; +} + + +interface RegExp { + /** + * Executes a search on a string using a regular expression pattern, and returns an array containing the results of that search. + * @param string The String object or string literal on which to perform the search. + */ + exec(string: string): RegExpExecArray; + /** + * Returns a Boolean value that indicates whether or not a pattern exists in a searched string. + * @param string String on which to perform the search. + */ + test(string: string): bool; + /** Returns a copy of the text of the regular expression pattern. Read-only. The rgExp argument is a Regular expression object. It can be a variable name or a literal. */ + source: string; + /** Returns a Boolean value indicating the state of the global flag (g) used with a regular expression. Default is false. Read-only. */ + global: bool; + /** Returns a Boolean value indicating the state of the ignoreCase flag (i) used with a regular expression. Default is false. Read-only. */ + ignoreCase: bool; + /** Returns a Boolean value indicating the state of the multiline flag (m) used with a regular expression. Default is false. Read-only. */ + multiline: bool; + + lastIndex: number; + + // Non-standard extensions + compile(): RegExp; +} +declare var RegExp: { + new (pattern: string, flags?: string): RegExp; + (pattern: string, flags?: string): RegExp; + + // Non-standard extensions + $1: string; + $2: string; + $3: string; + $4: string; + $5: string; + $6: string; + $7: string; + $8: string; + $9: string; + lastMatch: string; +} + +interface Error { + name: string; + message: string; +} +declare var Error: { + new (message?: string): Error; + (message?: string): Error; + prototype: Error; +} + +interface EvalError extends Error { +} +declare var EvalError: { + new (message?: string): EvalError; + (message?: string): EvalError; + prototype: EvalError; +} + +interface RangeError extends Error { +} +declare var RangeError: { + new (message?: string): RangeError; + (message?: string): RangeError; + prototype: RangeError; +} + +interface ReferenceError extends Error { +} +declare var ReferenceError: { + new (message?: string): ReferenceError; + (message?: string): ReferenceError; + prototype: ReferenceError; +} + +interface SyntaxError extends Error { +} +declare var SyntaxError: { + new (message?: string): SyntaxError; + (message?: string): SyntaxError; + prototype: SyntaxError; +} + +interface TypeError extends Error { +} +declare var TypeError: { + new (message?: string): TypeError; + (message?: string): TypeError; + prototype: TypeError; +} + +interface URIError extends Error { +} +declare var URIError: { + new (message?: string): URIError; + (message?: string): URIError; + prototype: URIError; +} + +interface JSON { + /** + * Converts a JavaScript Object Notation (JSON) string into an object. + * @param text A valid JSON string. + * @param reviver A function that transforms the results. This function is called for each member of the object. + * If a member contains nested objects, the nested objects are transformed before the parent object is. + */ + parse(text: string, reviver?: (key: any, value: any) => any): any; + /** + * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. + * @param value A JavaScript value, usually an object or array, to be converted. + */ + stringify(value: any): string; + /** + * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. + * @param value A JavaScript value, usually an object or array, to be converted. + * @param replacer A function that transforms the results. + */ + stringify(value: any, replacer: (key: string, value: any) => any): string; + /** + * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. + * @param value A JavaScript value, usually an object or array, to be converted. + * @param replacer Array that transforms the results. + */ + stringify(value: any, replacer: any[]): string; + /** + * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. + * @param value A JavaScript value, usually an object or array, to be converted. + * @param replacer A function that transforms the results. + * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. + */ + stringify(value: any, replacer: (key: string, value: any) => any, space: any): string; + /** + * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. + * @param value A JavaScript value, usually an object or array, to be converted. + * @param replacer Array that transforms the results. + * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. + */ + stringify(value: any, replacer: any[], space: any): string; +} +/** + * An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format. + */ +declare var JSON: JSON; + +//////////////// +/// ECMAScript Array API (specially handled by compiler) +//////////////// + +interface Array { + toString(): string; + toLocaleString(): string; + concat(...items: _element[][]): _element[]; + concat(...items: _element[]): _element[]; + join(seperator?: string): string; + pop(): _element; + push(...items: _element[]): number; + reverse(): _element[]; + shift(): _element; + slice(start: number, end?: number): _element[]; + sort(compareFn?: (a: _element, b: _element) => number): _element[]; + splice(start: number): _element[]; + splice(start: number, deleteCount: number, ...items: _element[]): _element[]; + unshift(...items: _element[]): number; + + indexOf(searchElement: _element, fromIndex?: number): number; + lastIndexOf(searchElement: _element, fromIndex?: number): number; + every(callbackfn: (value: _element, index: number, array: _element[]) => bool, thisArg?: any): bool; + some(callbackfn: (value: _element, index: number, array: _element[]) => bool, thisArg?: any): bool; + forEach(callbackfn: (value: _element, index: number, array: _element[]) => void , thisArg?: any): void; + map(callbackfn: (value: _element, index: number, array: _element[]) => any, thisArg?: any): any[]; + filter(callbackfn: (value: _element, index: number, array: _element[]) => bool, thisArg?: any): _element[]; + reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: _element[]) => any, initialValue?: any): any; + reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: _element[]) => any, initialValue?: any): any; + + length: number; +} +declare var Array: { + new (...items: any[]): any[]; + (...items: any[]): any[]; + isArray(arg: any): bool; + prototype: Array; +} + +//////////////// +/// IE10 ECMAScript Extensions +//////////////// + +interface ArrayBuffer { + byteLength: number; +} +declare var ArrayBuffer: { + prototype: ArrayBuffer; + new (byteLength: number); +} + +interface ArrayBufferView { + buffer: ArrayBuffer; + byteOffset: number; + byteLength: number; +} + +interface Int8Array extends ArrayBufferView { + BYTES_PER_ELEMENT: number; + length: number; + [index: number]: number; + get(index: number): number; + set(index: number, value: number): void; + set(array: Int8Array, offset?: number): void; + set(array: number[], offset?: number): void; + subarray(begin: number, end?: number): Int8Array; +} +declare var Int8Array: { + prototype: Int8Array; + new (length: number): Int8Array; + new (array: Int8Array): Int8Array; + new (array: number[]): Int8Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int8Array; + BYTES_PER_ELEMENT: number; +} + +interface Uint8Array extends ArrayBufferView { + BYTES_PER_ELEMENT: number; + length: number; + [index: number]: number; + get(index: number): number; + set(index: number, value: number): void; + set(array: Uint8Array, offset?: number): void; + set(array: number[], offset?: number): void; + subarray(begin: number, end?: number): Uint8Array; +} +declare var Uint8Array: { + prototype: Uint8Array; + new (length: number): Uint8Array; + new (array: Uint8Array): Uint8Array; + new (array: number[]): Uint8Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint8Array; + BYTES_PER_ELEMENT: number; +} + +interface Int16Array extends ArrayBufferView { + BYTES_PER_ELEMENT: number; + length: number; + [index: number]: number; + get(index: number): number; + set(index: number, value: number): void; + set(array: Int16Array, offset?: number): void; + set(array: number[], offset?: number): void; + subarray(begin: number, end?: number): Int16Array; +} +declare var Int16Array: { + prototype: Int16Array; + new (length: number): Int16Array; + new (array: Int16Array): Int16Array; + new (array: number[]): Int16Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int16Array; + BYTES_PER_ELEMENT: number; +} + +interface Uint16Array extends ArrayBufferView { + BYTES_PER_ELEMENT: number; + length: number; + [index: number]: number; + get(index: number): number; + set(index: number, value: number): void; + set(array: Uint16Array, offset?: number): void; + set(array: number[], offset?: number): void; + subarray(begin: number, end?: number): Uint16Array; +} +declare var Uint16Array: { + prototype: Uint16Array; + new (length: number): Uint16Array; + new (array: Uint16Array): Uint16Array; + new (array: number[]): Uint16Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint16Array; + BYTES_PER_ELEMENT: number; +} + +interface Int32Array extends ArrayBufferView { + BYTES_PER_ELEMENT: number; + length: number; + [index: number]: number; + get(index: number): number; + set(index: number, value: number): void; + set(array: Int32Array, offset?: number): void; + set(array: number[], offset?: number): void; + subarray(begin: number, end?: number): Int32Array; +} +declare var Int32Array: { + prototype: Int32Array; + new (length: number): Int32Array; + new (array: Int32Array): Int32Array; + new (array: number[]): Int32Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Int32Array; + BYTES_PER_ELEMENT: number; +} + +interface Uint32Array extends ArrayBufferView { + BYTES_PER_ELEMENT: number; + length: number; + [index: number]: number; + get(index: number): number; + set(index: number, value: number): void; + set(array: Uint32Array, offset?: number): void; + set(array: number[], offset?: number): void; + subarray(begin: number, end?: number): Uint32Array; +} +declare var Uint32Array: { + prototype: Uint32Array; + new (length: number): Uint32Array; + new (array: Uint32Array): Uint32Array; + new (array: number[]): Uint32Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Uint32Array; + BYTES_PER_ELEMENT: number; +} + +interface Float32Array extends ArrayBufferView { + BYTES_PER_ELEMENT: number; + length: number; + [index: number]: number; + get(index: number): number; + set(index: number, value: number): void; + set(array: Float32Array, offset?: number): void; + set(array: number[], offset?: number): void; + subarray(begin: number, end?: number): Float32Array; +} +declare var Float32Array: { + prototype: Float32Array; + new (length: number): Float32Array; + new (array: Float32Array): Float32Array; + new (array: number[]): Float32Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float32Array; + BYTES_PER_ELEMENT: number; +} + +interface Float64Array extends ArrayBufferView { + BYTES_PER_ELEMENT: number; + length: number; + [index: number]: number; + get(index: number): number; + set(index: number, value: number): void; + set(array: Float64Array, offset?: number): void; + set(array: number[], offset?: number): void; + subarray(begin: number, end?: number): Float64Array; +} +declare var Float64Array: { + prototype: Float64Array; + new (length: number): Float64Array; + new (array: Float64Array): Float64Array; + new (array: number[]): Float64Array; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): Float64Array; + BYTES_PER_ELEMENT: number; +} + +interface DataView extends ArrayBufferView { + getInt8(byteOffset: number): number; + getUint8(byteOffset: number): number; + getInt16(byteOffset: number, littleEndian?: bool): number; + getUint16(byteOffset: number, littleEndian?: bool): number; + getInt32(byteOffset: number, littleEndian?: bool): number; + getUint32(byteOffset: number, littleEndian?: bool): number; + getFloat32(byteOffset: number, littleEndian?: bool): number; + getFloat64(byteOffset: number, littleEndian?: bool): number; + + setInt8(byteOffset: number, value: number): void; + setUint8(byteOffset: number, value: number): void; + setInt16(byteOffset: number, value: number, littleEndian?: bool): void; + setUint16(byteOffset: number, value: number, littleEndian?: bool): void; + setInt32(byteOffset: number, value: number, littleEndian?: bool): void; + setUint32(byteOffset: number, value: number, littleEndian?: bool): void; + setFloat32(byteOffset: number, value: number, littleEndian?: bool): void; + setFloat64(byteOffset: number, value: number, littleEndian?: bool): void; +} +declare var DataView: { + prototype: DataView; + new (buffer: ArrayBuffer, byteOffset?: number, length?: number): DataView; +} + +//////////////// +/// IE9 DOM APIs (note that +//////////////// + +interface NavigatorID { + appVersion: string; + appName: string; + userAgent: string; + platform: string; +} + +interface HTMLTableElement extends HTMLElement, DOML2DeprecatedBorderStyle_HTMLTableElement, DOML2DeprecatedAlignmentStyle_HTMLTableElement, MSBorderColorStyle, MSDataBindingExtensions, MSHTMLTableElementExtensions, DOML2DeprecatedBackgroundStyle, MSBorderColorHighlightStyle, MSDataBindingTableExtensions, DOML2DeprecatedBackgroundColorStyle { + tBodies: HTMLCollection; + width: string; + tHead: HTMLTableSectionElement; + cellSpacing: string; + tFoot: HTMLTableSectionElement; + frame: string; + rows: HTMLCollection; + rules: string; + cellPadding: string; + summary: string; + caption: HTMLTableCaptionElement; + deleteRow(index?: number): void; + createTBody(): HTMLElement; + deleteCaption(): void; + insertRow(index?: number): HTMLElement; + deleteTFoot(): void; + createTHead(): HTMLElement; + deleteTHead(): void; + createCaption(): HTMLElement; + createTFoot(): HTMLElement; +} +declare var HTMLTableElement: { + prototype: HTMLTableElement; + new(): HTMLTableElement; +} + +interface TreeWalker { + whatToShow: number; + filter: NodeFilterCallback; + root: Node; + currentNode: Node; + expandEntityReferences: bool; + previousSibling(): Node; + lastChild(): Node; + nextSibling(): Node; + nextNode(): Node; + parentNode(): Node; + firstChild(): Node; + previousNode(): Node; +} +declare var TreeWalker: { + prototype: TreeWalker; + new(): TreeWalker; +} + +interface GetSVGDocument { + getSVGDocument(): SVGDocument; +} + +interface HTMLHtmlElementDOML2Deprecated { + version: string; +} + +interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { + y: number; + y1: number; + x: number; + x1: number; +} +declare var SVGPathSegCurvetoQuadraticRel: { + prototype: SVGPathSegCurvetoQuadraticRel; + new(): SVGPathSegCurvetoQuadraticRel; +} + +interface Performance { + navigation: PerformanceNavigation; + timing: PerformanceTiming; + toJSON(): any; +} +declare var Performance: { + prototype: Performance; + new(): Performance; +} + +interface SVGSVGElementEventHandlers { + onresize: (ev: UIEvent) => any; + onunload: (ev: Event) => any; + onscroll: (ev: UIEvent) => any; + onerror: (ev: Event) => any; + onzoom: (ev: any) => any; + onabort: (ev: UIEvent) => any; +} + +interface MSDataBindingTableExtensions { + dataPageSize: number; + nextPage(): void; + firstPage(): void; + refresh(): void; + previousPage(): void; + lastPage(): void; +} + +interface DOML2DeprecatedAlignmentStyle_HTMLParagraphElement { + align: string; +} + +interface CompositionEvent extends UIEvent { + data: string; + locale: string; + initCompositionEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, dataArg: string, locale: string): void; +} +declare var CompositionEvent: { + prototype: CompositionEvent; + new(): CompositionEvent; +} + +interface SVGMarkerElement extends SVGElement, SVGStylable, SVGLangSpace, SVGFitToViewBox { + orientType: SVGAnimatedEnumeration; + markerUnits: SVGAnimatedEnumeration; + markerWidth: SVGAnimatedLength; + markerHeight: SVGAnimatedLength; + orientAngle: SVGAnimatedAngle; + refY: SVGAnimatedLength; + refX: SVGAnimatedLength; + setOrientToAngle(angle: SVGAngle): void; + setOrientToAuto(): void; + SVG_MARKER_ORIENT_UNKNOWN: number; + SVG_MARKER_ORIENT_ANGLE: number; + SVG_MARKERUNITS_UNKNOWN: number; + SVG_MARKERUNITS_STROKEWIDTH: number; + SVG_MARKER_ORIENT_AUTO: number; + SVG_MARKERUNITS_USERSPACEONUSE: number; +} +declare var SVGMarkerElement: { + prototype: SVGMarkerElement; + new(): SVGMarkerElement; + SVG_MARKER_ORIENT_UNKNOWN: number; + SVG_MARKER_ORIENT_ANGLE: number; + SVG_MARKERUNITS_UNKNOWN: number; + SVG_MARKERUNITS_STROKEWIDTH: number; + SVG_MARKER_ORIENT_AUTO: number; + SVG_MARKERUNITS_USERSPACEONUSE: number; +} + +interface WindowTimers { + clearTimeout(handle: number): void; + setTimeout(expression: any, msec?: number, language?: any): number; + clearInterval(handle: number): void; + setInterval(expression: any, msec?: number, language?: any): number; +} + +interface CSSStyleDeclaration extends CSS3Properties, SVG1_1Properties, CSS2Properties { + cssText: string; + length: number; + parentRule: CSSRule; + getPropertyPriority(propertyName: string): string; + getPropertyValue(propertyName: string): string; + removeProperty(propertyName: string): string; + item(index: number): string; + [index: number]: string; + setProperty(propertyName: string, value: string, priority?: string): void; +} +declare var CSSStyleDeclaration: { + prototype: CSSStyleDeclaration; + new(): CSSStyleDeclaration; +} + +interface SVGGElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests { +} +declare var SVGGElement: { + prototype: SVGGElement; + new(): SVGGElement; +} + +interface MSStyleCSSProperties extends MSCSSProperties { + pixelWidth: number; + posHeight: number; + posLeft: number; + pixelTop: number; + pixelBottom: number; + textDecorationNone: bool; + pixelLeft: number; + posTop: number; + posBottom: number; + textDecorationOverline: bool; + posWidth: number; + textDecorationLineThrough: bool; + pixelHeight: number; + textDecorationBlink: bool; + posRight: number; + pixelRight: number; + textDecorationUnderline: bool; +} +declare var MSStyleCSSProperties: { + prototype: MSStyleCSSProperties; + new(): MSStyleCSSProperties; +} + +interface MSCSSStyleSheetExtensions { + owningElement: Element; + imports: StyleSheetList; + isAlternate: bool; + rules: MSCSSRuleList; + isPrefAlternate: bool; + readOnly: bool; + cssText: string; + href: string; + id: string; + pages: StyleSheetPageList; + addImport(bstrURL: string, lIndex?: number): number; + addPageRule(bstrSelector: string, bstrStyle: string, lIndex?: number): number; + removeRule(lIndex: number): void; + addRule(bstrSelector: string, bstrStyle?: string, lIndex?: number): number; + removeImport(lIndex: number): void; +} + +interface Navigator extends NavigatorID, NavigatorOnLine, NavigatorDoNotTrack, NavigatorAbilities, NavigatorGeolocation, MSNavigatorAbilities { +} +declare var Navigator: { + prototype: Navigator; + new(): Navigator; +} + +interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { + y: number; + x2: number; + x: number; + y2: number; +} +declare var SVGPathSegCurvetoCubicSmoothAbs: { + prototype: SVGPathSegCurvetoCubicSmoothAbs; + new(): SVGPathSegCurvetoCubicSmoothAbs; +} + +interface MSBorderColorStyle_HTMLFrameSetElement { + borderColor: any; +} + +interface SVGZoomEvent extends UIEvent { + zoomRectScreen: SVGRect; + previousScale: number; + newScale: number; + previousTranslate: SVGPoint; + newTranslate: SVGPoint; +} +declare var SVGZoomEvent: { + prototype: SVGZoomEvent; + new(): SVGZoomEvent; +} + +interface NodeSelector { + querySelectorAll(selectors: string): NodeList; + querySelector(selectors: string): Element; +} + +interface HTMLTableDataCellElement extends HTMLTableCellElement, MSHTMLTableDataCellElementExtensions { +} +declare var HTMLTableDataCellElement: { + prototype: HTMLTableDataCellElement; + new(): HTMLTableDataCellElement; +} + +interface MSHTMLDirectoryElementExtensions extends DOML2DeprecatedListNumberingAndBulletStyle { +} + +interface HTMLBaseElement extends HTMLElement { + target: string; + href: string; +} +declare var HTMLBaseElement: { + prototype: HTMLBaseElement; + new(): HTMLBaseElement; +} + +interface ClientRect { + left: number; + width: number; + right: number; + top: number; + bottom: number; + height: number; +} +declare var ClientRect: { + prototype: ClientRect; + new(): ClientRect; +} + +interface PositionErrorCallback { + (error: PositionError): void; +} + +interface DOMImplementation extends DOMHTMLImplementation { + createDocumentType(qualifiedName: string, publicId: string, systemId: string): DocumentType; + createDocument(namespaceURI: string, qualifiedName: string, doctype: DocumentType): Document; + hasFeature(feature: string, version?: string): bool; +} +declare var DOMImplementation: { + prototype: DOMImplementation; + new(): DOMImplementation; +} + +interface DOML2DeprecatedWidthStyle_HTMLBlockElement { + width: number; +} + +interface SVGUnitTypes { + SVG_UNIT_TYPE_UNKNOWN: number; + SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: number; + SVG_UNIT_TYPE_USERSPACEONUSE: number; +} +declare var SVGUnitTypes: { + prototype: SVGUnitTypes; + new(): SVGUnitTypes; + SVG_UNIT_TYPE_UNKNOWN: number; + SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: number; + SVG_UNIT_TYPE_USERSPACEONUSE: number; +} + +interface DocumentRange { + createRange(): Range; +} + +interface MSHTMLDocumentExtensions { + onrowexit: (ev: MSEventObj) => any; + compatible: MSCompatibleInfoCollection; + oncontrolselect: (ev: MSEventObj) => any; + onrowsinserted: (ev: MSEventObj) => any; + onpropertychange: (ev: MSEventObj) => any; + media: string; + onafterupdate: (ev: MSEventObj) => any; + onhelp: (ev: Event) => any; + uniqueID: string; + onbeforeactivate: (ev: UIEvent) => any; + onstoragecommit: (ev: StorageEvent) => any; + onselectionchange: (ev: Event) => any; + documentMode: number; + onfocusout: (ev: FocusEvent) => any; + ondataavailable: (ev: MSEventObj) => any; + onbeforeupdate: (ev: MSEventObj) => any; + onfocusin: (ev: FocusEvent) => any; + security: string; + namespaces: MSNamespaceInfoCollection; + ondatasetcomplete: (ev: MSEventObj) => any; + onbeforedeactivate: (ev: UIEvent) => any; + onstop: (ev: Event) => any; + onactivate: (ev: UIEvent) => any; + onmssitemodejumplistitemremoved: (ev: MSSiteModeEvent) => any; + frames: Window; + onselectstart: (ev: Event) => any; + onerrorupdate: (ev: MSEventObj) => any; + parentWindow: Window; + ondeactivate: (ev: UIEvent) => any; + ondatasetchanged: (ev: MSEventObj) => any; + onrowsdelete: (ev: MSEventObj) => any; + onmsthumbnailclick: (ev: MSSiteModeEvent) => any; + onrowenter: (ev: MSEventObj) => any; + onbeforeeditfocus: (ev: MSEventObj) => any; + Script: MSScriptHost; + oncellchange: (ev: MSEventObj) => any; + URLUnencoded: string; + updateSettings(): void; + execCommandShowHelp(commandId: string): bool; + releaseCapture(): void; + focus(): void; +} + +interface CSS2Properties { + backgroundAttachment: string; + visibility: string; + fontFamily: string; + borderRightStyle: string; + clear: string; + content: string; + counterIncrement: string; + orphans: string; + marginBottom: string; + borderStyle: string; + counterReset: string; + outlineWidth: string; + marginRight: string; + paddingLeft: string; + borderBottom: string; + marginTop: string; + borderTopColor: string; + top: string; + fontWeight: string; + textIndent: string; + borderRight: string; + width: string; + listStyleImage: string; + cursor: string; + listStylePosition: string; + borderTopStyle: string; + direction: string; + maxWidth: string; + color: string; + clip: string; + borderRightWidth: string; + verticalAlign: string; + pageBreakAfter: string; + overflow: string; + borderBottomStyle: string; + borderLeftStyle: string; + fontStretch: string; + emptyCells: string; + padding: string; + paddingRight: string; + background: string; + bottom: string; + height: string; + paddingTop: string; + right: string; + borderLeftWidth: string; + borderLeft: string; + backgroundPosition: string; + backgroundColor: string; + widows: string; + lineHeight: string; + pageBreakInside: string; + borderTopWidth: string; + left: string; + outlineStyle: string; + borderTop: string; + paddingBottom: string; + outlineColor: string; + wordSpacing: string; + outline: string; + font: string; + marginLeft: string; + display: string; + maxHeight: string; + cssFloat: string; + letterSpacing: string; + borderSpacing: string; + backgroundRepeat: string; + fontSizeAdjust: string; + borderLeftColor: string; + borderWidth: string; + backgroundImage: string; + listStyleType: string; + whiteSpace: string; + fontStyle: string; + borderBottomColor: string; + minWidth: string; + position: string; + zIndex: string; + borderColor: string; + listStyle: string; + captionSide: string; + borderCollapse: string; + fontVariant: string; + quotes: string; + tableLayout: string; + unicodeBidi: string; + borderBottomWidth: string; + minHeight: string; + textDecoration: string; + fontSize: string; + border: string; + pageBreakBefore: string; + textAlign: string; + textTransform: string; + margin: string; + borderRightColor: string; +} + +interface MSImageResourceExtensions_HTMLInputElement { + dynsrc: string; + vrml: string; + lowsrc: string; + start: string; + loop: number; +} + +interface MSHTMLEmbedElementExtensions { + palette: string; + hidden: string; + pluginspage: string; + units: string; +} + +interface MSHTMLModElementExtensions { +} + +interface Element extends Node, NodeSelector, ElementTraversal, MSElementExtensions { + scrollTop: number; + clientLeft: number; + scrollLeft: number; + tagName: string; + clientWidth: number; + scrollWidth: number; + clientHeight: number; + clientTop: number; + scrollHeight: number; + getAttribute(name?: string): string; + getElementsByTagNameNS(namespaceURI: string, localName: string): NodeList; + hasAttributeNS(namespaceURI: string, localName: string): bool; + getBoundingClientRect(): ClientRect; + getAttributeNS(namespaceURI: string, localName: string): string; + getAttributeNodeNS(namespaceURI: string, localName: string): Attr; + setAttributeNodeNS(newAttr: Attr): Attr; + hasAttribute(name: string): bool; + removeAttribute(name?: string): void; + setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void; + getAttributeNode(name: string): Attr; + getElementsByTagName(name: string): NodeList; + setAttributeNode(newAttr: Attr): Attr; + getClientRects(): ClientRectList; + removeAttributeNode(oldAttr: Attr): Attr; + setAttribute(name?: string, value?: string): void; + removeAttributeNS(namespaceURI: string, localName: string): void; +} +declare var Element: { + prototype: Element; + new(): Element; +} + +interface SVGDocument { + rootElement: SVGSVGElement; +} + +interface HTMLNextIdElement extends HTMLElement { + n: string; +} +declare var HTMLNextIdElement: { + prototype: HTMLNextIdElement; + new(): HTMLNextIdElement; +} + +interface SVGPathSegMovetoRel extends SVGPathSeg { + y: number; + x: number; +} +declare var SVGPathSegMovetoRel: { + prototype: SVGPathSegMovetoRel; + new(): SVGPathSegMovetoRel; +} + +interface SVGLineElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests { + y1: SVGAnimatedLength; + x2: SVGAnimatedLength; + x1: SVGAnimatedLength; + y2: SVGAnimatedLength; +} +declare var SVGLineElement: { + prototype: SVGLineElement; + new(): SVGLineElement; +} + +interface HTMLParagraphElement extends HTMLElement, DOML2DeprecatedAlignmentStyle_HTMLParagraphElement, MSHTMLParagraphElementExtensions { +} +declare var HTMLParagraphElement: { + prototype: HTMLParagraphElement; + new(): HTMLParagraphElement; +} + +interface MSHTMLTextAreaElementExtensions { + status: any; + createTextRange(): TextRange; +} + +interface ErrorFunction { + (eventOrMessage: any, source: string, fileno: number): any; +} + +interface HTMLAreasCollection extends HTMLCollection { + remove(index?: number): void; + add(element: HTMLElement, before?: any): void; +} +declare var HTMLAreasCollection: { + prototype: HTMLAreasCollection; + new(): HTMLAreasCollection; +} + +interface SVGDescElement extends SVGElement, SVGStylable, SVGLangSpace { +} +declare var SVGDescElement: { + prototype: SVGDescElement; + new(): SVGDescElement; +} + +interface Node extends EventTarget { + nodeType: number; + previousSibling: Node; + localName: string; + namespaceURI: string; + textContent: string; + parentNode: Node; + nextSibling: Node; + nodeValue: string; + lastChild: Node; + childNodes: NodeList; + nodeName: string; + ownerDocument: Document; + attributes: Attr[]; + firstChild: Node; + prefix: string; + removeChild(oldChild: Node): Node; + appendChild(newChild: Node): Node; + isSupported(feature: string, version: string): bool; + isEqualNode(arg: Node): bool; + lookupPrefix(namespaceURI: string): string; + isDefaultNamespace(namespaceURI: string): bool; + compareDocumentPosition(other: Node): number; + normalize(): void; + isSameNode(other: Node): bool; + hasAttributes(): bool; + lookupNamespaceURI(prefix: string): string; + cloneNode(deep?: bool): Node; + hasChildNodes(): bool; + replaceChild(newChild: Node, oldChild: Node): Node; + insertBefore(newChild: Node, refChild?: Node): Node; + ENTITY_REFERENCE_NODE: number; + ATTRIBUTE_NODE: number; + DOCUMENT_FRAGMENT_NODE: number; + TEXT_NODE: number; + ELEMENT_NODE: number; + COMMENT_NODE: number; + DOCUMENT_POSITION_DISCONNECTED: number; + DOCUMENT_POSITION_CONTAINED_BY: number; + DOCUMENT_POSITION_CONTAINS: number; + DOCUMENT_TYPE_NODE: number; + DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: number; + DOCUMENT_NODE: number; + ENTITY_NODE: number; + PROCESSING_INSTRUCTION_NODE: number; + CDATA_SECTION_NODE: number; + NOTATION_NODE: number; + DOCUMENT_POSITION_FOLLOWING: number; + DOCUMENT_POSITION_PRECEDING: number; +} +declare var Node: { + prototype: Node; + new(): Node; + ENTITY_REFERENCE_NODE: number; + ATTRIBUTE_NODE: number; + DOCUMENT_FRAGMENT_NODE: number; + TEXT_NODE: number; + ELEMENT_NODE: number; + COMMENT_NODE: number; + DOCUMENT_POSITION_DISCONNECTED: number; + DOCUMENT_POSITION_CONTAINED_BY: number; + DOCUMENT_POSITION_CONTAINS: number; + DOCUMENT_TYPE_NODE: number; + DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: number; + DOCUMENT_NODE: number; + ENTITY_NODE: number; + PROCESSING_INSTRUCTION_NODE: number; + CDATA_SECTION_NODE: number; + NOTATION_NODE: number; + DOCUMENT_POSITION_FOLLOWING: number; + DOCUMENT_POSITION_PRECEDING: number; +} + +interface MSHTMLLegendElementExtensions { +} + +interface MSCSSStyleDeclarationExtensions { + getAttribute(attributeName: string, flags?: number): any; + setAttribute(attributeName: string, AttributeValue: any, flags?: number): void; + removeAttribute(attributeName: string, flags?: number): bool; +} + +interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { + y: number; + x: number; +} +declare var SVGPathSegCurvetoQuadraticSmoothRel: { + prototype: SVGPathSegCurvetoQuadraticSmoothRel; + new(): SVGPathSegCurvetoQuadraticSmoothRel; +} + +interface DOML2DeprecatedAlignmentStyle_HTMLTableRowElement { + align: string; +} + +interface DOML2DeprecatedBorderStyle_HTMLObjectElement { + border: string; +} + +interface MSHTMLSpanElementExtensions { +} + +interface MSHTMLObjectElementExtensions { + object: Object; + alt: string; + classid: string; + altHtml: string; + BaseHref: string; +} + +interface DOML2DeprecatedListSpaceReduction { + compact: bool; +} + +interface CSS3Properties { + textAlignLast: string; + textUnderlinePosition: string; + wordWrap: string; + borderTopLeftRadius: string; + backgroundClip: string; + msTransformOrigin: string; + opacity: string; + overflowY: string; + boxShadow: string; + backgroundSize: string; + wordBreak: string; + boxSizing: string; + rubyOverhang: string; + rubyAlign: string; + textJustify: string; + borderRadius: string; + overflowX: string; + borderTopRightRadius: string; + msTransform: string; + borderBottomLeftRadius: string; + rubyPosition: string; + borderBottomRightRadius: string; + backgroundOrigin: string; + textOverflow: string; +} + +interface MSScriptHost { +} +declare var MSScriptHost: { + prototype: MSScriptHost; + new(): MSScriptHost; +} + +interface SVGClipPathElement extends SVGElement, SVGUnitTypes, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests { + clipPathUnits: SVGAnimatedEnumeration; +} +declare var SVGClipPathElement: { + prototype: SVGClipPathElement; + new(): SVGClipPathElement; +} + +interface MouseEvent extends UIEvent, MSMouseEventExtensions { + pageX: number; + offsetY: number; + x: number; + y: number; + altKey: bool; + metaKey: bool; + ctrlKey: bool; + offsetX: number; + screenX: number; + clientY: number; + shiftKey: bool; + screenY: number; + relatedTarget: EventTarget; + button: number; + pageY: number; + buttons: number; + clientX: number; + initMouseEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: bool, altKeyArg: bool, shiftKeyArg: bool, metaKeyArg: bool, buttonArg: number, relatedTargetArg: EventTarget): void; + getModifierState(keyArg: string): bool; +} +declare var MouseEvent: { + prototype: MouseEvent; + new(): MouseEvent; +} + +interface DOML2DeprecatedAlignmentStyle_HTMLTableElement { + align: string; +} + +interface RangeException { + code: number; + message: string; + toString(): string; + INVALID_NODE_TYPE_ERR: number; + BAD_BOUNDARYPOINTS_ERR: number; +} +declare var RangeException: { + prototype: RangeException; + new(): RangeException; + INVALID_NODE_TYPE_ERR: number; + BAD_BOUNDARYPOINTS_ERR: number; +} + +interface DOML2DeprecatedAlignmentStyle_HTMLHRElement { + align: string; +} + +interface SVGTextPositioningElement extends SVGTextContentElement { + y: SVGAnimatedLengthList; + rotate: SVGAnimatedNumberList; + dy: SVGAnimatedLengthList; + x: SVGAnimatedLengthList; + dx: SVGAnimatedLengthList; +} +declare var SVGTextPositioningElement: { + prototype: SVGTextPositioningElement; + new(): SVGTextPositioningElement; +} + +interface HTMLAppletElement extends HTMLElement, DOML2DeprecatedWidthStyle_HTMLAppletElement, DOML2DeprecatedMarginStyle_HTMLObjectElement, MSHTMLAppletElementExtensions, MSDataBindingExtensions, MSDataBindingRecordSetExtensions, DOML2DeprecatedAlignmentStyle_HTMLObjectElement { + object: string; + archive: string; + codeBase: string; + alt: string; + name: string; + height: string; + code: string; +} +declare var HTMLAppletElement: { + prototype: HTMLAppletElement; + new(): HTMLAppletElement; +} + +interface MSHTMLFieldSetElementExtensions extends DOML2DeprecatedAlignmentStyle_HTMLFieldSetElement { +} + +interface DocumentEvent { + createEvent(eventInterface: string): Event; +} + +interface MSHTMLUnknownElementExtensions { +} + +interface TextMetrics { + width: number; +} +declare var TextMetrics: { + prototype: TextMetrics; + new(): TextMetrics; +} + +interface DOML2DeprecatedWordWrapSuppression_HTMLBodyElement { + noWrap: bool; +} + +interface HTMLOListElement extends HTMLElement, DOML2DeprecatedListNumberingAndBulletStyle, DOML2DeprecatedListSpaceReduction, MSHTMLOListElementExtensions { + start: number; +} +declare var HTMLOListElement: { + prototype: HTMLOListElement; + new(): HTMLOListElement; +} + +interface MSHTMLTableCaptionElementExtensions { + vAlign: string; +} + +interface SVGAnimatedString { + animVal: string; + baseVal: string; +} +declare var SVGAnimatedString: { + prototype: SVGAnimatedString; + new(): SVGAnimatedString; +} + +interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { + y: number; +} +declare var SVGPathSegLinetoVerticalRel: { + prototype: SVGPathSegLinetoVerticalRel; + new(): SVGPathSegLinetoVerticalRel; +} + +interface CDATASection extends Text { +} +declare var CDATASection: { + prototype: CDATASection; + new(): CDATASection; +} + +interface StyleMedia { + type: string; + matchMedium(mediaquery: string): bool; +} +declare var StyleMedia: { + prototype: StyleMedia; + new(): StyleMedia; +} + +interface TextRange { + boundingLeft: number; + htmlText: string; + offsetLeft: number; + boundingWidth: number; + boundingHeight: number; + boundingTop: number; + text: string; + offsetTop: number; + moveToPoint(x: number, y: number): void; + queryCommandValue(cmdID: string): any; + getBookmark(): string; + move(Unit: string, Count?: number): number; + queryCommandIndeterm(cmdID: string): bool; + scrollIntoView(fStart?: bool): void; + findText(string: string, count?: number, flags?: number): bool; + execCommand(cmdID: string, showUI?: bool, value?: any): bool; + getBoundingClientRect(): ClientRect; + moveToBookmark(Bookmark: string): bool; + isEqual(range: TextRange): bool; + duplicate(): TextRange; + collapse(Start?: bool): void; + queryCommandText(cmdID: string): string; + select(): void; + pasteHTML(html: string): void; + inRange(range: TextRange): bool; + moveEnd(Unit: string, Count?: number): number; + getClientRects(): ClientRectList; + moveStart(Unit: string, Count?: number): number; + parentElement(): Element; + queryCommandState(cmdID: string): bool; + compareEndPoints(how: string, sourceRange: TextRange): number; + execCommandShowHelp(cmdID: string): bool; + moveToElementText(element: Element): void; + expand(Unit: string): bool; + queryCommandSupported(cmdID: string): bool; + setEndPoint(how: string, SourceRange: TextRange): void; + queryCommandEnabled(cmdID: string): bool; +} +declare var TextRange: { + prototype: TextRange; + new(): TextRange; +} + +interface HTMLSelectElement extends HTMLElement, MSHTMLCollectionExtensions, MSDataBindingExtensions, MSHTMLSelectElementExtensions { + options: HTMLSelectElement; + value: string; + form: HTMLFormElement; + name: string; + size: number; + length: number; + selectedIndex: number; + multiple: bool; + type: string; + remove(index?: number): void; + add(element: HTMLElement, before?: any): void; + item(name?: any, index?: any): any; + (name: any, index: any): any; + namedItem(name: string): any; + [name: string]: any; + (name: string): any; +} +declare var HTMLSelectElement: { + prototype: HTMLSelectElement; + new(): HTMLSelectElement; +} + +interface CSSStyleSheet extends StyleSheet, MSCSSStyleSheetExtensions { + ownerRule: CSSRule; + cssRules: CSSRuleList; + insertRule(rule: string, index?: number): number; + deleteRule(index?: number): void; +} +declare var CSSStyleSheet: { + prototype: CSSStyleSheet; + new(): CSSStyleSheet; +} + +interface HTMLBlockElement extends HTMLElement, DOML2DeprecatedTextFlowControl_HTMLBlockElement, DOML2DeprecatedWidthStyle_HTMLBlockElement { + cite: string; +} +declare var HTMLBlockElement: { + prototype: HTMLBlockElement; + new(): HTMLBlockElement; +} + +interface SVGTests { + requiredFeatures: SVGStringList; + requiredExtensions: SVGStringList; + systemLanguage: SVGStringList; + hasExtension(extension: string): bool; +} + +interface MSSelection { + type: string; + typeDetail: string; + createRange(): TextRange; + clear(): void; + createRangeCollection(): TextRangeCollection; + empty(): void; +} +declare var MSSelection: { + prototype: MSSelection; + new(): MSSelection; +} + +interface MSHTMLDListElementExtensions { +} + +interface HTMLMetaElement extends HTMLElement, MSHTMLMetaElementExtensions { + httpEquiv: string; + name: string; + content: string; + scheme: string; +} +declare var HTMLMetaElement: { + prototype: HTMLMetaElement; + new(): HTMLMetaElement; +} + +interface Selection { + isCollapsed: bool; + anchorNode: Node; + focusNode: Node; + anchorOffset: number; + focusOffset: number; + rangeCount: number; + addRange(range: Range): void; + collapseToEnd(): void; + toString(): string; + selectAllChildren(parentNode: Node): void; + getRangeAt(index: number): Range; + collapse(parentNode: Node, offset: number): void; + removeAllRanges(): void; + collapseToStart(): void; + deleteFromDocument(): void; + removeRange(range: Range): void; +} +declare var Selection: { + prototype: Selection; + new(): Selection; +} + +interface SVGAnimatedAngle { + animVal: SVGAngle; + baseVal: SVGAngle; +} +declare var SVGAnimatedAngle: { + prototype: SVGAnimatedAngle; + new(): SVGAnimatedAngle; +} + +interface SVGPatternElement extends SVGElement, SVGUnitTypes, SVGStylable, SVGLangSpace, SVGTests, SVGFitToViewBox, SVGURIReference { + patternUnits: SVGAnimatedEnumeration; + y: SVGAnimatedLength; + width: SVGAnimatedLength; + x: SVGAnimatedLength; + patternContentUnits: SVGAnimatedEnumeration; + patternTransform: SVGAnimatedTransformList; + height: SVGAnimatedLength; +} +declare var SVGPatternElement: { + prototype: SVGPatternElement; + new(): SVGPatternElement; +} + +interface SVGScriptElement extends SVGElement, SVGURIReference { + type: string; +} +declare var SVGScriptElement: { + prototype: SVGScriptElement; + new(): SVGScriptElement; +} + +interface HTMLDDElement extends HTMLElement, DOML2DeprecatedWordWrapSuppression_HTMLDDElement { +} +declare var HTMLDDElement: { + prototype: HTMLDDElement; + new(): HTMLDDElement; +} + +interface NodeIterator { + whatToShow: number; + filter: NodeFilterCallback; + root: Node; + expandEntityReferences: bool; + nextNode(): Node; + detach(): void; + previousNode(): Node; +} +declare var NodeIterator: { + prototype: NodeIterator; + new(): NodeIterator; +} + +interface CSSStyleRule extends CSSRule, MSCSSStyleRuleExtensions { + selectorText: string; + style: MSStyleCSSProperties; +} +declare var CSSStyleRule: { + prototype: CSSStyleRule; + new(): CSSStyleRule; +} + +interface MSDataBindingRecordSetReadonlyExtensions { + recordset: Object; + namedRecordset(dataMember: string, hierarchy?: any): Object; +} + +interface HTMLLinkElement extends HTMLElement, MSLinkStyleExtensions, LinkStyle { + rel: string; + target: string; + href: string; + media: string; + rev: string; + type: string; + charset: string; + hreflang: string; +} +declare var HTMLLinkElement: { + prototype: HTMLLinkElement; + new(): HTMLLinkElement; +} + +interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { + viewTarget: SVGStringList; +} +declare var SVGViewElement: { + prototype: SVGViewElement; + new(): SVGViewElement; +} + +interface MSHTMLAppletElementExtensions extends DOML2DeprecatedBorderStyle_HTMLObjectElement { + codeType: string; + standby: string; + classid: string; + useMap: string; + form: HTMLFormElement; + data: string; + contentDocument: Document; + altHtml: string; + declare: bool; + type: string; + BaseHref: string; +} + +interface SVGLocatable { + farthestViewportElement: SVGElement; + nearestViewportElement: SVGElement; + getBBox(): SVGRect; + getTransformToElement(element: SVGElement): SVGMatrix; + getCTM(): SVGMatrix; + getScreenCTM(): SVGMatrix; +} + +interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, MSHTMLFontElementExtensions, DOML2DeprecatedSizeProperty { + face: string; +} +declare var HTMLFontElement: { + prototype: HTMLFontElement; + new(): HTMLFontElement; +} + +interface MSHTMLTableElementExtensions { + cells: HTMLCollection; + height: any; + cols: number; + moveRow(indexFrom?: number, indexTo?: number): Object; +} + +interface SVGTitleElement extends SVGElement, SVGStylable, SVGLangSpace { +} +declare var SVGTitleElement: { + prototype: SVGTitleElement; + new(): SVGTitleElement; +} + +interface ControlRangeCollection { + length: number; + queryCommandValue(cmdID: string): any; + remove(index: number): void; + add(item: Element): void; + queryCommandIndeterm(cmdID: string): bool; + scrollIntoView(varargStart?: any): void; + item(index: number): Element; + [index: number]: Element; + execCommand(cmdID: string, showUI?: bool, value?: any): bool; + addElement(item: Element): void; + queryCommandState(cmdID: string): bool; + queryCommandSupported(cmdID: string): bool; + queryCommandEnabled(cmdID: string): bool; + queryCommandText(cmdID: string): string; + select(): void; +} +declare var ControlRangeCollection: { + prototype: ControlRangeCollection; + new(): ControlRangeCollection; +} + +interface DOML2DeprecatedAlignmentStyle_HTMLImageElement { + align: string; +} + +interface MSHTMLFrameElementExtensions { + width: any; + contentWindow: Window; + onload: (ev: Event) => any; + frameBorder: string; + height: any; + border: string; + frameSpacing: any; +} + +interface MSNamespaceInfo extends MSEventAttachmentTarget { + urn: string; + onreadystatechange: (ev: Event) => any; + name: string; + readyState: string; + doImport(implementationUrl: string): void; +} +declare var MSNamespaceInfo: { + prototype: MSNamespaceInfo; + new(): MSNamespaceInfo; +} + +interface WindowSessionStorage { + sessionStorage: Storage; +} + +interface SVGAnimatedTransformList { + animVal: SVGTransformList; + baseVal: SVGTransformList; +} +declare var SVGAnimatedTransformList: { + prototype: SVGAnimatedTransformList; + new(): SVGAnimatedTransformList; +} + +interface HTMLTableCaptionElement extends HTMLElement, MSHTMLTableCaptionElementExtensions, DOML2DeprecatedAlignmentStyle_HTMLTableCaptionElement { +} +declare var HTMLTableCaptionElement: { + prototype: HTMLTableCaptionElement; + new(): HTMLTableCaptionElement; +} + +interface HTMLOptionElement extends HTMLElement, MSDataBindingExtensions { + index: number; + defaultSelected: bool; + value: string; + text: string; + form: HTMLFormElement; + label: string; + selected: bool; +} +declare var HTMLOptionElement: { + prototype: HTMLOptionElement; + new(): HTMLOptionElement; +} + +interface HTMLMapElement extends HTMLElement { + name: string; + areas: HTMLAreasCollection; +} +declare var HTMLMapElement: { + prototype: HTMLMapElement; + new(): HTMLMapElement; +} + +interface HTMLMenuElement extends HTMLElement, DOML2DeprecatedListSpaceReduction, MSHTMLMenuElementExtensions { + type: string; +} +declare var HTMLMenuElement: { + prototype: HTMLMenuElement; + new(): HTMLMenuElement; +} + +interface MouseWheelEvent extends MouseEvent { + wheelDelta: number; + initMouseWheelEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, buttonArg: number, relatedTargetArg: EventTarget, modifiersListArg: string, wheelDeltaArg: number): void; +} +declare var MouseWheelEvent: { + prototype: MouseWheelEvent; + new(): MouseWheelEvent; +} + +interface SVGFitToViewBox { + viewBox: SVGAnimatedRect; + preserveAspectRatio: SVGAnimatedPreserveAspectRatio; +} + +interface MSHTMLAnchorElementExtensions { + nameProp: string; + protocolLong: string; + urn: string; + mimeType: string; + Methods: string; +} + +interface SVGPointList { + numberOfItems: number; + replaceItem(newItem: SVGPoint, index: number): SVGPoint; + getItem(index: number): SVGPoint; + clear(): void; + appendItem(newItem: SVGPoint): SVGPoint; + initialize(newItem: SVGPoint): SVGPoint; + removeItem(index: number): SVGPoint; + insertItemBefore(newItem: SVGPoint, index: number): SVGPoint; +} +declare var SVGPointList: { + prototype: SVGPointList; + new(): SVGPointList; +} + +interface MSElementCSSInlineStyleExtensions { + doScroll(component?: any): void; + componentFromPoint(x: number, y: number): string; +} + +interface SVGAnimatedLengthList { + animVal: SVGLengthList; + baseVal: SVGLengthList; +} +declare var SVGAnimatedLengthList: { + prototype: SVGAnimatedLengthList; + new(): SVGAnimatedLengthList; +} + +interface MSHTMLTableDataCellElementExtensions { +} + +interface Window extends ViewCSS, MSEventAttachmentTarget, MSWindowExtensions, WindowPerformance, ScreenView, EventTarget, WindowLocalStorage, WindowSessionStorage, WindowTimers { + ondragend: (ev: DragEvent) => any; + onkeydown: (ev: KeyboardEvent) => any; + ondragover: (ev: DragEvent) => any; + onkeyup: (ev: KeyboardEvent) => any; + onreset: (ev: Event) => any; + onmouseup: (ev: MouseEvent) => any; + ondragstart: (ev: DragEvent) => any; + ondrag: (ev: DragEvent) => any; + onmouseover: (ev: MouseEvent) => any; + ondragleave: (ev: DragEvent) => any; + history: History; + name: string; + onafterprint: (ev: Event) => any; + onpause: (ev: Event) => any; + onbeforeprint: (ev: Event) => any; + top: Window; + onmousedown: (ev: MouseEvent) => any; + onseeked: (ev: Event) => any; + opener: Window; + onclick: (ev: MouseEvent) => any; + onwaiting: (ev: Event) => any; + ononline: (ev: Event) => any; + ondurationchange: (ev: Event) => any; + frames: Window; + onblur: (ev: FocusEvent) => any; + onemptied: (ev: Event) => any; + onseeking: (ev: Event) => any; + oncanplay: (ev: Event) => any; + onstalled: (ev: Event) => any; + onmousemove: (ev: MouseEvent) => any; + onoffline: (ev: Event) => any; + length: number; + onbeforeunload: (ev: BeforeUnloadEvent) => any; + onratechange: (ev: Event) => any; + onstorage: (ev: StorageEvent) => any; + onloadstart: (ev: Event) => any; + ondragenter: (ev: DragEvent) => any; + onsubmit: (ev: Event) => any; + self: Window; + onprogress: (ev: any) => any; + ondblclick: (ev: MouseEvent) => any; + oncontextmenu: (ev: MouseEvent) => any; + onchange: (ev: Event) => any; + onloadedmetadata: (ev: Event) => any; + onplay: (ev: Event) => any; + onerror: ErrorFunction; + onplaying: (ev: Event) => any; + parent: Window; + location: Location; + oncanplaythrough: (ev: Event) => any; + onabort: (ev: UIEvent) => any; + onreadystatechange: (ev: Event) => any; + onkeypress: (ev: KeyboardEvent) => any; + frameElement: Element; + onloadeddata: (ev: Event) => any; + onsuspend: (ev: Event) => any; + window: Window; + onfocus: (ev: FocusEvent) => any; + onmessage: (ev: MessageEvent) => any; + ontimeupdate: (ev: Event) => any; + onresize: (ev: UIEvent) => any; + navigator: Navigator; + onselect: (ev: UIEvent) => any; + ondrop: (ev: DragEvent) => any; + onmouseout: (ev: MouseEvent) => any; + onended: (ev: Event) => any; + onhashchange: (ev: Event) => any; + onunload: (ev: Event) => any; + onscroll: (ev: UIEvent) => any; + onmousewheel: (ev: MouseWheelEvent) => any; + onload: (ev: Event) => any; + onvolumechange: (ev: Event) => any; + oninput: (ev: Event) => any; + alert(message?: string): void; + focus(): void; + print(): void; + prompt(message?: string, defaul?: string): string; + toString(): string; + open(url?: string, target?: string, features?: string, replace?: bool): Window; + close(): void; + confirm(message?: string): bool; + postMessage(message: any, targetOrigin: string, ports?: any): void; + showModalDialog(url?: string, argument?: any, options?: any): any; + blur(): void; + getSelection(): Selection; +} +declare var Window: { + prototype: Window; + new(): Window; +} + +interface SVGAnimatedPreserveAspectRatio { + animVal: SVGPreserveAspectRatio; + baseVal: SVGPreserveAspectRatio; +} +declare var SVGAnimatedPreserveAspectRatio: { + prototype: SVGAnimatedPreserveAspectRatio; + new(): SVGAnimatedPreserveAspectRatio; +} + +interface MSSiteModeEvent extends Event { + buttonID: number; + actionURL: string; +} +declare var MSSiteModeEvent: { + prototype: MSSiteModeEvent; + new(): MSSiteModeEvent; +} + +interface MSCSSStyleRuleExtensions { + readOnly: bool; +} + +interface StyleSheetPageList { + length: number; + item(index: number): StyleSheetPage; + [index: number]: StyleSheetPage; +} +declare var StyleSheetPageList: { + prototype: StyleSheetPageList; + new(): StyleSheetPageList; +} + +interface HTMLCollection extends MSHTMLCollectionExtensions { + length: number; + item(nameOrIndex?: any, optionalIndex?: any): Element; + (nameOrIndex: any, optionalIndex: any): Element; + namedItem(name: string): Element; + [index: number]: Element; + [name: string]: Element; + (name: string): Element; +} +declare var HTMLCollection: { + prototype: HTMLCollection; + new(): HTMLCollection; +} + +interface MSCSSProperties extends CSSStyleDeclaration, MSCSSStyleDeclarationExtensions { + scrollbarShadowColor: string; + scrollbarHighlightColor: string; + layoutGridChar: string; + layoutGridType: string; + textAutospace: string; + textKashidaSpace: string; + writingMode: string; + scrollbarFaceColor: string; + backgroundPositionY: string; + lineBreak: string; + imeMode: string; + msBlockProgression: string; + layoutGridLine: string; + scrollbarBaseColor: string; + layoutGrid: string; + layoutFlow: string; + textKashida: string; + filter: string; + zoom: string; + scrollbarArrowColor: string; + behavior: string; + backgroundPositionX: string; + accelerator: string; + layoutGridMode: string; + textJustifyTrim: string; + scrollbar3dLightColor: string; + msInterpolationMode: string; + scrollbarTrackColor: string; + scrollbarDarkShadowColor: string; + styleFloat: string; +} +declare var MSCSSProperties: { + prototype: MSCSSProperties; + new(): MSCSSProperties; +} + +interface HTMLImageElement extends HTMLElement, DOML2DeprecatedMarginStyle, DOML2DeprecatedBorderStyle, DOML2DeprecatedAlignmentStyle_HTMLImageElement, MSImageResourceExtensions, MSHTMLImageElementExtensions, MSDataBindingExtensions, MSResourceMetadata { + width: number; + naturalHeight: number; + alt: string; + src: string; + useMap: string; + naturalWidth: number; + name: string; + height: number; + longDesc: string; + isMap: bool; + complete: bool; +} +declare var HTMLImageElement: { + prototype: HTMLImageElement; + new(): HTMLImageElement; +} + +interface HTMLAreaElement extends HTMLElement, MSHTMLAreaElementExtensions { + protocol: string; + search: string; + alt: string; + coords: string; + hostname: string; + port: string; + pathname: string; + host: string; + hash: string; + target: string; + href: string; + noHref: bool; + shape: string; + toString(): string; +} +declare var HTMLAreaElement: { + prototype: HTMLAreaElement; + new(): HTMLAreaElement; +} + +interface EventTarget { + removeEventListener(type: string, listener: EventListener, useCapture?: bool): void; + addEventListener(type: string, listener: EventListener, useCapture?: bool): void; + dispatchEvent(evt: Event): bool; +} + +interface SVGAngle { + valueAsString: string; + valueInSpecifiedUnits: number; + value: number; + unitType: number; + newValueSpecifiedUnits(unitType: number, valueInSpecifiedUnits: number): void; + convertToSpecifiedUnits(unitType: number): void; + SVG_ANGLETYPE_RAD: number; + SVG_ANGLETYPE_UNKNOWN: number; + SVG_ANGLETYPE_UNSPECIFIED: number; + SVG_ANGLETYPE_DEG: number; + SVG_ANGLETYPE_GRAD: number; +} +declare var SVGAngle: { + prototype: SVGAngle; + new(): SVGAngle; + SVG_ANGLETYPE_RAD: number; + SVG_ANGLETYPE_UNKNOWN: number; + SVG_ANGLETYPE_UNSPECIFIED: number; + SVG_ANGLETYPE_DEG: number; + SVG_ANGLETYPE_GRAD: number; +} + +interface HTMLButtonElement extends HTMLElement, MSHTMLButtonElementExtensions, MSDataBindingExtensions { + value: string; + form: HTMLFormElement; + name: string; + type: string; +} +declare var HTMLButtonElement: { + prototype: HTMLButtonElement; + new(): HTMLButtonElement; +} + +interface MSHTMLLabelElementExtensions { +} + +interface HTMLSourceElement extends HTMLElement { + src: string; + media: string; + type: string; +} +declare var HTMLSourceElement: { + prototype: HTMLSourceElement; + new(): HTMLSourceElement; +} + +interface CanvasGradient { + addColorStop(offset: number, color: string): void; +} +declare var CanvasGradient: { + prototype: CanvasGradient; + new(): CanvasGradient; +} + +interface KeyboardEvent extends UIEvent, KeyboardEventExtensions { + location: number; + shiftKey: bool; + locale: string; + key: string; + altKey: bool; + metaKey: bool; + char: string; + ctrlKey: bool; + repeat: bool; + getModifierState(keyArg: string): bool; + initKeyboardEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, keyArg: string, locationArg: number, modifiersListArg: string, repeat: bool, locale: string): void; + DOM_KEY_LOCATION_RIGHT: number; + DOM_KEY_LOCATION_STANDARD: number; + DOM_KEY_LOCATION_LEFT: number; + DOM_KEY_LOCATION_NUMPAD: number; + DOM_KEY_LOCATION_JOYSTICK: number; + DOM_KEY_LOCATION_MOBILE: number; +} +declare var KeyboardEvent: { + prototype: KeyboardEvent; + new(): KeyboardEvent; + DOM_KEY_LOCATION_RIGHT: number; + DOM_KEY_LOCATION_STANDARD: number; + DOM_KEY_LOCATION_LEFT: number; + DOM_KEY_LOCATION_NUMPAD: number; + DOM_KEY_LOCATION_JOYSTICK: number; + DOM_KEY_LOCATION_MOBILE: number; +} + +interface Document extends Node, DocumentStyle, DocumentRange, HTMLDocument, NodeSelector, DocumentEvent, DocumentTraversal, DocumentView, SVGDocument { + doctype: DocumentType; + xmlVersion: string; + implementation: DOMImplementation; + xmlEncoding: string; + xmlStandalone: bool; + documentElement: HTMLElement; + inputEncoding: string; + createElement(tagName: string): HTMLElement; + adoptNode(source: Node): Node; + createComment(data: string): Comment; + createDocumentFragment(): DocumentFragment; + getElementsByTagName(tagname: string): NodeList; + getElementsByTagNameNS(namespaceURI: string, localName: string): NodeList; + createProcessingInstruction(target: string, data: string): ProcessingInstruction; + createElementNS(namespaceURI: string, qualifiedName: string): Element; + createAttribute(name: string): Attr; + createTextNode(data: string): Text; + importNode(importedNode: Node, deep: bool): Node; + createCDATASection(data: string): CDATASection; + createAttributeNS(namespaceURI: string, qualifiedName: string): Attr; + getElementById(elementId: string): HTMLElement; +} +declare var Document: { + prototype: Document; + new(): Document; +} + +interface MessageEvent extends Event { + source: Window; + origin: string; + data: any; + initMessageEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: Window): void; +} +declare var MessageEvent: { + prototype: MessageEvent; + new(): MessageEvent; +} + +interface SVGElement extends Element, SVGElementEventHandlers { + xmlbase: string; + viewportElement: SVGElement; + id: string; + ownerSVGElement: SVGSVGElement; +} +declare var SVGElement: { + prototype: SVGElement; + new(): SVGElement; +} + +interface HTMLScriptElement extends HTMLElement { + defer: bool; + text: string; + src: string; + htmlFor: string; + charset: string; + type: string; + event: string; +} +declare var HTMLScriptElement: { + prototype: HTMLScriptElement; + new(): HTMLScriptElement; +} + +interface MSHTMLBodyElementExtensions extends DOML2DeprecatedWordWrapSuppression_HTMLBodyElement { + scroll: string; + bottomMargin: any; + topMargin: any; + rightMargin: any; + bgProperties: string; + leftMargin: any; + createTextRange(): TextRange; +} + +interface HTMLTableRowElement extends HTMLElement, MSBorderColorHighlightStyle_HTMLTableRowElement, HTMLTableAlignment, MSBorderColorStyle_HTMLTableRowElement, DOML2DeprecatedAlignmentStyle_HTMLTableRowElement, DOML2DeprecatedBackgroundColorStyle, MSHTMLTableRowElementExtensions { + rowIndex: number; + cells: HTMLCollection; + sectionRowIndex: number; + deleteCell(index?: number): void; + insertCell(index?: number): HTMLElement; +} +declare var HTMLTableRowElement: { + prototype: HTMLTableRowElement; + new(): HTMLTableRowElement; +} + +interface MSCommentExtensions { + text: string; +} + +interface DOML2DeprecatedMarginStyle_HTMLMarqueeElement { + vspace: number; + hspace: number; +} + +interface MSCSSRuleList { + length: number; + item(index?: number): CSSStyleRule; + [index: number]: CSSStyleRule; +} +declare var MSCSSRuleList: { + prototype: MSCSSRuleList; + new(): MSCSSRuleList; +} + +interface CanvasRenderingContext2D { + shadowOffsetX: number; + lineWidth: number; + miterLimit: number; + canvas: HTMLCanvasElement; + strokeStyle: any; + font: string; + globalAlpha: number; + globalCompositeOperation: string; + shadowOffsetY: number; + fillStyle: any; + lineCap: string; + shadowBlur: number; + textAlign: string; + textBaseline: string; + shadowColor: string; + lineJoin: string; + restore(): void; + setTransform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; + save(): void; + arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: bool): void; + measureText(text: string): TextMetrics; + isPointInPath(x: number, y: number): bool; + quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void; + putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void; + rotate(angle: number): void; + fillText(text: string, x: number, y: number, maxWidth?: number): void; + translate(x: number, y: number): void; + scale(x: number, y: number): void; + createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient; + lineTo(x: number, y: number): void; + fill(): void; + createPattern(image: HTMLElement, repetition: string): CanvasPattern; + closePath(): void; + rect(x: number, y: number, w: number, h: number): void; + clip(): void; + createImageData(imageDataOrSw: any, sh?: number): ImageData; + clearRect(x: number, y: number, w: number, h: number): void; + moveTo(x: number, y: number): void; + getImageData(sx: number, sy: number, sw: number, sh: number): ImageData; + fillRect(x: number, y: number, w: number, h: number): void; + bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void; + drawImage(image: HTMLElement, offsetX: number, offsetY: number, width?: number, height?: number, canvasOffsetX?: number, canvasOffsetY?: number, canvasImageWidth?: number, canvasImageHeight?: number): void; + transform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void; + stroke(): void; + strokeRect(x: number, y: number, w: number, h: number): void; + strokeText(text: string, x: number, y: number, maxWidth?: number): void; + beginPath(): void; + arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void; + createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient; +} +declare var CanvasRenderingContext2D: { + prototype: CanvasRenderingContext2D; + new(): CanvasRenderingContext2D; +} + +interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { + x: number; +} +declare var SVGPathSegLinetoHorizontalAbs: { + prototype: SVGPathSegLinetoHorizontalAbs; + new(): SVGPathSegLinetoHorizontalAbs; +} + +interface DOML2DeprecatedAlignmentStyle_HTMLObjectElement { + align: string; +} + +interface DOML2DeprecatedBorderStyle_MSHTMLIFrameElementExtensions { + border: string; +} + +interface MSHTMLElementRangeExtensions { + createControlRange(): ControlRangeCollection; +} + +interface SVGPathSegArcAbs extends SVGPathSeg { + y: number; + sweepFlag: bool; + r2: number; + x: number; + angle: number; + r1: number; + largeArcFlag: bool; +} +declare var SVGPathSegArcAbs: { + prototype: SVGPathSegArcAbs; + new(): SVGPathSegArcAbs; +} + +interface MSScreenExtensions { + deviceXDPI: number; + fontSmoothingEnabled: bool; + bufferDepth: number; + logicalXDPI: number; + systemXDPI: number; + logicalYDPI: number; + systemYDPI: number; + updateInterval: number; + deviceYDPI: number; +} + +interface HTMLHtmlElement extends HTMLElement, HTMLHtmlElementDOML2Deprecated { +} +declare var HTMLHtmlElement: { + prototype: HTMLHtmlElement; + new(): HTMLHtmlElement; +} + +interface MSBorderColorStyle { + borderColor: any; +} + +interface SVGTransformList { + numberOfItems: number; + getItem(index: number): SVGTransform; + consolidate(): SVGTransform; + clear(): void; + appendItem(newItem: SVGTransform): SVGTransform; + initialize(newItem: SVGTransform): SVGTransform; + removeItem(index: number): SVGTransform; + insertItemBefore(newItem: SVGTransform, index: number): SVGTransform; + replaceItem(newItem: SVGTransform, index: number): SVGTransform; + createSVGTransformFromMatrix(matrix: SVGMatrix): SVGTransform; +} +declare var SVGTransformList: { + prototype: SVGTransformList; + new(): SVGTransformList; +} + +interface SVGPathSegClosePath extends SVGPathSeg { +} +declare var SVGPathSegClosePath: { + prototype: SVGPathSegClosePath; + new(): SVGPathSegClosePath; +} + +interface DOML2DeprecatedMarginStyle_MSHTMLIFrameElementExtensions { + vspace: number; + hspace: number; +} + +interface HTMLFrameElement extends HTMLElement, GetSVGDocument, MSHTMLFrameElementExtensions, MSDataBindingExtensions, MSBorderColorStyle_HTMLFrameElement { + scrolling: string; + marginHeight: string; + src: string; + name: string; + marginWidth: string; + contentDocument: Document; + longDesc: string; + noResize: bool; +} +declare var HTMLFrameElement: { + prototype: HTMLFrameElement; + new(): HTMLFrameElement; +} + +interface SVGAnimatedLength { + animVal: SVGLength; + baseVal: SVGLength; +} +declare var SVGAnimatedLength: { + prototype: SVGAnimatedLength; + new(): SVGAnimatedLength; +} + +interface CSSMediaRule extends CSSRule { + media: MediaList; + cssRules: CSSRuleList; + insertRule(rule: string, index?: number): number; + deleteRule(index?: number): void; +} +declare var CSSMediaRule: { + prototype: CSSMediaRule; + new(): CSSMediaRule; +} + +interface HTMLQuoteElement extends HTMLElement, MSHTMLQuoteElementExtensions { + cite: string; +} +declare var HTMLQuoteElement: { + prototype: HTMLQuoteElement; + new(): HTMLQuoteElement; +} + +interface SVGDefsElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests { +} +declare var SVGDefsElement: { + prototype: SVGDefsElement; + new(): SVGDefsElement; +} + +interface SVGAnimatedPoints { + points: SVGPointList; + animatedPoints: SVGPointList; +} + +interface WindowModal { + dialogArguments: any; + returnValue: any; +} + +interface MSHTMLButtonElementExtensions { + status: any; + createTextRange(): TextRange; +} + +interface XMLHttpRequest extends EventTarget, MSXMLHttpRequestExtensions { + onreadystatechange: (ev: Event) => any; + status: number; + onload: (ev: Event) => any; + readyState: number; + responseText: string; + responseXML: Document; + statusText: string; + open(method: string, url: string, async?: bool, user?: string, password?: string): void; + send(data?: any): void; + abort(): void; + getAllResponseHeaders(): string; + setRequestHeader(header: string, value: string): void; + getResponseHeader(header: string): string; + LOADING: number; + DONE: number; + UNSENT: number; + OPENED: number; + HEADERS_RECEIVED: number; +} +declare var XMLHttpRequest: { + prototype: XMLHttpRequest; + new (): XMLHttpRequest; + LOADING: number; + DONE: number; + UNSENT: number; + OPENED: number; + HEADERS_RECEIVED: number; +} + +interface HTMLTableHeaderCellElement extends HTMLTableCellElement, HTMLTableHeaderCellScope { +} +declare var HTMLTableHeaderCellElement: { + prototype: HTMLTableHeaderCellElement; + new(): HTMLTableHeaderCellElement; +} + +interface HTMLDListElement extends HTMLElement, DOML2DeprecatedListSpaceReduction, MSHTMLDListElementExtensions { +} +declare var HTMLDListElement: { + prototype: HTMLDListElement; + new(): HTMLDListElement; +} + +interface MSDataBindingExtensions { + dataSrc: string; + dataFormatAs: string; + dataFld: string; +} + +interface SVGEllipseElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests { + ry: SVGAnimatedLength; + cx: SVGAnimatedLength; + rx: SVGAnimatedLength; + cy: SVGAnimatedLength; +} +declare var SVGEllipseElement: { + prototype: SVGEllipseElement; + new(): SVGEllipseElement; +} + +interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { + x: number; +} +declare var SVGPathSegLinetoHorizontalRel: { + prototype: SVGPathSegLinetoHorizontalRel; + new(): SVGPathSegLinetoHorizontalRel; +} + +interface SVGAElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests, SVGURIReference { + target: SVGAnimatedString; +} +declare var SVGAElement: { + prototype: SVGAElement; + new(): SVGAElement; +} + +interface MSHTMLMetaElementExtensions { + url: string; + charset: string; +} + +interface SVGStylable { + className: SVGAnimatedString; + style: CSSStyleDeclaration; +} + +interface MSHTMLTableCellElementExtensions { +} + +interface HTMLFrameSetElement extends HTMLElement, MSHTMLFrameSetElementExtensions, MSBorderColorStyle_HTMLFrameSetElement { + onresize: (ev: UIEvent) => any; + ononline: (ev: Event) => any; + onafterprint: (ev: Event) => any; + onbeforeprint: (ev: Event) => any; + onoffline: (ev: Event) => any; + rows: string; + cols: string; + onblur: (ev: FocusEvent) => any; + onunload: (ev: Event) => any; + onhashchange: (ev: Event) => any; + onfocus: (ev: FocusEvent) => any; + onmessage: (ev: MessageEvent) => any; + onload: (ev: Event) => any; + onerror: (ev: Event) => any; + onbeforeunload: (ev: BeforeUnloadEvent) => any; + onstorage: (ev: StorageEvent) => any; +} +declare var HTMLFrameSetElement: { + prototype: HTMLFrameSetElement; + new(): HTMLFrameSetElement; +} + +interface SVGTransformable extends SVGLocatable { + transform: SVGAnimatedTransformList; +} + +interface Screen extends MSScreenExtensions { + width: number; + colorDepth: number; + availWidth: number; + pixelDepth: number; + availHeight: number; + height: number; +} +declare var Screen: { + prototype: Screen; + new(): Screen; +} + +interface NavigatorGeolocation { + geolocation: Geolocation; +} + +interface Coordinates { + altitudeAccuracy: number; + longitude: number; + latitude: number; + speed: number; + heading: number; + altitude: number; + accuracy: number; +} +declare var Coordinates: { + prototype: Coordinates; + new(): Coordinates; +} + +interface DOML2DeprecatedAlignmentStyle_HTMLTableColElement { + align: string; +} + +interface EventListener { + (evt: Event): void; +} + +interface SVGLangSpace { + xmllang: string; + xmlspace: string; +} + +interface DataTransfer { + effectAllowed: string; + dropEffect: string; + clearData(format?: string): bool; + setData(format: string, data: string): bool; + getData(format: string): string; +} +declare var DataTransfer: { + prototype: DataTransfer; + new(): DataTransfer; +} + +interface FocusEvent extends UIEvent { + relatedTarget: EventTarget; + initFocusEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, detailArg: number, relatedTargetArg: EventTarget): void; +} +declare var FocusEvent: { + prototype: FocusEvent; + new(): FocusEvent; +} + +interface Range { + startOffset: number; + collapsed: bool; + endOffset: number; + startContainer: Node; + endContainer: Node; + commonAncestorContainer: Node; + setStart(refNode: Node, offset: number): void; + setEndBefore(refNode: Node): void; + setStartBefore(refNode: Node): void; + selectNode(refNode: Node): void; + detach(): void; + getBoundingClientRect(): ClientRect; + toString(): string; + compareBoundaryPoints(how: number, sourceRange: Range): number; + insertNode(newNode: Node): void; + collapse(toStart: bool): void; + selectNodeContents(refNode: Node): void; + cloneContents(): DocumentFragment; + setEnd(refNode: Node, offset: number): void; + cloneRange(): Range; + getClientRects(): ClientRectList; + surroundContents(newParent: Node): void; + deleteContents(): void; + setStartAfter(refNode: Node): void; + extractContents(): DocumentFragment; + setEndAfter(refNode: Node): void; + END_TO_END: number; + START_TO_START: number; + START_TO_END: number; + END_TO_START: number; +} +declare var Range: { + prototype: Range; + new(): Range; + END_TO_END: number; + START_TO_START: number; + START_TO_END: number; + END_TO_START: number; +} + +interface MSHTMLPreElementExtensions extends DOML2DeprecatedTextFlowControl_HTMLBlockElement { + cite: string; +} + +interface SVGPoint { + y: number; + x: number; + matrixTransform(matrix: SVGMatrix): SVGPoint; +} +declare var SVGPoint: { + prototype: SVGPoint; + new(): SVGPoint; +} + +interface MSPluginsCollection { + length: number; + refresh(reload?: bool): void; +} +declare var MSPluginsCollection: { + prototype: MSPluginsCollection; + new(): MSPluginsCollection; +} + +interface MSHTMLFontElementExtensions { +} + +interface SVGAnimatedNumberList { + animVal: SVGNumberList; + baseVal: SVGNumberList; +} +declare var SVGAnimatedNumberList: { + prototype: SVGAnimatedNumberList; + new(): SVGAnimatedNumberList; +} + +interface SVGSVGElement extends SVGElement, SVGZoomAndPan, SVGLangSpace, SVGLocatable, SVGTests, SVGFitToViewBox, SVGSVGElementEventHandlers, SVGStylable, DocumentEvent, ViewCSS_SVGSVGElement { + width: SVGAnimatedLength; + x: SVGAnimatedLength; + contentStyleType: string; + screenPixelToMillimeterY: number; + height: SVGAnimatedLength; + contentScriptType: string; + pixelUnitToMillimeterX: number; + currentTranslate: SVGPoint; + y: SVGAnimatedLength; + viewport: SVGRect; + currentScale: number; + screenPixelToMillimeterX: number; + pixelUnitToMillimeterY: number; + setCurrentTime(seconds: number): void; + createSVGLength(): SVGLength; + getIntersectionList(rect: SVGRect, referenceElement: SVGElement): NodeList; + unpauseAnimations(): void; + createSVGRect(): SVGRect; + checkIntersection(element: SVGElement, rect: SVGRect): bool; + unsuspendRedrawAll(): void; + pauseAnimations(): void; + suspendRedraw(maxWaitMilliseconds: number): number; + deselectAll(): void; + createSVGAngle(): SVGAngle; + getEnclosureList(rect: SVGRect, referenceElement: SVGElement): NodeList; + createSVGTransform(): SVGTransform; + unsuspendRedraw(suspendHandleID: number): void; + forceRedraw(): void; + getCurrentTime(): number; + checkEnclosure(element: SVGElement, rect: SVGRect): bool; + createSVGMatrix(): SVGMatrix; + createSVGPoint(): SVGPoint; + createSVGNumber(): SVGNumber; + createSVGTransformFromMatrix(matrix: SVGMatrix): SVGTransform; + getElementById(elementId: string): Element; +} +declare var SVGSVGElement: { + prototype: SVGSVGElement; + new(): SVGSVGElement; +} + +interface HTMLLabelElement extends HTMLElement, MSDataBindingExtensions, MSHTMLLabelElementExtensions { + htmlFor: string; + form: HTMLFormElement; +} +declare var HTMLLabelElement: { + prototype: HTMLLabelElement; + new(): HTMLLabelElement; +} + +interface MSResourceMetadata { + protocol: string; + fileSize: string; + fileUpdatedDate: string; + nameProp: string; + fileCreatedDate: string; + fileModifiedDate: string; + mimeType: string; +} + +interface MSHTMLQuoteElementExtensions { + dateTime: string; +} + +interface DOML2DeprecatedAlignmentStyle_HTMLIFrameElement { + align: string; +} + +interface HTMLLegendElement extends HTMLElement, DOML2DeprecatedAlignmentStyle_HTMLLegendElement, MSDataBindingExtensions, MSHTMLLegendElementExtensions { + form: HTMLFormElement; +} +declare var HTMLLegendElement: { + prototype: HTMLLegendElement; + new(): HTMLLegendElement; +} + +interface HTMLDirectoryElement extends HTMLElement, DOML2DeprecatedListSpaceReduction, MSHTMLDirectoryElementExtensions { +} +declare var HTMLDirectoryElement: { + prototype: HTMLDirectoryElement; + new(): HTMLDirectoryElement; +} + +interface NavigatorAbilities { +} + +interface MSHTMLImageElementExtensions { + href: string; +} + +interface SVGAnimatedInteger { + animVal: number; + baseVal: number; +} +declare var SVGAnimatedInteger: { + prototype: SVGAnimatedInteger; + new(): SVGAnimatedInteger; +} + +interface SVGTextElement extends SVGTextPositioningElement, SVGTransformable { +} +declare var SVGTextElement: { + prototype: SVGTextElement; + new(): SVGTextElement; +} + +interface SVGTSpanElement extends SVGTextPositioningElement { +} +declare var SVGTSpanElement: { + prototype: SVGTSpanElement; + new(): SVGTSpanElement; +} + +interface HTMLLIElement extends HTMLElement, DOML2DeprecatedListNumberingAndBulletStyle, MSHTMLLIElementExtensions { + value: number; +} +declare var HTMLLIElement: { + prototype: HTMLLIElement; + new(): HTMLLIElement; +} + +interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { + y: number; +} +declare var SVGPathSegLinetoVerticalAbs: { + prototype: SVGPathSegLinetoVerticalAbs; + new(): SVGPathSegLinetoVerticalAbs; +} + +interface ViewCSS { + getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; +} + +interface MSAttrExtensions { + expando: bool; +} + +interface MSStorageExtensions { + remainingSpace: number; +} + +interface SVGStyleElement extends SVGElement, SVGLangSpace { + media: string; + type: string; + title: string; +} +declare var SVGStyleElement: { + prototype: SVGStyleElement; + new(): SVGStyleElement; +} + +interface MSCurrentStyleCSSProperties extends MSCSSProperties { + blockDirection: string; + clipBottom: string; + clipLeft: string; + clipRight: string; + clipTop: string; + hasLayout: string; +} +declare var MSCurrentStyleCSSProperties: { + prototype: MSCurrentStyleCSSProperties; + new(): MSCurrentStyleCSSProperties; +} + +interface MSLinkStyleExtensions { + styleSheet: StyleSheet; +} + +interface MSHTMLCollectionExtensions { + urns(urn: any): Object; + tags(tagName: any): Object; +} + +interface DOML2DeprecatedWordWrapSuppression_HTMLDivElement { + noWrap: bool; +} + +interface DocumentTraversal { + createNodeIterator(root: Node, whatToShow: number, filter: NodeFilterCallback, entityReferenceExpansion: bool): NodeIterator; + createTreeWalker(root: Node, whatToShow: number, filter: NodeFilterCallback, entityReferenceExpansion: bool): TreeWalker; +} + +interface Storage extends MSStorageExtensions { + length: number; + getItem(key: string): any; + [key: string]: any; + setItem(key: string, data: string): void; + clear(): void; + removeItem(key: string): void; + key(index: number): string; + [index: number]: any; +} +declare var Storage: { + prototype: Storage; + new(): Storage; +} + +interface HTMLTableHeaderCellScope { + scope: string; +} + +interface HTMLIFrameElement extends HTMLElement, GetSVGDocument, MSHTMLIFrameElementExtensions, MSDataBindingExtensions, DOML2DeprecatedAlignmentStyle_HTMLIFrameElement { + width: string; + contentWindow: Window; + scrolling: string; + src: string; + marginHeight: string; + name: string; + marginWidth: string; + height: string; + contentDocument: Document; + longDesc: string; + frameBorder: string; +} +declare var HTMLIFrameElement: { + prototype: HTMLIFrameElement; + new(): HTMLIFrameElement; +} + +interface MSNavigatorAbilities { + userLanguage: string; + plugins: MSPluginsCollection; + cookieEnabled: bool; + appCodeName: string; + cpuClass: string; + appMinorVersion: string; + connectionSpeed: number; + browserLanguage: string; + mimeTypes: MSMimeTypesCollection; + product: string; + systemLanguage: string; + javaEnabled(): bool; + taintEnabled(): bool; +} + +interface TextRangeCollection { + length: number; + item(index: number): TextRange; + [index: number]: TextRange; +} +declare var TextRangeCollection: { + prototype: TextRangeCollection; + new(): TextRangeCollection; +} + +interface HTMLBodyElement extends HTMLElement, HTMLBodyElementDOML2Deprecated, MSHTMLBodyElementExtensions, DOML2DeprecatedBackgroundStyle, DOML2DeprecatedBackgroundColorStyle { + onresize: (ev: UIEvent) => any; + ononline: (ev: Event) => any; + onafterprint: (ev: Event) => any; + onbeforeprint: (ev: Event) => any; + onoffline: (ev: Event) => any; + onblur: (ev: FocusEvent) => any; + onhashchange: (ev: Event) => any; + onunload: (ev: Event) => any; + onfocus: (ev: FocusEvent) => any; + onmessage: (ev: MessageEvent) => any; + onload: (ev: Event) => any; + onerror: (ev: Event) => any; + onbeforeunload: (ev: BeforeUnloadEvent) => any; + onstorage: (ev: StorageEvent) => any; +} +declare var HTMLBodyElement: { + prototype: HTMLBodyElement; + new(): HTMLBodyElement; +} + +interface DocumentType extends Node { + name: string; + notations: NamedNodeMap; + systemId: string; + internalSubset: string; + entities: NamedNodeMap; + publicId: string; +} +declare var DocumentType: { + prototype: DocumentType; + new(): DocumentType; +} + +interface MSHTMLInputElementExtensions extends DOML2DeprecatedMarginStyle_HTMLInputElement, DOML2DeprecatedBorderStyle_HTMLInputElement { + status: bool; + complete: bool; + createTextRange(): TextRange; +} + +interface DOML2DeprecatedAlignmentStyle_HTMLLegendElement { + align: string; +} + +interface SVGRadialGradientElement extends SVGGradientElement { + cx: SVGAnimatedLength; + r: SVGAnimatedLength; + cy: SVGAnimatedLength; + fx: SVGAnimatedLength; + fy: SVGAnimatedLength; +} +declare var SVGRadialGradientElement: { + prototype: SVGRadialGradientElement; + new(): SVGRadialGradientElement; +} + +interface MutationEvent extends Event { + newValue: string; + attrChange: number; + attrName: string; + prevValue: string; + relatedNode: Node; + initMutationEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, relatedNodeArg: Node, prevValueArg: string, newValueArg: string, attrNameArg: string, attrChangeArg: number): void; + MODIFICATION: number; + REMOVAL: number; + ADDITION: number; +} +declare var MutationEvent: { + prototype: MutationEvent; + new(): MutationEvent; + MODIFICATION: number; + REMOVAL: number; + ADDITION: number; +} + +interface DragEvent extends MouseEvent { + dataTransfer: DataTransfer; + initDragEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: bool, altKeyArg: bool, shiftKeyArg: bool, metaKeyArg: bool, buttonArg: number, relatedTargetArg: EventTarget, dataTransferArg: DataTransfer): void; +} +declare var DragEvent: { + prototype: DragEvent; + new(): DragEvent; +} + +interface DOML2DeprecatedWidthStyle_HTMLTableCellElement { + width: number; +} + +interface HTMLTableSectionElement extends HTMLElement, MSHTMLTableSectionElementExtensions, DOML2DeprecatedAlignmentStyle_HTMLTableSectionElement, HTMLTableAlignment { + rows: HTMLCollection; + deleteRow(index?: number): void; + insertRow(index?: number): HTMLElement; +} +declare var HTMLTableSectionElement: { + prototype: HTMLTableSectionElement; + new(): HTMLTableSectionElement; +} + +interface DOML2DeprecatedListNumberingAndBulletStyle { + type: string; +} + +interface HTMLInputElement extends HTMLElement, DOML2DeprecatedAlignmentStyle_HTMLInputElement, MSImageResourceExtensions_HTMLInputElement, MSHTMLInputElementExtensions, MSDataBindingExtensions { + width: string; + defaultChecked: bool; + alt: string; + accept: string; + value: string; + src: string; + useMap: string; + name: string; + form: HTMLFormElement; + selectionStart: number; + height: string; + indeterminate: bool; + readOnly: bool; + size: number; + checked: bool; + maxLength: number; + selectionEnd: number; + type: string; + defaultValue: string; + setSelectionRange(start: number, end: number): void; + select(): void; +} +declare var HTMLInputElement: { + prototype: HTMLInputElement; + new(): HTMLInputElement; +} + +interface HTMLAnchorElement extends HTMLElement, MSHTMLAnchorElementExtensions, MSDataBindingExtensions { + rel: string; + protocol: string; + search: string; + coords: string; + hostname: string; + pathname: string; + target: string; + href: string; + name: string; + charset: string; + hreflang: string; + port: string; + host: string; + hash: string; + rev: string; + type: string; + shape: string; + toString(): string; +} +declare var HTMLAnchorElement: { + prototype: HTMLAnchorElement; + new(): HTMLAnchorElement; +} + +interface SVGImageElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests, SVGURIReference { + y: SVGAnimatedLength; + width: SVGAnimatedLength; + preserveAspectRatio: SVGAnimatedPreserveAspectRatio; + x: SVGAnimatedLength; + height: SVGAnimatedLength; +} +declare var SVGImageElement: { + prototype: SVGImageElement; + new(): SVGImageElement; +} + +interface MSElementExtensions { + msMatchesSelector(selectors: string): bool; + fireEvent(eventName: string, eventObj?: any): bool; +} + +interface HTMLParamElement extends HTMLElement { + value: string; + name: string; + type: string; + valueType: string; +} +declare var HTMLParamElement: { + prototype: HTMLParamElement; + new(): HTMLParamElement; +} + +interface MSHTMLDocumentViewExtensions { + createStyleSheet(href?: string, index?: number): CSSStyleSheet; +} + +interface SVGAnimatedNumber { + animVal: number; + baseVal: number; +} +declare var SVGAnimatedNumber: { + prototype: SVGAnimatedNumber; + new(): SVGAnimatedNumber; +} + +interface PerformanceTiming { + redirectStart: number; + domainLookupEnd: number; + responseStart: number; + domComplete: number; + domainLookupStart: number; + loadEventStart: number; + msFirstPaint: number; + unloadEventEnd: number; + fetchStart: number; + requestStart: number; + domInteractive: number; + navigationStart: number; + connectEnd: number; + loadEventEnd: number; + connectStart: number; + responseEnd: number; + domLoading: number; + redirectEnd: number; + unloadEventStart: number; + domContentLoadedEventStart: number; + domContentLoadedEventEnd: number; + toJSON(): any; +} +declare var PerformanceTiming: { + prototype: PerformanceTiming; + new(): PerformanceTiming; +} + +interface DOML2DeprecatedAlignmentStyle_HTMLInputElement { + align: string; +} + +interface HTMLPreElement extends HTMLElement, DOML2DeprecatedWidthStyle, MSHTMLPreElementExtensions { +} +declare var HTMLPreElement: { + prototype: HTMLPreElement; + new(): HTMLPreElement; +} + +interface EventException { + code: number; + message: string; + toString(): string; + DISPATCH_REQUEST_ERR: number; + UNSPECIFIED_EVENT_TYPE_ERR: number; +} +declare var EventException: { + prototype: EventException; + new(): EventException; + DISPATCH_REQUEST_ERR: number; + UNSPECIFIED_EVENT_TYPE_ERR: number; +} + +interface MSBorderColorHighlightStyle_HTMLTableCellElement { + borderColorLight: any; + borderColorDark: any; +} + +interface DOMHTMLImplementation { + createHTMLDocument(title: string): Document; +} + +interface NavigatorOnLine { + onLine: bool; +} + +interface SVGElementEventHandlers { + onmouseover: (ev: MouseEvent) => any; + onmousemove: (ev: MouseEvent) => any; + onmouseout: (ev: MouseEvent) => any; + ondblclick: (ev: MouseEvent) => any; + onfocusout: (ev: FocusEvent) => any; + onfocusin: (ev: FocusEvent) => any; + onmousedown: (ev: MouseEvent) => any; + onmouseup: (ev: MouseEvent) => any; + onload: (ev: Event) => any; + onclick: (ev: MouseEvent) => any; +} + +interface WindowLocalStorage { + localStorage: Storage; +} + +interface SVGMetadataElement extends SVGElement { +} +declare var SVGMetadataElement: { + prototype: SVGMetadataElement; + new(): SVGMetadataElement; +} + +interface SVGPathSegArcRel extends SVGPathSeg { + y: number; + sweepFlag: bool; + r2: number; + x: number; + angle: number; + r1: number; + largeArcFlag: bool; +} +declare var SVGPathSegArcRel: { + prototype: SVGPathSegArcRel; + new(): SVGPathSegArcRel; +} + +interface SVGPathSegMovetoAbs extends SVGPathSeg { + y: number; + x: number; +} +declare var SVGPathSegMovetoAbs: { + prototype: SVGPathSegMovetoAbs; + new(): SVGPathSegMovetoAbs; +} + +interface SVGStringList { + numberOfItems: number; + replaceItem(newItem: string, index: number): string; + getItem(index: number): string; + clear(): void; + appendItem(newItem: string): string; + initialize(newItem: string): string; + removeItem(index: number): string; + insertItemBefore(newItem: string, index: number): string; +} +declare var SVGStringList: { + prototype: SVGStringList; + new(): SVGStringList; +} + +interface XDomainRequest { + timeout: number; + onerror: (ev: Event) => any; + onload: (ev: Event) => any; + onprogress: (ev: any) => any; + ontimeout: (ev: Event) => any; + responseText: string; + contentType: string; + open(method: string, url: string): void; + abort(): void; + send(data?: any): void; +} +declare var XDomainRequest: { + prototype: XDomainRequest; + new (): XDomainRequest; +} + +interface DOML2DeprecatedBackgroundColorStyle { + bgColor: any; +} + +interface ElementTraversal { + childElementCount: number; + previousElementSibling: Element; + lastElementChild: Element; + nextElementSibling: Element; + firstElementChild: Element; +} + +interface SVGLength { + valueAsString: string; + valueInSpecifiedUnits: number; + value: number; + unitType: number; + newValueSpecifiedUnits(unitType: number, valueInSpecifiedUnits: number): void; + convertToSpecifiedUnits(unitType: number): void; + SVG_LENGTHTYPE_NUMBER: number; + SVG_LENGTHTYPE_CM: number; + SVG_LENGTHTYPE_PC: number; + SVG_LENGTHTYPE_PERCENTAGE: number; + SVG_LENGTHTYPE_MM: number; + SVG_LENGTHTYPE_PT: number; + SVG_LENGTHTYPE_IN: number; + SVG_LENGTHTYPE_EMS: number; + SVG_LENGTHTYPE_PX: number; + SVG_LENGTHTYPE_UNKNOWN: number; + SVG_LENGTHTYPE_EXS: number; +} +declare var SVGLength: { + prototype: SVGLength; + new(): SVGLength; + SVG_LENGTHTYPE_NUMBER: number; + SVG_LENGTHTYPE_CM: number; + SVG_LENGTHTYPE_PC: number; + SVG_LENGTHTYPE_PERCENTAGE: number; + SVG_LENGTHTYPE_MM: number; + SVG_LENGTHTYPE_PT: number; + SVG_LENGTHTYPE_IN: number; + SVG_LENGTHTYPE_EMS: number; + SVG_LENGTHTYPE_PX: number; + SVG_LENGTHTYPE_UNKNOWN: number; + SVG_LENGTHTYPE_EXS: number; +} + +interface SVGPolygonElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGAnimatedPoints, SVGTests { +} +declare var SVGPolygonElement: { + prototype: SVGPolygonElement; + new(): SVGPolygonElement; +} + +interface HTMLPhraseElement extends HTMLElement { + dateTime: string; + cite: string; +} +declare var HTMLPhraseElement: { + prototype: HTMLPhraseElement; + new(): HTMLPhraseElement; +} + +interface MSHTMLAreaElementExtensions { +} + +interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { + y: number; + y1: number; + x2: number; + x: number; + x1: number; + y2: number; +} +declare var SVGPathSegCurvetoCubicRel: { + prototype: SVGPathSegCurvetoCubicRel; + new(): SVGPathSegCurvetoCubicRel; +} + +interface MSEventObj { + nextPage: string; + keyCode: number; + toElement: Element; + returnValue: any; + dataFld: string; + y: number; + dataTransfer: DataTransfer; + propertyName: string; + url: string; + offsetX: number; + recordset: Object; + screenX: number; + buttonID: number; + wheelDelta: number; + reason: number; + origin: string; + data: string; + srcFilter: Object; + boundElements: HTMLCollection; + cancelBubble: bool; + altLeft: bool; + behaviorCookie: number; + bookmarks: BookmarkCollection; + type: string; + repeat: bool; + srcElement: Element; + source: Window; + fromElement: Element; + offsetY: number; + x: number; + behaviorPart: number; + qualifier: string; + altKey: bool; + ctrlKey: bool; + clientY: number; + shiftKey: bool; + shiftLeft: bool; + contentOverflow: bool; + screenY: number; + ctrlLeft: bool; + button: number; + srcUrn: string; + clientX: number; + actionURL: string; + getAttribute(strAttributeName: string, lFlags?: number): any; + setAttribute(strAttributeName: string, AttributeValue: any, lFlags?: number): void; + removeAttribute(strAttributeName: string, lFlags?: number): bool; +} +declare var MSEventObj: { + prototype: MSEventObj; + new(): MSEventObj; +} + +interface SVGTextContentElement extends SVGElement, SVGStylable, SVGLangSpace, SVGTests { + textLength: SVGAnimatedLength; + lengthAdjust: SVGAnimatedEnumeration; + getCharNumAtPosition(point: SVGPoint): number; + getStartPositionOfChar(charnum: number): SVGPoint; + getExtentOfChar(charnum: number): SVGRect; + getComputedTextLength(): number; + getSubStringLength(charnum: number, nchars: number): number; + selectSubString(charnum: number, nchars: number): void; + getNumberOfChars(): number; + getRotationOfChar(charnum: number): number; + getEndPositionOfChar(charnum: number): SVGPoint; + LENGTHADJUST_SPACING: number; + LENGTHADJUST_SPACINGANDGLYPHS: number; + LENGTHADJUST_UNKNOWN: number; +} +declare var SVGTextContentElement: { + prototype: SVGTextContentElement; + new(): SVGTextContentElement; + LENGTHADJUST_SPACING: number; + LENGTHADJUST_SPACINGANDGLYPHS: number; + LENGTHADJUST_UNKNOWN: number; +} + +interface DOML2DeprecatedColorProperty { + color: string; +} + +interface MSHTMLLIElementExtensions { +} + +interface HTMLCanvasElement extends HTMLElement { + width: number; + height: number; + toDataURL(): string; + toDataURL(type: string, ...args: any[]): string; + getContext(contextId: string): CanvasRenderingContext2D; +} +declare var HTMLCanvasElement: { + prototype: HTMLCanvasElement; + new(): HTMLCanvasElement; +} + +interface HTMLTitleElement extends HTMLElement { + text: string; +} +declare var HTMLTitleElement: { + prototype: HTMLTitleElement; + new(): HTMLTitleElement; +} + +interface Location { + hash: string; + protocol: string; + search: string; + href: string; + hostname: string; + port: string; + pathname: string; + host: string; + reload(flag?: bool): void; + replace(url: string): void; + assign(url: string): void; + toString(): string; +} +declare var Location: { + prototype: Location; + new(): Location; +} + +interface HTMLStyleElement extends HTMLElement, MSLinkStyleExtensions, LinkStyle { + media: string; + type: string; +} +declare var HTMLStyleElement: { + prototype: HTMLStyleElement; + new(): HTMLStyleElement; +} + +interface MSHTMLOptGroupElementExtensions { + index: number; + defaultSelected: bool; + text: string; + value: string; + form: HTMLFormElement; + selected: bool; +} + +interface MSBorderColorHighlightStyle { + borderColorLight: any; + borderColorDark: any; +} + +interface DOML2DeprecatedSizeProperty_HTMLBaseFontElement { + size: number; +} + +interface SVGTransform { + type: number; + angle: number; + matrix: SVGMatrix; + setTranslate(tx: number, ty: number): void; + setScale(sx: number, sy: number): void; + setMatrix(matrix: SVGMatrix): void; + setSkewY(angle: number): void; + setRotate(angle: number, cx: number, cy: number): void; + setSkewX(angle: number): void; + SVG_TRANSFORM_SKEWX: number; + SVG_TRANSFORM_UNKNOWN: number; + SVG_TRANSFORM_SCALE: number; + SVG_TRANSFORM_TRANSLATE: number; + SVG_TRANSFORM_MATRIX: number; + SVG_TRANSFORM_ROTATE: number; + SVG_TRANSFORM_SKEWY: number; +} +declare var SVGTransform: { + prototype: SVGTransform; + new(): SVGTransform; + SVG_TRANSFORM_SKEWX: number; + SVG_TRANSFORM_UNKNOWN: number; + SVG_TRANSFORM_SCALE: number; + SVG_TRANSFORM_TRANSLATE: number; + SVG_TRANSFORM_MATRIX: number; + SVG_TRANSFORM_ROTATE: number; + SVG_TRANSFORM_SKEWY: number; +} + +interface MSCSSFilter { + Percent: number; + Enabled: bool; + Duration: number; + Play(Duration: number): void; + Apply(): void; + Stop(): void; +} +declare var MSCSSFilter: { + prototype: MSCSSFilter; + new(): MSCSSFilter; +} + +interface UIEvent extends Event { + detail: number; + view: AbstractView; + initUIEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, detailArg: number): void; +} +declare var UIEvent: { + prototype: UIEvent; + new(): UIEvent; +} + +interface ViewCSS_SVGSVGElement { + getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; +} + +interface SVGURIReference { + href: SVGAnimatedString; +} + +interface SVGPathSeg { + pathSegType: number; + pathSegTypeAsLetter: string; + PATHSEG_MOVETO_REL: number; + PATHSEG_LINETO_VERTICAL_REL: number; + PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: number; + PATHSEG_CURVETO_QUADRATIC_REL: number; + PATHSEG_CURVETO_CUBIC_ABS: number; + PATHSEG_LINETO_HORIZONTAL_ABS: number; + PATHSEG_CURVETO_QUADRATIC_ABS: number; + PATHSEG_LINETO_ABS: number; + PATHSEG_CLOSEPATH: number; + PATHSEG_LINETO_HORIZONTAL_REL: number; + PATHSEG_CURVETO_CUBIC_SMOOTH_REL: number; + PATHSEG_LINETO_REL: number; + PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: number; + PATHSEG_ARC_REL: number; + PATHSEG_CURVETO_CUBIC_REL: number; + PATHSEG_UNKNOWN: number; + PATHSEG_LINETO_VERTICAL_ABS: number; + PATHSEG_ARC_ABS: number; + PATHSEG_MOVETO_ABS: number; + PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: number; +} +declare var SVGPathSeg: { + PATHSEG_MOVETO_REL: number; + PATHSEG_LINETO_VERTICAL_REL: number; + PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: number; + PATHSEG_CURVETO_QUADRATIC_REL: number; + PATHSEG_CURVETO_CUBIC_ABS: number; + PATHSEG_LINETO_HORIZONTAL_ABS: number; + PATHSEG_CURVETO_QUADRATIC_ABS: number; + PATHSEG_LINETO_ABS: number; + PATHSEG_CLOSEPATH: number; + PATHSEG_LINETO_HORIZONTAL_REL: number; + PATHSEG_CURVETO_CUBIC_SMOOTH_REL: number; + PATHSEG_LINETO_REL: number; + PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: number; + PATHSEG_ARC_REL: number; + PATHSEG_CURVETO_CUBIC_REL: number; + PATHSEG_UNKNOWN: number; + PATHSEG_LINETO_VERTICAL_ABS: number; + PATHSEG_ARC_ABS: number; + PATHSEG_MOVETO_ABS: number; + PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: number; +} + +interface WheelEvent extends MouseEvent { + deltaZ: number; + deltaX: number; + deltaMode: number; + deltaY: number; + initWheelEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, buttonArg: number, relatedTargetArg: EventTarget, modifiersListArg: string, deltaXArg: number, deltaYArg: number, deltaZArg: number, deltaMode: number): void; + DOM_DELTA_PIXEL: number; + DOM_DELTA_LINE: number; + DOM_DELTA_PAGE: number; +} +declare var WheelEvent: { + prototype: WheelEvent; + new(): WheelEvent; + DOM_DELTA_PIXEL: number; + DOM_DELTA_LINE: number; + DOM_DELTA_PAGE: number; +} + +interface DOML2DeprecatedAlignmentStyle_HTMLDivElement { + align: string; +} + +interface MSEventAttachmentTarget { + attachEvent(event: string, listener: EventListener): bool; + detachEvent(event: string, listener: EventListener): void; +} + +interface SVGNumber { + value: number; +} +declare var SVGNumber: { + prototype: SVGNumber; + new(): SVGNumber; +} + +interface SVGPathElement extends SVGElement, SVGStylable, SVGAnimatedPathData, SVGTransformable, SVGLangSpace, SVGTests { + getPathSegAtLength(distance: number): number; + getPointAtLength(distance: number): SVGPoint; + createSVGPathSegCurvetoQuadraticAbs(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticAbs; + createSVGPathSegLinetoRel(x: number, y: number): SVGPathSegLinetoRel; + createSVGPathSegCurvetoQuadraticRel(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticRel; + createSVGPathSegCurvetoCubicAbs(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicAbs; + createSVGPathSegLinetoAbs(x: number, y: number): SVGPathSegLinetoAbs; + createSVGPathSegClosePath(): SVGPathSegClosePath; + createSVGPathSegCurvetoCubicRel(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicRel; + createSVGPathSegCurvetoQuadraticSmoothRel(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothRel; + createSVGPathSegMovetoRel(x: number, y: number): SVGPathSegMovetoRel; + createSVGPathSegCurvetoCubicSmoothAbs(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothAbs; + createSVGPathSegMovetoAbs(x: number, y: number): SVGPathSegMovetoAbs; + createSVGPathSegLinetoVerticalRel(y: number): SVGPathSegLinetoVerticalRel; + createSVGPathSegArcRel(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: bool, sweepFlag: bool): SVGPathSegArcRel; + createSVGPathSegCurvetoQuadraticSmoothAbs(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothAbs; + createSVGPathSegLinetoHorizontalRel(x: number): SVGPathSegLinetoHorizontalRel; + getTotalLength(): number; + createSVGPathSegCurvetoCubicSmoothRel(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothRel; + createSVGPathSegLinetoHorizontalAbs(x: number): SVGPathSegLinetoHorizontalAbs; + createSVGPathSegLinetoVerticalAbs(y: number): SVGPathSegLinetoVerticalAbs; + createSVGPathSegArcAbs(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: bool, sweepFlag: bool): SVGPathSegArcAbs; +} +declare var SVGPathElement: { + prototype: SVGPathElement; + new(): SVGPathElement; +} + +interface MSCompatibleInfo { + version: string; + userAgent: string; +} +declare var MSCompatibleInfo: { + prototype: MSCompatibleInfo; + new(): MSCompatibleInfo; +} + +interface MSHTMLDocumentEventExtensions { + createEventObject(eventObj?: any): MSEventObj; + fireEvent(eventName: string, eventObj?: any): bool; +} + +interface Text extends CharacterData, MSNodeExtensions { + wholeText: string; + splitText(offset: number): Text; + replaceWholeText(content: string): Text; +} +declare var Text: { + prototype: Text; + new(): Text; +} + +interface SVGAnimatedRect { + animVal: SVGRect; + baseVal: SVGRect; +} +declare var SVGAnimatedRect: { + prototype: SVGAnimatedRect; + new(): SVGAnimatedRect; +} + +interface CSSNamespaceRule extends CSSRule { + namespaceURI: string; + prefix: string; +} +declare var CSSNamespaceRule: { + prototype: CSSNamespaceRule; + new(): CSSNamespaceRule; +} + +interface HTMLUnknownElement extends HTMLElement, MSDataBindingRecordSetReadonlyExtensions, MSHTMLUnknownElementExtensions { +} +declare var HTMLUnknownElement: { + prototype: HTMLUnknownElement; + new(): HTMLUnknownElement; +} + +interface SVGPathSegList { + numberOfItems: number; + replaceItem(newItem: SVGPathSeg, index: number): SVGPathSeg; + getItem(index: number): SVGPathSeg; + clear(): void; + appendItem(newItem: SVGPathSeg): SVGPathSeg; + initialize(newItem: SVGPathSeg): SVGPathSeg; + removeItem(index: number): SVGPathSeg; + insertItemBefore(newItem: SVGPathSeg, index: number): SVGPathSeg; +} +declare var SVGPathSegList: { + prototype: SVGPathSegList; + new(): SVGPathSegList; +} + +interface HTMLAudioElement extends HTMLMediaElement { +} +declare var HTMLAudioElement: { + prototype: HTMLAudioElement; + new(): HTMLAudioElement; +} + +interface MSImageResourceExtensions { + dynsrc: string; + vrml: string; + lowsrc: string; + start: string; + loop: number; +} + +interface MSBorderColorHighlightStyle_HTMLTableRowElement { + borderColorLight: any; + borderColorDark: any; +} + +interface PositionError { + code: number; + message: string; + toString(): string; + POSITION_UNAVAILABLE: number; + PERMISSION_DENIED: number; + TIMEOUT: number; +} +declare var PositionError: { + POSITION_UNAVAILABLE: number; + PERMISSION_DENIED: number; + TIMEOUT: number; +} + +interface BrowserPublic { +} +declare var BrowserPublic: { + prototype: BrowserPublic; + new(): BrowserPublic; +} + +interface HTMLTableCellElement extends HTMLElement, DOML2DeprecatedTableCellHeight, HTMLTableAlignment, MSBorderColorHighlightStyle_HTMLTableCellElement, DOML2DeprecatedWidthStyle_HTMLTableCellElement, DOML2DeprecatedBackgroundStyle, MSBorderColorStyle_HTMLTableCellElement, MSHTMLTableCellElementExtensions, DOML2DeprecatedAlignmentStyle_HTMLTableCellElement, HTMLTableHeaderCellScope, DOML2DeprecatedWordWrapSuppression, DOML2DeprecatedBackgroundColorStyle { + headers: string; + abbr: string; + rowSpan: number; + cellIndex: number; + colSpan: number; + axis: string; +} +declare var HTMLTableCellElement: { + prototype: HTMLTableCellElement; + new(): HTMLTableCellElement; +} + +interface MSNamespaceInfoCollection { + length: number; + add(namespace?: string, urn?: string, implementationUrl?: any): Object; + item(index: any): Object; + [index: string]: Object; + (index: any): Object; +} +declare var MSNamespaceInfoCollection: { + prototype: MSNamespaceInfoCollection; + new(): MSNamespaceInfoCollection; +} + +interface SVGElementInstance extends EventTarget { + previousSibling: SVGElementInstance; + parentNode: SVGElementInstance; + lastChild: SVGElementInstance; + nextSibling: SVGElementInstance; + childNodes: SVGElementInstanceList; + correspondingUseElement: SVGUseElement; + correspondingElement: SVGElement; + firstChild: SVGElementInstance; +} +declare var SVGElementInstance: { + prototype: SVGElementInstance; + new(): SVGElementInstance; +} + +interface MSHTMLUListElementExtensions { +} + +interface SVGCircleElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests { + cx: SVGAnimatedLength; + r: SVGAnimatedLength; + cy: SVGAnimatedLength; +} +declare var SVGCircleElement: { + prototype: SVGCircleElement; + new(): SVGCircleElement; +} + +interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedSizeProperty_HTMLBaseFontElement, DOML2DeprecatedColorProperty { + face: string; +} +declare var HTMLBaseFontElement: { + prototype: HTMLBaseFontElement; + new(): HTMLBaseFontElement; +} + +interface CustomEvent extends Event { + detail: Object; + initCustomEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, detailArg: Object): void; +} +declare var CustomEvent: { + prototype: CustomEvent; + new(): CustomEvent; +} + +interface CSSImportRule extends CSSRule { + styleSheet: CSSStyleSheet; + href: string; + media: MediaList; +} +declare var CSSImportRule: { + prototype: CSSImportRule; + new(): CSSImportRule; +} + +interface StyleSheetList { + length: number; + item(index?: number): StyleSheet; + [index: number]: StyleSheet; +} +declare var StyleSheetList: { + prototype: StyleSheetList; + new(): StyleSheetList; +} + +interface HTMLTextAreaElement extends HTMLElement, MSDataBindingExtensions, MSHTMLTextAreaElementExtensions { + value: string; + form: HTMLFormElement; + name: string; + selectionStart: number; + rows: number; + cols: number; + readOnly: bool; + wrap: string; + selectionEnd: number; + type: string; + defaultValue: string; + setSelectionRange(start: number, end: number): void; + select(): void; +} +declare var HTMLTextAreaElement: { + prototype: HTMLTextAreaElement; + new(): HTMLTextAreaElement; +} + +interface MSHTMLFormElementExtensions { + encoding: string; +} + +interface DOML2DeprecatedMarginStyle { + vspace: number; + hspace: number; +} + +interface Geolocation { + clearWatch(watchId: number): void; + getCurrentPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): void; + watchPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): number; +} +declare var Geolocation: { + prototype: Geolocation; + new(): Geolocation; +} + +interface MSWindowModeless { + dialogTop: any; + dialogLeft: any; + dialogWidth: any; + dialogHeight: any; + menuArguments: any; +} + +interface HTMLMarqueeElement extends HTMLElement, DOML2DeprecatedMarginStyle_HTMLMarqueeElement, MSDataBindingExtensions, MSHTMLMarqueeElementExtensions, DOML2DeprecatedBackgroundColorStyle { + width: string; + onbounce: (ev: Event) => any; + trueSpeed: bool; + scrollAmount: number; + scrollDelay: number; + behavior: string; + height: string; + loop: number; + direction: string; + onstart: (ev: Event) => any; + onfinish: (ev: Event) => any; + stop(): void; + start(): void; +} +declare var HTMLMarqueeElement: { + prototype: HTMLMarqueeElement; + new(): HTMLMarqueeElement; +} + +interface SVGRect { + y: number; + width: number; + x: number; + height: number; +} +declare var SVGRect: { + prototype: SVGRect; + new(): SVGRect; +} + +interface MSNodeExtensions { + swapNode(otherNode: Node): Node; + removeNode(deep?: bool): Node; + replaceNode(replacement: Node): Node; +} + +interface KeyboardEventExtensions { + keyCode: number; + which: number; + charCode: number; +} + +interface History { + length: number; + back(distance?: any): void; + forward(distance?: any): void; + go(delta?: any): void; +} +declare var History: { + prototype: History; + new(): History; +} + +interface DocumentStyle { + styleSheets: StyleSheetList; +} + +interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { + y: number; + y1: number; + x2: number; + x: number; + x1: number; + y2: number; +} +declare var SVGPathSegCurvetoCubicAbs: { + prototype: SVGPathSegCurvetoCubicAbs; + new(): SVGPathSegCurvetoCubicAbs; +} + +interface TimeRanges { + length: number; + start(index: number): number; + end(index: number): number; +} +declare var TimeRanges: { + prototype: TimeRanges; + new(): TimeRanges; +} + +interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { + y: number; + y1: number; + x: number; + x1: number; +} +declare var SVGPathSegCurvetoQuadraticAbs: { + prototype: SVGPathSegCurvetoQuadraticAbs; + new(): SVGPathSegCurvetoQuadraticAbs; +} + +interface MSHTMLSelectElementExtensions { +} + +interface CSSRule { + cssText: string; + parentStyleSheet: CSSStyleSheet; + parentRule: CSSRule; + type: number; + IMPORT_RULE: number; + MEDIA_RULE: number; + STYLE_RULE: number; + NAMESPACE_RULE: number; + PAGE_RULE: number; + UNKNOWN_RULE: number; + FONT_FACE_RULE: number; + CHARSET_RULE: number; +} +declare var CSSRule: { + prototype: CSSRule; + new(): CSSRule; + IMPORT_RULE: number; + MEDIA_RULE: number; + STYLE_RULE: number; + NAMESPACE_RULE: number; + PAGE_RULE: number; + UNKNOWN_RULE: number; + FONT_FACE_RULE: number; + CHARSET_RULE: number; +} + +interface SVGPathSegLinetoAbs extends SVGPathSeg { + y: number; + x: number; +} +declare var SVGPathSegLinetoAbs: { + prototype: SVGPathSegLinetoAbs; + new(): SVGPathSegLinetoAbs; +} + +interface MSMouseEventExtensions { + toElement: Element; + layerY: number; + fromElement: Element; + which: number; + layerX: number; +} + +interface HTMLModElement extends HTMLElement, MSHTMLModElementExtensions { + dateTime: string; + cite: string; +} +declare var HTMLModElement: { + prototype: HTMLModElement; + new(): HTMLModElement; +} + +interface DOML2DeprecatedWordWrapSuppression { + noWrap: bool; +} + +interface BeforeUnloadEvent extends Event { + returnValue: string; +} +declare var BeforeUnloadEvent: { + prototype: BeforeUnloadEvent; + new(): BeforeUnloadEvent; +} + +interface MSPopupWindow { + document: HTMLDocument; + isOpen: bool; + show(x: number, y: number, w: number, h: number, element?: any): void; + hide(): void; +} +declare var MSPopupWindow: { + prototype: MSPopupWindow; + new(): MSPopupWindow; +} + +interface SVGMatrix { + e: number; + c: number; + a: number; + b: number; + d: number; + f: number; + multiply(secondMatrix: SVGMatrix): SVGMatrix; + flipY(): SVGMatrix; + skewY(angle: number): SVGMatrix; + inverse(): SVGMatrix; + scaleNonUniform(scaleFactorX: number, scaleFactorY: number): SVGMatrix; + rotate(angle: number): SVGMatrix; + flipX(): SVGMatrix; + translate(x: number, y: number): SVGMatrix; + scale(scaleFactor: number): SVGMatrix; + rotateFromVector(x: number, y: number): SVGMatrix; + skewX(angle: number): SVGMatrix; +} +declare var SVGMatrix: { + prototype: SVGMatrix; + new(): SVGMatrix; +} + +interface SVGUseElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests, SVGURIReference { + y: SVGAnimatedLength; + width: SVGAnimatedLength; + animatedInstanceRoot: SVGElementInstance; + instanceRoot: SVGElementInstance; + x: SVGAnimatedLength; + height: SVGAnimatedLength; +} +declare var SVGUseElement: { + prototype: SVGUseElement; + new(): SVGUseElement; +} + +interface Event extends MSEventExtensions { + timeStamp: number; + defaultPrevented: bool; + isTrusted: bool; + currentTarget: EventTarget; + target: EventTarget; + eventPhase: number; + type: string; + cancelable: bool; + bubbles: bool; + initEvent(eventTypeArg: string, canBubbleArg: bool, cancelableArg: bool): void; + stopPropagation(): void; + stopImmediatePropagation(): void; + preventDefault(): void; + CAPTURING_PHASE: number; + AT_TARGET: number; + BUBBLING_PHASE: number; +} +declare var Event: { + prototype: Event; + new(): Event; + CAPTURING_PHASE: number; + AT_TARGET: number; + BUBBLING_PHASE: number; +} + +interface ImageData { + width: number; + data: number[]; + height: number; +} +declare var ImageData: { + prototype: ImageData; + new(): ImageData; +} + +interface MSHTMLElementExtensions { + onlosecapture: (ev: MSEventObj) => any; + onrowexit: (ev: MSEventObj) => any; + oncontrolselect: (ev: MSEventObj) => any; + onrowsinserted: (ev: MSEventObj) => any; + onmouseleave: (ev: MouseEvent) => any; + document: HTMLDocument; + behaviorUrns: MSBehaviorUrnsCollection; + onpropertychange: (ev: MSEventObj) => any; + children: HTMLCollection; + filters: Object; + onbeforecut: (ev: DragEvent) => any; + scopeName: string; + onbeforepaste: (ev: DragEvent) => any; + onmove: (ev: MSEventObj) => any; + onafterupdate: (ev: MSEventObj) => any; + onbeforecopy: (ev: DragEvent) => any; + onlayoutcomplete: (ev: MSEventObj) => any; + onresizeend: (ev: MSEventObj) => any; + uniqueID: string; + onhelp: (ev: Event) => any; + onbeforeactivate: (ev: UIEvent) => any; + isMultiLine: bool; + uniqueNumber: number; + tagUrn: string; + onfocusout: (ev: FocusEvent) => any; + ondataavailable: (ev: MSEventObj) => any; + hideFocus: bool; + onbeforeupdate: (ev: MSEventObj) => any; + onfilterchange: (ev: MSEventObj) => any; + onfocusin: (ev: FocusEvent) => any; + recordNumber: any; + parentTextEdit: Element; + ondatasetcomplete: (ev: MSEventObj) => any; + onbeforedeactivate: (ev: UIEvent) => any; + outerText: string; + onresizestart: (ev: MSEventObj) => any; + onactivate: (ev: UIEvent) => any; + isTextEdit: bool; + isDisabled: bool; + readyState: string; + all: HTMLCollection; + onmouseenter: (ev: MouseEvent) => any; + onmovestart: (ev: MSEventObj) => any; + onselectstart: (ev: Event) => any; + onpaste: (ev: DragEvent) => any; + canHaveHTML: bool; + innerText: string; + onerrorupdate: (ev: MSEventObj) => any; + ondeactivate: (ev: UIEvent) => any; + oncut: (ev: DragEvent) => any; + onmoveend: (ev: MSEventObj) => any; + onresize: (ev: UIEvent) => any; + language: string; + ondatasetchanged: (ev: MSEventObj) => any; + oncopy: (ev: DragEvent) => any; + onrowsdelete: (ev: MSEventObj) => any; + parentElement: HTMLElement; + onrowenter: (ev: MSEventObj) => any; + onbeforeeditfocus: (ev: MSEventObj) => any; + canHaveChildren: bool; + sourceIndex: number; + oncellchange: (ev: MSEventObj) => any; + dragDrop(): bool; + releaseCapture(): void; + addFilter(filter: Object): void; + setCapture(containerCapture?: bool): void; + removeBehavior(cookie: number): bool; + contains(child: HTMLElement): bool; + applyElement(apply: Element, where?: string): Element; + replaceAdjacentText(where: string, newText: string): string; + mergeAttributes(source: HTMLElement, preserveIdentity?: bool): void; + insertAdjacentElement(position: string, insertedElement: Element): Element; + insertAdjacentText(where: string, text: string): void; + getAdjacentText(where: string): string; + removeFilter(filter: Object): void; + setActive(): void; + addBehavior(bstrUrl: string, factory?: any): number; + clearAttributes(): void; +} + +interface HTMLTableColElement extends HTMLElement, MSHTMLTableColElementExtensions, HTMLTableAlignment, DOML2DeprecatedAlignmentStyle_HTMLTableColElement { + width: any; + span: number; +} +declare var HTMLTableColElement: { + prototype: HTMLTableColElement; + new(): HTMLTableColElement; +} + +interface HTMLDocument extends MSEventAttachmentTarget, MSHTMLDocumentSelection, MSHTMLDocumentExtensions, MSNodeExtensions, MSResourceMetadata, MSHTMLDocumentEventExtensions, MSHTMLDocumentViewExtensions { + ondragend: (ev: DragEvent) => any; + ondragover: (ev: DragEvent) => any; + onkeydown: (ev: KeyboardEvent) => any; + bgColor: string; + onkeyup: (ev: KeyboardEvent) => any; + onreset: (ev: Event) => any; + onmouseup: (ev: MouseEvent) => any; + ondragstart: (ev: DragEvent) => any; + scripts: HTMLCollection; + ondrag: (ev: DragEvent) => any; + linkColor: string; + ondragleave: (ev: DragEvent) => any; + onmouseover: (ev: MouseEvent) => any; + onpause: (ev: Event) => any; + charset: string; + vlinkColor: string; + onmousedown: (ev: MouseEvent) => any; + onseeked: (ev: Event) => any; + title: string; + onclick: (ev: MouseEvent) => any; + onwaiting: (ev: Event) => any; + defaultCharset: string; + embeds: HTMLCollection; + ondurationchange: (ev: Event) => any; + all: HTMLCollection; + applets: HTMLCollection; + forms: HTMLCollection; + onblur: (ev: FocusEvent) => any; + dir: string; + body: HTMLElement; + designMode: string; + onemptied: (ev: Event) => any; + domain: string; + onseeking: (ev: Event) => any; + oncanplay: (ev: Event) => any; + onstalled: (ev: Event) => any; + onmousemove: (ev: MouseEvent) => any; + onratechange: (ev: Event) => any; + onloadstart: (ev: Event) => any; + ondragenter: (ev: DragEvent) => any; + onsubmit: (ev: Event) => any; + onprogress: (ev: any) => any; + ondblclick: (ev: MouseEvent) => any; + oncontextmenu: (ev: MouseEvent) => any; + activeElement: Element; + onchange: (ev: Event) => any; + onloadedmetadata: (ev: Event) => any; + onerror: (ev: Event) => any; + onplay: (ev: Event) => any; + links: HTMLCollection; + onplaying: (ev: Event) => any; + URL: string; + images: HTMLCollection; + head: HTMLHeadElement; + location: Location; + cookie: string; + oncanplaythrough: (ev: Event) => any; + onabort: (ev: UIEvent) => any; + characterSet: string; + anchors: HTMLCollection; + lastModified: string; + onreadystatechange: (ev: Event) => any; + onkeypress: (ev: KeyboardEvent) => any; + onloadeddata: (ev: Event) => any; + plugins: HTMLCollection; + onsuspend: (ev: Event) => any; + referrer: string; + readyState: string; + alinkColor: string; + onfocus: (ev: FocusEvent) => any; + fgColor: string; + ontimeupdate: (ev: Event) => any; + onselect: (ev: UIEvent) => any; + ondrop: (ev: DragEvent) => any; + onmouseout: (ev: MouseEvent) => any; + onended: (ev: Event) => any; + compatMode: string; + onscroll: (ev: UIEvent) => any; + onmousewheel: (ev: MouseWheelEvent) => any; + onload: (ev: Event) => any; + onvolumechange: (ev: Event) => any; + oninput: (ev: Event) => any; + queryCommandValue(commandId: string): string; + queryCommandIndeterm(commandId: string): bool; + execCommand(commandId: string, showUI?: bool, value?: any): bool; + getElementsByName(elementName: string): NodeList; + writeln(...content: string[]): void; + open(url?: string, name?: string, features?: string, replace?: bool): any; + queryCommandState(commandId: string): bool; + close(): void; + hasFocus(): bool; + getElementsByClassName(classNames: string): NodeList; + queryCommandSupported(commandId: string): bool; + getSelection(): Selection; + queryCommandEnabled(commandId: string): bool; + write(...content: string[]): void; + queryCommandText(commandId: string): string; +} + +interface SVGException { + code: number; + message: string; + toString(): string; + SVG_MATRIX_NOT_INVERTABLE: number; + SVG_WRONG_TYPE_ERR: number; + SVG_INVALID_VALUE_ERR: number; +} +declare var SVGException: { + prototype: SVGException; + new(): SVGException; + SVG_MATRIX_NOT_INVERTABLE: number; + SVG_WRONG_TYPE_ERR: number; + SVG_INVALID_VALUE_ERR: number; +} + +interface DOML2DeprecatedTableCellHeight { + height: any; +} + +interface HTMLTableAlignment { + ch: string; + vAlign: string; + chOff: string; +} + +interface SVGAnimatedEnumeration { + animVal: number; + baseVal: number; +} +declare var SVGAnimatedEnumeration: { + prototype: SVGAnimatedEnumeration; + new(): SVGAnimatedEnumeration; +} + +interface SVGLinearGradientElement extends SVGGradientElement { + y1: SVGAnimatedLength; + x2: SVGAnimatedLength; + x1: SVGAnimatedLength; + y2: SVGAnimatedLength; +} +declare var SVGLinearGradientElement: { + prototype: SVGLinearGradientElement; + new(): SVGLinearGradientElement; +} + +interface DOML2DeprecatedSizeProperty { + size: number; +} + +interface MSHTMLHeadingElementExtensions extends DOML2DeprecatedTextFlowControl_HTMLBlockElement { +} + +interface MSBorderColorStyle_HTMLTableCellElement { + borderColor: any; +} + +interface DOML2DeprecatedWidthStyle_HTMLHRElement { + width: number; +} + +interface HTMLUListElement extends HTMLElement, DOML2DeprecatedListSpaceReduction, DOML2DeprecatedListNumberingAndBulletStyle, MSHTMLUListElementExtensions { +} +declare var HTMLUListElement: { + prototype: HTMLUListElement; + new(): HTMLUListElement; +} + +interface SVGRectElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests { + y: SVGAnimatedLength; + width: SVGAnimatedLength; + ry: SVGAnimatedLength; + rx: SVGAnimatedLength; + x: SVGAnimatedLength; + height: SVGAnimatedLength; +} +declare var SVGRectElement: { + prototype: SVGRectElement; + new(): SVGRectElement; +} + +interface DOML2DeprecatedBorderStyle { + border: string; +} + +interface HTMLDivElement extends HTMLElement, DOML2DeprecatedAlignmentStyle_HTMLDivElement, MSHTMLDivElementExtensions, MSDataBindingExtensions { +} +declare var HTMLDivElement: { + prototype: HTMLDivElement; + new(): HTMLDivElement; +} + +interface NavigatorDoNotTrack { + msDoNotTrack: string; +} + +interface SVG1_1Properties { + fillRule: string; + strokeLinecap: string; + stopColor: string; + glyphOrientationHorizontal: string; + kerning: string; + alignmentBaseline: string; + dominantBaseline: string; + fill: string; + strokeMiterlimit: string; + marker: string; + glyphOrientationVertical: string; + markerMid: string; + textAnchor: string; + fillOpacity: string; + strokeDasharray: string; + mask: string; + stopOpacity: string; + stroke: string; + strokeDashoffset: string; + strokeOpacity: string; + markerStart: string; + pointerEvents: string; + baselineShift: string; + markerEnd: string; + clipRule: string; + strokeLinejoin: string; + clipPath: string; + strokeWidth: string; +} + +interface NamedNodeMap { + length: number; + removeNamedItemNS(namespaceURI: string, localName: string): Node; + item(index: number): Node; + [index: number]: Node; + removeNamedItem(name: string): Node; + getNamedItem(name: string): Node; + [name: string]: Node; + setNamedItem(arg: Node): Node; + getNamedItemNS(namespaceURI: string, localName: string): Node; + setNamedItemNS(arg: Node): Node; +} +declare var NamedNodeMap: { + prototype: NamedNodeMap; + new(): NamedNodeMap; +} + +interface MediaList { + length: number; + mediaText: string; + deleteMedium(oldMedium: string): void; + appendMedium(newMedium: string): void; + item(index: number): string; + [index: number]: string; + toString(): string; +} +declare var MediaList: { + prototype: MediaList; + new(): MediaList; +} + +interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { + y: number; + x: number; +} +declare var SVGPathSegCurvetoQuadraticSmoothAbs: { + prototype: SVGPathSegCurvetoQuadraticSmoothAbs; + new(): SVGPathSegCurvetoQuadraticSmoothAbs; +} + +interface SVGLengthList { + numberOfItems: number; + replaceItem(newItem: SVGLength, index: number): SVGLength; + getItem(index: number): SVGLength; + clear(): void; + appendItem(newItem: SVGLength): SVGLength; + initialize(newItem: SVGLength): SVGLength; + removeItem(index: number): SVGLength; + insertItemBefore(newItem: SVGLength, index: number): SVGLength; +} +declare var SVGLengthList: { + prototype: SVGLengthList; + new(): SVGLengthList; +} + +interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { + y: number; + x2: number; + x: number; + y2: number; +} +declare var SVGPathSegCurvetoCubicSmoothRel: { + prototype: SVGPathSegCurvetoCubicSmoothRel; + new(): SVGPathSegCurvetoCubicSmoothRel; +} + +interface MSWindowExtensions { + status: string; + onmouseleave: (ev: MouseEvent) => any; + screenLeft: number; + offscreenBuffering: any; + maxConnectionsPerServer: number; + onmouseenter: (ev: MouseEvent) => any; + clipboardData: DataTransfer; + defaultStatus: string; + clientInformation: Navigator; + closed: bool; + onhelp: (ev: Event) => any; + external: BrowserPublic; + event: MSEventObj; + onfocusout: (ev: FocusEvent) => any; + screenTop: number; + onfocusin: (ev: FocusEvent) => any; + showModelessDialog(url?: string, argument?: any, options?: any): Window; + navigate(url: string): void; + resizeBy(x?: number, y?: number): void; + item(index: any): any; + resizeTo(x?: number, y?: number): void; + createPopup(arguments?: any): MSPopupWindow; + toStaticHTML(html: string): string; + execScript(code: string, language?: string): any; + msWriteProfilerMark(profilerMarkName: string): void; + moveTo(x?: number, y?: number): void; + moveBy(x?: number, y?: number): void; + showHelp(url: string, helpArg?: any, features?: string): void; +} + +interface ProcessingInstruction extends Node { + target: string; + data: string; +} +declare var ProcessingInstruction: { + prototype: ProcessingInstruction; + new(): ProcessingInstruction; +} + +interface MSBehaviorUrnsCollection { + length: number; + item(index: number): string; +} +declare var MSBehaviorUrnsCollection: { + prototype: MSBehaviorUrnsCollection; + new(): MSBehaviorUrnsCollection; +} + +interface CSSFontFaceRule extends CSSRule { + style: CSSStyleDeclaration; +} +declare var CSSFontFaceRule: { + prototype: CSSFontFaceRule; + new(): CSSFontFaceRule; +} + +interface DOML2DeprecatedBackgroundStyle { + background: string; +} + +interface TextEvent extends UIEvent { + inputMethod: number; + data: string; + locale: string; + initTextEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, dataArg: string, inputMethod: number, locale: string): void; + DOM_INPUT_METHOD_KEYBOARD: number; + DOM_INPUT_METHOD_DROP: number; + DOM_INPUT_METHOD_IME: number; + DOM_INPUT_METHOD_SCRIPT: number; + DOM_INPUT_METHOD_VOICE: number; + DOM_INPUT_METHOD_UNKNOWN: number; + DOM_INPUT_METHOD_PASTE: number; + DOM_INPUT_METHOD_HANDWRITING: number; + DOM_INPUT_METHOD_OPTION: number; + DOM_INPUT_METHOD_MULTIMODAL: number; +} +declare var TextEvent: { + prototype: TextEvent; + new(): TextEvent; + DOM_INPUT_METHOD_KEYBOARD: number; + DOM_INPUT_METHOD_DROP: number; + DOM_INPUT_METHOD_IME: number; + DOM_INPUT_METHOD_SCRIPT: number; + DOM_INPUT_METHOD_VOICE: number; + DOM_INPUT_METHOD_UNKNOWN: number; + DOM_INPUT_METHOD_PASTE: number; + DOM_INPUT_METHOD_HANDWRITING: number; + DOM_INPUT_METHOD_OPTION: number; + DOM_INPUT_METHOD_MULTIMODAL: number; +} + +interface MSHTMLHRElementExtensions extends DOML2DeprecatedColorProperty { +} + +interface AbstractView { + styleMedia: StyleMedia; + document: Document; +} + +interface DocumentFragment extends Node, NodeSelector, MSEventAttachmentTarget, MSNodeExtensions { +} +declare var DocumentFragment: { + prototype: DocumentFragment; + new(): DocumentFragment; +} + +interface DOML2DeprecatedAlignmentStyle_HTMLFieldSetElement { + align: string; +} + +interface SVGPolylineElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGAnimatedPoints, SVGTests { +} +declare var SVGPolylineElement: { + prototype: SVGPolylineElement; + new(): SVGPolylineElement; +} + +interface DOML2DeprecatedWidthStyle { + width: number; +} + +interface DOML2DeprecatedAlignmentStyle_HTMLHeadingElement { + align: string; +} + +interface SVGAnimatedPathData { + pathSegList: SVGPathSegList; +} + +interface Position { + timestamp: Date; + coords: Coordinates; +} +declare var Position: { + prototype: Position; + new(): Position; +} + +interface BookmarkCollection { + length: number; + item(index: number): any; + [index: number]: any; +} +declare var BookmarkCollection: { + prototype: BookmarkCollection; + new(): BookmarkCollection; +} + +interface CSSPageRule extends CSSRule, StyleSheetPage { + selectorText: string; + style: CSSStyleDeclaration; +} +declare var CSSPageRule: { + prototype: CSSPageRule; + new(): CSSPageRule; +} + +interface WindowPerformance { + performance: any; +} + +interface HTMLBRElement extends HTMLElement, DOML2DeprecatedTextFlowControl_HTMLBRElement { +} +declare var HTMLBRElement: { + prototype: HTMLBRElement; + new(): HTMLBRElement; +} + +interface MSHTMLDivElementExtensions extends DOML2DeprecatedWordWrapSuppression_HTMLDivElement { +} + +interface DOML2DeprecatedBorderStyle_HTMLInputElement { + border: string; +} + +interface HTMLSpanElement extends HTMLElement, MSHTMLSpanElementExtensions, MSDataBindingExtensions { +} +declare var HTMLSpanElement: { + prototype: HTMLSpanElement; + new(): HTMLSpanElement; +} + +interface HTMLHRElementDOML2Deprecated { + noShade: bool; +} + +interface HTMLHeadElement extends HTMLElement { + profile: string; +} +declare var HTMLHeadElement: { + prototype: HTMLHeadElement; + new(): HTMLHeadElement; +} + +interface NodeFilterCallback { + (...args: any[]): any; +} + +interface HTMLHeadingElement extends HTMLElement, DOML2DeprecatedAlignmentStyle_HTMLHeadingElement, MSHTMLHeadingElementExtensions { +} +declare var HTMLHeadingElement: { + prototype: HTMLHeadingElement; + new(): HTMLHeadingElement; +} + +interface HTMLFormElement extends HTMLElement, MSHTMLFormElementExtensions, MSHTMLCollectionExtensions { + length: number; + target: string; + acceptCharset: string; + enctype: string; + elements: HTMLCollection; + action: string; + name: string; + method: string; + reset(): void; + item(name?: any, index?: any): any; + (name: any, index: any): any; + submit(): void; + namedItem(name: string): any; + [name: string]: any; + (name: string): any; +} +declare var HTMLFormElement: { + prototype: HTMLFormElement; + new(): HTMLFormElement; +} + +interface SVGZoomAndPan { + zoomAndPan: number; + SVG_ZOOMANDPAN_MAGNIFY: number; + SVG_ZOOMANDPAN_UNKNOWN: number; + SVG_ZOOMANDPAN_DISABLE: number; +} +declare var SVGZoomAndPan: { + prototype: SVGZoomAndPan; + new(): SVGZoomAndPan; + SVG_ZOOMANDPAN_MAGNIFY: number; + SVG_ZOOMANDPAN_UNKNOWN: number; + SVG_ZOOMANDPAN_DISABLE: number; +} + +interface MSEventExtensions { + cancelBubble: bool; + srcElement: Element; +} + +interface HTMLMediaElement extends HTMLElement { + initialTime: number; + played: TimeRanges; + currentSrc: string; + readyState: string; + autobuffer: bool; + loop: bool; + ended: bool; + buffered: TimeRanges; + error: MediaError; + seekable: TimeRanges; + autoplay: bool; + controls: bool; + volume: number; + src: string; + playbackRate: number; + duration: number; + muted: bool; + defaultPlaybackRate: number; + paused: bool; + seeking: bool; + currentTime: number; + preload: string; + networkState: number; + pause(): void; + play(): void; + load(): void; + canPlayType(type: string): string; + HAVE_METADATA: number; + HAVE_CURRENT_DATA: number; + HAVE_NOTHING: number; + NETWORK_NO_SOURCE: number; + HAVE_ENOUGH_DATA: number; + NETWORK_EMPTY: number; + NETWORK_LOADING: number; + NETWORK_IDLE: number; + HAVE_FUTURE_DATA: number; +} +declare var HTMLMediaElement: { + prototype: HTMLMediaElement; + new(): HTMLMediaElement; + HAVE_METADATA: number; + HAVE_CURRENT_DATA: number; + HAVE_NOTHING: number; + NETWORK_NO_SOURCE: number; + HAVE_ENOUGH_DATA: number; + NETWORK_EMPTY: number; + NETWORK_LOADING: number; + NETWORK_IDLE: number; + HAVE_FUTURE_DATA: number; +} + +interface ElementCSSInlineStyle extends MSElementCSSInlineStyleExtensions { + runtimeStyle: MSStyleCSSProperties; + currentStyle: MSCurrentStyleCSSProperties; +} + +interface DOMParser { + parseFromString(source: string, mimeType: string): Document; +} +declare var DOMParser: { + prototype: DOMParser; + new (): DOMParser; +} + +interface MSMimeTypesCollection { + length: number; +} +declare var MSMimeTypesCollection: { + prototype: MSMimeTypesCollection; + new(): MSMimeTypesCollection; +} + +interface StyleSheet { + disabled: bool; + ownerNode: Node; + parentStyleSheet: StyleSheet; + href: string; + media: MediaList; + type: string; + title: string; +} +declare var StyleSheet: { + prototype: StyleSheet; + new(): StyleSheet; +} + +interface DOML2DeprecatedBorderStyle_HTMLTableElement { + border: string; +} + +interface DOML2DeprecatedWidthStyle_HTMLAppletElement { + width: number; +} + +interface SVGTextPathElement extends SVGTextContentElement, SVGURIReference { + startOffset: SVGAnimatedLength; + method: SVGAnimatedEnumeration; + spacing: SVGAnimatedEnumeration; + TEXTPATH_SPACINGTYPE_EXACT: number; + TEXTPATH_METHODTYPE_STRETCH: number; + TEXTPATH_SPACINGTYPE_AUTO: number; + TEXTPATH_SPACINGTYPE_UNKNOWN: number; + TEXTPATH_METHODTYPE_UNKNOWN: number; + TEXTPATH_METHODTYPE_ALIGN: number; +} +declare var SVGTextPathElement: { + prototype: SVGTextPathElement; + new(): SVGTextPathElement; + TEXTPATH_SPACINGTYPE_EXACT: number; + TEXTPATH_METHODTYPE_STRETCH: number; + TEXTPATH_SPACINGTYPE_AUTO: number; + TEXTPATH_SPACINGTYPE_UNKNOWN: number; + TEXTPATH_METHODTYPE_UNKNOWN: number; + TEXTPATH_METHODTYPE_ALIGN: number; +} + +interface NodeList { + length: number; + item(index: number): Node; + [index: number]: Node; +} +declare var NodeList: { + prototype: NodeList; + new(): NodeList; +} + +interface HTMLDTElement extends HTMLElement, DOML2DeprecatedWordWrapSuppression_HTMLDTElement { +} +declare var HTMLDTElement: { + prototype: HTMLDTElement; + new(): HTMLDTElement; +} + +interface XMLSerializer { + serializeToString(target: Node): string; +} +declare var XMLSerializer: { + prototype: XMLSerializer; + new (): XMLSerializer; +} + +interface StyleSheetPage { + pseudoClass: string; + selector: string; +} + +interface DOML2DeprecatedWordWrapSuppression_HTMLDDElement { + noWrap: bool; +} + +interface MSHTMLTableRowElementExtensions { + height: any; +} + +interface SVGGradientElement extends SVGElement, SVGUnitTypes, SVGStylable, SVGURIReference { + spreadMethod: SVGAnimatedEnumeration; + gradientTransform: SVGAnimatedTransformList; + gradientUnits: SVGAnimatedEnumeration; + SVG_SPREADMETHOD_REFLECT: number; + SVG_SPREADMETHOD_PAD: number; + SVG_SPREADMETHOD_UNKNOWN: number; + SVG_SPREADMETHOD_REPEAT: number; +} +declare var SVGGradientElement: { + prototype: SVGGradientElement; + new(): SVGGradientElement; + SVG_SPREADMETHOD_REFLECT: number; + SVG_SPREADMETHOD_PAD: number; + SVG_SPREADMETHOD_UNKNOWN: number; + SVG_SPREADMETHOD_REPEAT: number; +} + +interface DOML2DeprecatedTextFlowControl_HTMLBRElement { + clear: string; +} + +interface MSHTMLParagraphElementExtensions extends DOML2DeprecatedTextFlowControl_HTMLBlockElement { +} + +interface NodeFilter { + acceptNode(n: Node): number; + SHOW_ENTITY_REFERENCE: number; + SHOW_NOTATION: number; + SHOW_ENTITY: number; + SHOW_DOCUMENT: number; + SHOW_PROCESSING_INSTRUCTION: number; + FILTER_REJECT: number; + SHOW_CDATA_SECTION: number; + FILTER_ACCEPT: number; + SHOW_ALL: number; + SHOW_DOCUMENT_TYPE: number; + SHOW_TEXT: number; + SHOW_ELEMENT: number; + SHOW_COMMENT: number; + FILTER_SKIP: number; + SHOW_ATTRIBUTE: number; + SHOW_DOCUMENT_FRAGMENT: number; +} +declare var NodeFilter: { + prototype: NodeFilter; + new(): NodeFilter; + SHOW_ENTITY_REFERENCE: number; + SHOW_NOTATION: number; + SHOW_ENTITY: number; + SHOW_DOCUMENT: number; + SHOW_PROCESSING_INSTRUCTION: number; + FILTER_REJECT: number; + SHOW_CDATA_SECTION: number; + FILTER_ACCEPT: number; + SHOW_ALL: number; + SHOW_DOCUMENT_TYPE: number; + SHOW_TEXT: number; + SHOW_ELEMENT: number; + SHOW_COMMENT: number; + FILTER_SKIP: number; + SHOW_ATTRIBUTE: number; + SHOW_DOCUMENT_FRAGMENT: number; +} + +interface MSBorderColorStyle_HTMLFrameElement { + borderColor: any; +} + +interface MSHTMLOListElementExtensions { +} + +interface DOML2DeprecatedWordWrapSuppression_HTMLDTElement { + noWrap: bool; +} + +interface ScreenView extends AbstractView { + outerWidth: number; + pageXOffset: number; + innerWidth: number; + pageYOffset: number; + screenY: number; + outerHeight: number; + screen: Screen; + innerHeight: number; + screenX: number; + scroll(x?: number, y?: number): void; + scrollBy(x?: number, y?: number): void; + scrollTo(x?: number, y?: number): void; +} + +interface DOML2DeprecatedMarginStyle_HTMLObjectElement { + vspace: number; + hspace: number; +} + +interface DOML2DeprecatedMarginStyle_HTMLInputElement { + vspace: number; + hspace: number; +} + +interface MSHTMLTableSectionElementExtensions extends DOML2DeprecatedBackgroundColorStyle { + moveRow(indexFrom?: number, indexTo?: number): Object; +} + +interface HTMLFieldSetElement extends HTMLElement, MSHTMLFieldSetElementExtensions { + form: HTMLFormElement; +} +declare var HTMLFieldSetElement: { + prototype: HTMLFieldSetElement; + new(): HTMLFieldSetElement; +} + +interface MediaError { + code: number; + MEDIA_ERR_ABORTED: number; + MEDIA_ERR_NETWORK: number; + MEDIA_ERR_SRC_NOT_SUPPORTED: number; + MEDIA_ERR_DECODE: number; +} +declare var MediaError: { + prototype: MediaError; + new(): MediaError; + MEDIA_ERR_ABORTED: number; + MEDIA_ERR_NETWORK: number; + MEDIA_ERR_SRC_NOT_SUPPORTED: number; + MEDIA_ERR_DECODE: number; +} + +interface SVGNumberList { + numberOfItems: number; + replaceItem(newItem: SVGNumber, index: number): SVGNumber; + getItem(index: number): SVGNumber; + clear(): void; + appendItem(newItem: SVGNumber): SVGNumber; + initialize(newItem: SVGNumber): SVGNumber; + removeItem(index: number): SVGNumber; + insertItemBefore(newItem: SVGNumber, index: number): SVGNumber; +} +declare var SVGNumberList: { + prototype: SVGNumberList; + new(): SVGNumberList; +} + +interface HTMLBGSoundElement extends HTMLElement { + balance: any; + volume: any; + src: string; + loop: number; +} +declare var HTMLBGSoundElement: { + prototype: HTMLBGSoundElement; + new(): HTMLBGSoundElement; +} + +interface HTMLElement extends Element, MSHTMLElementRangeExtensions, ElementCSSInlineStyle, MSEventAttachmentTarget, MSHTMLElementExtensions, MSNodeExtensions { + ondragend: (ev: DragEvent) => any; + onkeydown: (ev: KeyboardEvent) => any; + ondragover: (ev: DragEvent) => any; + onkeyup: (ev: KeyboardEvent) => any; + offsetTop: number; + onreset: (ev: Event) => any; + onmouseup: (ev: MouseEvent) => any; + ondragstart: (ev: DragEvent) => any; + ondrag: (ev: DragEvent) => any; + innerHTML: string; + onmouseover: (ev: MouseEvent) => any; + ondragleave: (ev: DragEvent) => any; + lang: string; + onpause: (ev: Event) => any; + className: string; + onseeked: (ev: Event) => any; + onmousedown: (ev: MouseEvent) => any; + title: string; + onclick: (ev: MouseEvent) => any; + onwaiting: (ev: Event) => any; + outerHTML: string; + offsetLeft: number; + ondurationchange: (ev: Event) => any; + offsetHeight: number; + dir: string; + onblur: (ev: FocusEvent) => any; + onemptied: (ev: Event) => any; + onseeking: (ev: Event) => any; + oncanplay: (ev: Event) => any; + onstalled: (ev: Event) => any; + onmousemove: (ev: MouseEvent) => any; + style: MSStyleCSSProperties; + isContentEditable: bool; + onratechange: (ev: Event) => any; + onloadstart: (ev: Event) => any; + ondragenter: (ev: DragEvent) => any; + contentEditable: string; + onsubmit: (ev: Event) => any; + tabIndex: number; + onprogress: (ev: any) => any; + ondblclick: (ev: MouseEvent) => any; + oncontextmenu: (ev: MouseEvent) => any; + onchange: (ev: Event) => any; + onloadedmetadata: (ev: Event) => any; + onerror: (ev: Event) => any; + onplay: (ev: Event) => any; + id: string; + onplaying: (ev: Event) => any; + oncanplaythrough: (ev: Event) => any; + onabort: (ev: UIEvent) => any; + onreadystatechange: (ev: Event) => any; + onkeypress: (ev: KeyboardEvent) => any; + offsetParent: Element; + onloadeddata: (ev: Event) => any; + disabled: bool; + onsuspend: (ev: Event) => any; + accessKey: string; + onfocus: (ev: FocusEvent) => any; + ontimeupdate: (ev: Event) => any; + onselect: (ev: UIEvent) => any; + ondrop: (ev: DragEvent) => any; + offsetWidth: number; + onmouseout: (ev: MouseEvent) => any; + onended: (ev: Event) => any; + onscroll: (ev: UIEvent) => any; + onmousewheel: (ev: MouseWheelEvent) => any; + onvolumechange: (ev: Event) => any; + onload: (ev: Event) => any; + oninput: (ev: Event) => any; + click(): void; + getElementsByClassName(classNames: string): NodeList; + scrollIntoView(top?: bool): void; + focus(): void; + blur(): void; + insertAdjacentHTML(where: string, html: string): void; +} +declare var HTMLElement: { + prototype: HTMLElement; + new(): HTMLElement; +} + +interface Comment extends CharacterData, MSCommentExtensions { +} +declare var Comment: { + prototype: Comment; + new(): Comment; +} + +interface CanvasPattern { +} +declare var CanvasPattern: { + prototype: CanvasPattern; + new(): CanvasPattern; +} + +interface HTMLHRElement extends HTMLElement, DOML2DeprecatedWidthStyle_HTMLHRElement, MSHTMLHRElementExtensions, HTMLHRElementDOML2Deprecated, DOML2DeprecatedAlignmentStyle_HTMLHRElement, DOML2DeprecatedSizeProperty { +} +declare var HTMLHRElement: { + prototype: HTMLHRElement; + new(): HTMLHRElement; +} + +interface MSHTMLFrameSetElementExtensions { + name: string; + frameBorder: string; + border: string; + frameSpacing: any; +} + +interface DOML2DeprecatedTextFlowControl_HTMLBlockElement { + clear: string; +} + +interface PositionOptions { + enableHighAccuracy?: bool; + timeout?: number; + maximumAge?: number; +} + +interface HTMLObjectElement extends HTMLElement, MSHTMLObjectElementExtensions, GetSVGDocument, DOML2DeprecatedMarginStyle_HTMLObjectElement, MSDataBindingExtensions, MSDataBindingRecordSetExtensions, DOML2DeprecatedAlignmentStyle_HTMLObjectElement, DOML2DeprecatedBorderStyle_HTMLObjectElement { + width: string; + codeType: string; + archive: string; + standby: string; + name: string; + useMap: string; + form: HTMLFormElement; + data: string; + height: string; + contentDocument: Document; + codeBase: string; + declare: bool; + type: string; + code: string; +} +declare var HTMLObjectElement: { + prototype: HTMLObjectElement; + new(): HTMLObjectElement; +} + +interface MSHTMLMenuElementExtensions { +} + +interface DocumentView { + defaultView: AbstractView; + elementFromPoint(x: number, y: number): Element; +} + +interface StorageEvent extends Event { + oldValue: any; + newValue: any; + url: string; + storageArea: Storage; + key: string; + initStorageEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, keyArg: string, oldValueArg: any, newValueArg: any, urlArg: string, storageAreaArg: Storage): void; +} +declare var StorageEvent: { + prototype: StorageEvent; + new(): StorageEvent; +} + +interface HTMLEmbedElement extends HTMLElement, GetSVGDocument, MSHTMLEmbedElementExtensions { + width: string; + src: string; + name: string; + height: string; +} +declare var HTMLEmbedElement: { + prototype: HTMLEmbedElement; + new(): HTMLEmbedElement; +} + +interface CharacterData extends Node { + length: number; + data: string; + deleteData(offset: number, count: number): void; + replaceData(offset: number, count: number, arg: string): void; + appendData(arg: string): void; + insertData(offset: number, arg: string): void; + substringData(offset: number, count: number): string; +} +declare var CharacterData: { + prototype: CharacterData; + new(): CharacterData; +} + +interface DOML2DeprecatedAlignmentStyle_HTMLTableSectionElement { + align: string; +} + +interface HTMLOptGroupElement extends HTMLElement, MSDataBindingExtensions, MSHTMLOptGroupElementExtensions { + label: string; +} +declare var HTMLOptGroupElement: { + prototype: HTMLOptGroupElement; + new(): HTMLOptGroupElement; +} + +interface HTMLIsIndexElement extends HTMLElement, MSHTMLIsIndexElementExtensions { + form: HTMLFormElement; + prompt: string; +} +declare var HTMLIsIndexElement: { + prototype: HTMLIsIndexElement; + new(): HTMLIsIndexElement; +} + +interface SVGPathSegLinetoRel extends SVGPathSeg { + y: number; + x: number; +} +declare var SVGPathSegLinetoRel: { + prototype: SVGPathSegLinetoRel; + new(): SVGPathSegLinetoRel; +} + +interface MSHTMLDocumentSelection { + selection: MSSelection; +} + +interface DOMException { + code: number; + message: string; + toString(): string; + HIERARCHY_REQUEST_ERR: number; + NO_MODIFICATION_ALLOWED_ERR: number; + INVALID_MODIFICATION_ERR: number; + NAMESPACE_ERR: number; + INVALID_CHARACTER_ERR: number; + TYPE_MISMATCH_ERR: number; + ABORT_ERR: number; + INVALID_STATE_ERR: number; + SECURITY_ERR: number; + NETWORK_ERR: number; + WRONG_DOCUMENT_ERR: number; + QUOTA_EXCEEDED_ERR: number; + INDEX_SIZE_ERR: number; + DOMSTRING_SIZE_ERR: number; + SYNTAX_ERR: number; + SERIALIZE_ERR: number; + VALIDATION_ERR: number; + NOT_FOUND_ERR: number; + URL_MISMATCH_ERR: number; + PARSE_ERR: number; + NO_DATA_ALLOWED_ERR: number; + NOT_SUPPORTED_ERR: number; + INVALID_ACCESS_ERR: number; + INUSE_ATTRIBUTE_ERR: number; +} +declare var DOMException: { + prototype: DOMException; + new(): DOMException; + HIERARCHY_REQUEST_ERR: number; + NO_MODIFICATION_ALLOWED_ERR: number; + INVALID_MODIFICATION_ERR: number; + NAMESPACE_ERR: number; + INVALID_CHARACTER_ERR: number; + TYPE_MISMATCH_ERR: number; + ABORT_ERR: number; + INVALID_STATE_ERR: number; + SECURITY_ERR: number; + NETWORK_ERR: number; + WRONG_DOCUMENT_ERR: number; + QUOTA_EXCEEDED_ERR: number; + INDEX_SIZE_ERR: number; + DOMSTRING_SIZE_ERR: number; + SYNTAX_ERR: number; + SERIALIZE_ERR: number; + VALIDATION_ERR: number; + NOT_FOUND_ERR: number; + URL_MISMATCH_ERR: number; + PARSE_ERR: number; + NO_DATA_ALLOWED_ERR: number; + NOT_SUPPORTED_ERR: number; + INVALID_ACCESS_ERR: number; + INUSE_ATTRIBUTE_ERR: number; +} + +interface MSCompatibleInfoCollection { + length: number; + item(index: number): MSCompatibleInfo; +} +declare var MSCompatibleInfoCollection: { + prototype: MSCompatibleInfoCollection; + new(): MSCompatibleInfoCollection; +} + +interface MSHTMLIsIndexElementExtensions { + action: string; +} + +interface SVGAnimatedBoolean { + animVal: bool; + baseVal: bool; +} +declare var SVGAnimatedBoolean: { + prototype: SVGAnimatedBoolean; + new(): SVGAnimatedBoolean; +} + +interface SVGSwitchElement extends SVGElement, SVGStylable, SVGTransformable, SVGLangSpace, SVGTests { +} +declare var SVGSwitchElement: { + prototype: SVGSwitchElement; + new(): SVGSwitchElement; +} + +interface MSHTMLIFrameElementExtensions extends DOML2DeprecatedMarginStyle_MSHTMLIFrameElementExtensions, DOML2DeprecatedBorderStyle_MSHTMLIFrameElementExtensions { + onload: (ev: Event) => any; + frameSpacing: any; + noResize: bool; +} + +interface SVGPreserveAspectRatio { + align: number; + meetOrSlice: number; + SVG_PRESERVEASPECTRATIO_NONE: number; + SVG_PRESERVEASPECTRATIO_XMINYMID: number; + SVG_PRESERVEASPECTRATIO_XMAXYMIN: number; + SVG_PRESERVEASPECTRATIO_XMINYMAX: number; + SVG_PRESERVEASPECTRATIO_XMAXYMAX: number; + SVG_MEETORSLICE_UNKNOWN: number; + SVG_PRESERVEASPECTRATIO_XMAXYMID: number; + SVG_PRESERVEASPECTRATIO_XMIDYMAX: number; + SVG_PRESERVEASPECTRATIO_XMINYMIN: number; + SVG_MEETORSLICE_MEET: number; + SVG_PRESERVEASPECTRATIO_XMIDYMID: number; + SVG_PRESERVEASPECTRATIO_XMIDYMIN: number; + SVG_MEETORSLICE_SLICE: number; + SVG_PRESERVEASPECTRATIO_UNKNOWN: number; +} +declare var SVGPreserveAspectRatio: { + prototype: SVGPreserveAspectRatio; + new(): SVGPreserveAspectRatio; + SVG_PRESERVEASPECTRATIO_NONE: number; + SVG_PRESERVEASPECTRATIO_XMINYMID: number; + SVG_PRESERVEASPECTRATIO_XMAXYMIN: number; + SVG_PRESERVEASPECTRATIO_XMINYMAX: number; + SVG_PRESERVEASPECTRATIO_XMAXYMAX: number; + SVG_MEETORSLICE_UNKNOWN: number; + SVG_PRESERVEASPECTRATIO_XMAXYMID: number; + SVG_PRESERVEASPECTRATIO_XMIDYMAX: number; + SVG_PRESERVEASPECTRATIO_XMINYMIN: number; + SVG_MEETORSLICE_MEET: number; + SVG_PRESERVEASPECTRATIO_XMIDYMID: number; + SVG_PRESERVEASPECTRATIO_XMIDYMIN: number; + SVG_MEETORSLICE_SLICE: number; + SVG_PRESERVEASPECTRATIO_UNKNOWN: number; +} + +interface Attr extends Node, MSAttrExtensions { + specified: bool; + ownerElement: Element; + value: string; + name: string; +} +declare var Attr: { + prototype: Attr; + new(): Attr; +} + +interface MSBorderColorStyle_HTMLTableRowElement { + borderColor: any; +} + +interface DOML2DeprecatedAlignmentStyle_HTMLTableCaptionElement { + align: string; +} + +interface PerformanceNavigation { + redirectCount: number; + type: number; + toJSON(): any; + TYPE_RELOAD: number; + TYPE_RESERVED: number; + TYPE_BACK_FORWARD: number; + TYPE_NAVIGATE: number; +} +declare var PerformanceNavigation: { + prototype: PerformanceNavigation; + new(): PerformanceNavigation; + TYPE_RELOAD: number; + TYPE_RESERVED: number; + TYPE_BACK_FORWARD: number; + TYPE_NAVIGATE: number; +} + +interface HTMLBodyElementDOML2Deprecated { + link: any; + aLink: any; + text: any; + vLink: any; +} + +interface SVGStopElement extends SVGElement, SVGStylable { + offset: SVGAnimatedNumber; +} +declare var SVGStopElement: { + prototype: SVGStopElement; + new(): SVGStopElement; +} + +interface PositionCallback { + (position: Position): void; +} + +interface SVGSymbolElement extends SVGElement, SVGStylable, SVGLangSpace, SVGFitToViewBox { +} +declare var SVGSymbolElement: { + prototype: SVGSymbolElement; + new(): SVGSymbolElement; +} + +interface SVGElementInstanceList { + length: number; + item(index: number): SVGElementInstance; +} +declare var SVGElementInstanceList: { + prototype: SVGElementInstanceList; + new(): SVGElementInstanceList; +} + +interface MSDataBindingRecordSetExtensions { + recordset: Object; + namedRecordset(dataMember: string, hierarchy?: any): Object; +} + +interface CSSRuleList { + length: number; + item(index: number): CSSRule; + [index: number]: CSSRule; +} +declare var CSSRuleList: { + prototype: CSSRuleList; + new(): CSSRuleList; +} + +interface MSHTMLTableColElementExtensions { +} + +interface LinkStyle { + sheet: StyleSheet; +} + +interface MSHTMLMarqueeElementExtensions { +} + +interface HTMLVideoElement extends HTMLMediaElement { + width: number; + videoWidth: number; + videoHeight: number; + height: number; + poster: string; +} +declare var HTMLVideoElement: { + prototype: HTMLVideoElement; + new(): HTMLVideoElement; +} + +interface MSXMLHttpRequestExtensions { + responseBody: any; + timeout: number; + ontimeout: (ev: Event) => any; +} + +interface ClientRectList { + length: number; + item(index: number): ClientRect; + [index: number]: ClientRect; +} +declare var ClientRectList: { + prototype: ClientRectList; + new(): ClientRectList; +} + +interface DOML2DeprecatedAlignmentStyle_HTMLTableCellElement { + align: string; +} + +interface SVGMaskElement extends SVGElement, SVGUnitTypes, SVGStylable, SVGLangSpace, SVGTests { + y: SVGAnimatedLength; + width: SVGAnimatedLength; + maskUnits: SVGAnimatedEnumeration; + maskContentUnits: SVGAnimatedEnumeration; + x: SVGAnimatedLength; + height: SVGAnimatedLength; +} +declare var SVGMaskElement: { + prototype: SVGMaskElement; + new(): SVGMaskElement; +} + +declare var Audio: { new (src?: string): HTMLAudioElement; }; +declare var Option: { new (text?: string, value?: string, defaultSelected?: bool, selected?: bool): HTMLOptionElement; }; +declare var Image: { new (width?: number, height?: number): HTMLImageElement; }; + +declare var ondragend: (ev: DragEvent) => any; +declare var onkeydown: (ev: KeyboardEvent) => any; +declare var ondragover: (ev: DragEvent) => any; +declare var onkeyup: (ev: KeyboardEvent) => any; +declare var onreset: (ev: Event) => any; +declare var onmouseup: (ev: MouseEvent) => any; +declare var ondragstart: (ev: DragEvent) => any; +declare var ondrag: (ev: DragEvent) => any; +declare var onmouseover: (ev: MouseEvent) => any; +declare var ondragleave: (ev: DragEvent) => any; +declare var history: History; +declare var name: string; +declare var onafterprint: (ev: Event) => any; +declare var onpause: (ev: Event) => any; +declare var onbeforeprint: (ev: Event) => any; +declare var top: Window; +declare var onmousedown: (ev: MouseEvent) => any; +declare var onseeked: (ev: Event) => any; +declare var opener: Window; +declare var onclick: (ev: MouseEvent) => any; +declare var onwaiting: (ev: Event) => any; +declare var ononline: (ev: Event) => any; +declare var ondurationchange: (ev: Event) => any; +declare var frames: Window; +declare var onblur: (ev: FocusEvent) => any; +declare var onemptied: (ev: Event) => any; +declare var onseeking: (ev: Event) => any; +declare var oncanplay: (ev: Event) => any; +declare var onstalled: (ev: Event) => any; +declare var onmousemove: (ev: MouseEvent) => any; +declare var onoffline: (ev: Event) => any; +declare var length: number; +declare var onbeforeunload: (ev: BeforeUnloadEvent) => any; +declare var onratechange: (ev: Event) => any; +declare var onstorage: (ev: StorageEvent) => any; +declare var onloadstart: (ev: Event) => any; +declare var ondragenter: (ev: DragEvent) => any; +declare var onsubmit: (ev: Event) => any; +declare var self: Window; +declare var onprogress: (ev: any) => any; +declare var ondblclick: (ev: MouseEvent) => any; +declare var oncontextmenu: (ev: MouseEvent) => any; +declare var onchange: (ev: Event) => any; +declare var onloadedmetadata: (ev: Event) => any; +declare var onplay: (ev: Event) => any; +declare var onerror: ErrorFunction; +declare var onplaying: (ev: Event) => any; +declare var parent: Window; +declare var location: Location; +declare var oncanplaythrough: (ev: Event) => any; +declare var onabort: (ev: UIEvent) => any; +declare var onreadystatechange: (ev: Event) => any; +declare var onkeypress: (ev: KeyboardEvent) => any; +declare var frameElement: Element; +declare var onloadeddata: (ev: Event) => any; +declare var onsuspend: (ev: Event) => any; +declare var window: Window; +declare var onfocus: (ev: FocusEvent) => any; +declare var onmessage: (ev: MessageEvent) => any; +declare var ontimeupdate: (ev: Event) => any; +declare var onresize: (ev: UIEvent) => any; +declare var navigator: Navigator; +declare var onselect: (ev: UIEvent) => any; +declare var ondrop: (ev: DragEvent) => any; +declare var onmouseout: (ev: MouseEvent) => any; +declare var onended: (ev: Event) => any; +declare var onhashchange: (ev: Event) => any; +declare var onunload: (ev: Event) => any; +declare var onscroll: (ev: UIEvent) => any; +declare var onmousewheel: (ev: MouseWheelEvent) => any; +declare var onload: (ev: Event) => any; +declare var onvolumechange: (ev: Event) => any; +declare var oninput: (ev: Event) => any; +declare function alert(message?: string): void; +declare function focus(): void; +declare function print(): void; +declare function prompt(message?: string, defaul?: string): string; +declare function toString(): string; +declare function open(url?: string, target?: string, features?: string, replace?: bool): Window; +declare function close(): void; +declare function confirm(message?: string): bool; +declare function postMessage(message: any, targetOrigin: string, ports?: any): void; +declare function showModalDialog(url?: string, argument?: any, options?: any): any; +declare function blur(): void; +declare function getSelection(): Selection; +declare function getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration; +declare function attachEvent(event: string, listener: EventListener): bool; +declare function detachEvent(event: string, listener: EventListener): void; +declare var status: string; +declare var onmouseleave: (ev: MouseEvent) => any; +declare var screenLeft: number; +declare var offscreenBuffering: any; +declare var maxConnectionsPerServer: number; +declare var onmouseenter: (ev: MouseEvent) => any; +declare var clipboardData: DataTransfer; +declare var defaultStatus: string; +declare var clientInformation: Navigator; +declare var closed: bool; +declare var onhelp: (ev: Event) => any; +declare var external: BrowserPublic; +declare var event: MSEventObj; +declare var onfocusout: (ev: FocusEvent) => any; +declare var screenTop: number; +declare var onfocusin: (ev: FocusEvent) => any; +declare function showModelessDialog(url?: string, argument?: any, options?: any): Window; +declare function navigate(url: string): void; +declare function resizeBy(x?: number, y?: number): void; +declare function item(index: any): any; +declare function resizeTo(x?: number, y?: number): void; +declare function createPopup(arguments?: any): MSPopupWindow; +declare function toStaticHTML(html: string): string; +declare function execScript(code: string, language?: string): any; +declare function msWriteProfilerMark(profilerMarkName: string): void; +declare function moveTo(x?: number, y?: number): void; +declare function moveBy(x?: number, y?: number): void; +declare function showHelp(url: string, helpArg?: any, features?: string): void; +declare var performance: any; +declare var outerWidth: number; +declare var pageXOffset: number; +declare var innerWidth: number; +declare var pageYOffset: number; +declare var screenY: number; +declare var outerHeight: number; +declare var screen: Screen; +declare var innerHeight: number; +declare var screenX: number; +declare function scroll(x?: number, y?: number): void; +declare function scrollBy(x?: number, y?: number): void; +declare function scrollTo(x?: number, y?: number): void; +declare var styleMedia: StyleMedia; +declare var document: Document; +declare function removeEventListener(type: string, listener: EventListener, useCapture?: bool): void; +declare function addEventListener(type: string, listener: EventListener, useCapture?: bool): void; +declare function dispatchEvent(evt: Event): bool; +declare var localStorage: Storage; +declare var sessionStorage: Storage; +declare function clearTimeout(handle: number): void; +declare function setTimeout(expression: any, msec?: number, language?: any): number; +declare function clearInterval(handle: number): void; +declare function setInterval(expression: any, msec?: number, language?: any): number; + + +///////////////////////////// +/// IE10 DOM APIs +///////////////////////////// + +interface HTMLBodyElement { + onpopstate: (ev: PopStateEvent) => any; +} + +interface MSGestureEvent extends UIEvent { + offsetY: number; + translationY: number; + velocityExpansion: number; + velocityY: number; + velocityAngular: number; + translationX: number; + velocityX: number; + hwTimestamp: number; + offsetX: number; + screenX: number; + rotation: number; + expansion: number; + clientY: number; + screenY: number; + scale: number; + gestureObject: any; + clientX: number; + initGestureEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, offsetXArg: number, offsetYArg: number, translationXArg: number, translationYArg: number, scaleArg: number, expansionArg: number, rotationArg: number, velocityXArg: number, velocityYArg: number, velocityExpansionArg: number, velocityAngularArg: number, hwTimestampArg: number): void; + MSGESTURE_FLAG_BEGIN: number; + MSGESTURE_FLAG_END: number; + MSGESTURE_FLAG_CANCEL: number; + MSGESTURE_FLAG_INERTIA: number; + MSGESTURE_FLAG_NONE: number; +} +declare var MSGestureEvent: { + prototype: MSGestureEvent; + new(): MSGestureEvent; + MSGESTURE_FLAG_BEGIN: number; + MSGESTURE_FLAG_END: number; + MSGESTURE_FLAG_CANCEL: number; + MSGESTURE_FLAG_INERTIA: number; + MSGESTURE_FLAG_NONE: number; +} + +interface HTMLAnchorElement { + text: string; +} + +interface HTMLInputElement { + validationMessage: string; + files: FileList; + max: string; + formTarget: string; + willValidate: bool; + step: string; + autofocus: bool; + required: bool; + formEnctype: string; + valueAsNumber: number; + placeholder: string; + formMethod: string; + list: HTMLElement; + autocomplete: string; + min: string; + formAction: string; + pattern: string; + validity: ValidityState; + formNoValidate: string; + multiple: bool; + checkValidity(): bool; + stepDown(n?: number): void; + stepUp(n?: number): void; + setCustomValidity(error: string): void; +} + +interface ErrorEvent extends Event { + colno: number; + filename: string; + lineno: number; + message: string; + initErrorEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, messageArg: string, filenameArg: string, linenoArg: number): void; +} +declare var ErrorEvent: { + prototype: ErrorEvent; + new(): ErrorEvent; +} + +interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGStylable, SVGLangSpace, SVGURIReference { + y: SVGAnimatedLength; + width: SVGAnimatedLength; + filterResX: SVGAnimatedInteger; + filterUnits: SVGAnimatedEnumeration; + primitiveUnits: SVGAnimatedEnumeration; + x: SVGAnimatedLength; + height: SVGAnimatedLength; + filterResY: SVGAnimatedInteger; + setFilterRes(filterResX: number, filterResY: number): void; +} +declare var SVGFilterElement: { + prototype: SVGFilterElement; + new(): SVGFilterElement; +} + +interface TrackEvent extends Event { + track: any; +} +declare var TrackEvent: { + prototype: TrackEvent; + new(): TrackEvent; +} + +interface SVGFEMergeNodeElement extends SVGElement { + in1: SVGAnimatedString; +} +declare var SVGFEMergeNodeElement: { + prototype: SVGFEMergeNodeElement; + new(): SVGFEMergeNodeElement; +} + +interface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { +} +declare var SVGFEFloodElement: { + prototype: SVGFEFloodElement; + new(): SVGFEFloodElement; +} + +interface MSElementExtensions { + msRegionOverflow: string; + onmspointerdown: (ev: any) => any; + onmsgotpointercapture: (ev: any) => any; + onmsgesturedoubletap: (ev: any) => any; + onmspointerhover: (ev: any) => any; + onmsgesturehold: (ev: any) => any; + onmspointermove: (ev: any) => any; + onmsgesturechange: (ev: any) => any; + onmsgesturestart: (ev: any) => any; + onmspointercancel: (ev: any) => any; + onmsgestureend: (ev: any) => any; + onmsgesturetap: (ev: any) => any; + onmspointerout: (ev: any) => any; + onmsinertiastart: (ev: any) => any; + onmslostpointercapture: (ev: any) => any; + onmspointerover: (ev: any) => any; + msContentZoomFactor: number; + onmspointerup: (ev: any) => any; + msGetRegionContent(): MSRangeCollection; + msReleasePointerCapture(pointerId: number): void; + msSetPointerCapture(pointerId: number): void; +} +declare var MSElementExtensions: { + prototype: MSElementExtensions; + new(): MSElementExtensions; +} + +interface MSCSSScrollTranslationProperties { + msScrollTranslation: string; +} + +interface MSGesture { + target: Element; + addPointer(pointerId: number): void; + stop(): void; +} +declare var MSGesture: { + prototype: MSGesture; + new (): MSGesture; +} + +interface TextTrackCue extends EventTarget { + onenter: (ev: Event) => any; + track: TextTrack; + endTime: number; + text: string; + pauseOnExit: bool; + id: string; + startTime: number; + onexit: (ev: Event) => any; + getCueAsHTML(): DocumentFragment; +} +declare var TextTrackCue: { + prototype: TextTrackCue; + new(): TextTrackCue; +} + +interface MSHTMLDocumentViewExtensions { + msCSSOMElementFloatMetrics: bool; + msElementsFromPoint(x: number, y: number): NodeList; + msElementsFromRect(left: number, top: number, width: number, height: number): NodeList; +} +declare var MSHTMLDocumentViewExtensions: { + prototype: MSHTMLDocumentViewExtensions; + new(): MSHTMLDocumentViewExtensions; +} + +interface MSStreamReader extends MSBaseReader { + error: DOMError; + readAsArrayBuffer(stream: MSStream, size?: number): void; + readAsBlob(stream: MSStream, size?: number): void; + readAsDataURL(stream: MSStream, size?: number): void; + readAsText(stream: MSStream, encoding?: string, size?: number): void; +} +declare var MSStreamReader: { + prototype: MSStreamReader; + new (): MSStreamReader; +} + +interface CSSFlexibleBoxProperties { + msFlex: string; + msFlexDirection: string; + msFlexNegative: string; + msFlexPack: string; + msFlexWrap: string; + msFlexItemAlign: string; + msFlexOrder: string; + msFlexPositive: string; + msFlexAlign: string; + msFlexFlow: string; + msFlexPreferredSize: string; + msFlexLinePack: string; +} + +interface DOMTokenList { + length: number; + contains(token: string): bool; + remove(token: string): void; + toggle(token: string): bool; + add(token: string): void; + item(index: number): string; + [index: number]: string; + toString(): string; +} +declare var DOMTokenList: { + prototype: DOMTokenList; + new(): DOMTokenList; +} + +interface EventException { + name: string; +} + +interface SVGFEFuncAElement extends SVGComponentTransferFunctionElement { +} +declare var SVGFEFuncAElement: { + prototype: SVGFEFuncAElement; + new(): SVGFEFuncAElement; +} + +interface Performance { + now(): number; +} + +interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + in1: SVGAnimatedString; +} +declare var SVGFETileElement: { + prototype: SVGFETileElement; + new(): SVGFETileElement; +} + +interface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + in2: SVGAnimatedString; + mode: SVGAnimatedEnumeration; + in1: SVGAnimatedString; + SVG_FEBLEND_MODE_DARKEN: number; + SVG_FEBLEND_MODE_UNKNOWN: number; + SVG_FEBLEND_MODE_MULTIPLY: number; + SVG_FEBLEND_MODE_NORMAL: number; + SVG_FEBLEND_MODE_SCREEN: number; + SVG_FEBLEND_MODE_LIGHTEN: number; +} +declare var SVGFEBlendElement: { + prototype: SVGFEBlendElement; + new(): SVGFEBlendElement; + SVG_FEBLEND_MODE_DARKEN: number; + SVG_FEBLEND_MODE_UNKNOWN: number; + SVG_FEBLEND_MODE_MULTIPLY: number; + SVG_FEBLEND_MODE_NORMAL: number; + SVG_FEBLEND_MODE_SCREEN: number; + SVG_FEBLEND_MODE_LIGHTEN: number; +} + +interface WindowTimers extends WindowTimersExtension { +} +declare var WindowTimers: { + prototype: WindowTimers; + new(): WindowTimers; +} + +interface CSSStyleDeclaration extends CSS2DTransformsProperties, CSSTransitionsProperties, CSSFontsProperties, MSCSSHighContrastProperties, CSSGridProperties, CSSAnimationsProperties, MSCSSContentZoomProperties, MSCSSScrollTranslationProperties, MSCSSTouchManipulationProperties, CSSFlexibleBoxProperties, MSCSSPositionedFloatsProperties, MSCSSRegionProperties, MSCSSSelectionBoundaryProperties, CSSMultiColumnProperties, CSSTextProperties, CSS3DTransformsProperties { +} + +interface MessageChannel { + port2: MessagePort; + port1: MessagePort; +} +declare var MessageChannel: { + prototype: MessageChannel; + new (): MessageChannel; +} + +interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { +} +declare var SVGFEMergeElement: { + prototype: SVGFEMergeElement; + new(): SVGFEMergeElement; +} + +interface Navigator extends MSFileSaver { +} + +interface TransitionEvent extends Event { + propertyName: string; + elapsedTime: number; + initTransitionEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, propertyNameArg: string, elapsedTimeArg: number): void; +} +declare var TransitionEvent: { + prototype: TransitionEvent; + new(): TransitionEvent; +} + +interface MediaQueryList { + matches: bool; + media: string; + addListener(listener: MediaQueryListListener): void; + removeListener(listener: MediaQueryListListener): void; +} +declare var MediaQueryList: { + prototype: MediaQueryList; + new(): MediaQueryList; +} + +interface DOMError { + name: string; + toString(): string; +} +declare var DOMError: { + prototype: DOMError; + new(): DOMError; +} + +interface SVGFEPointLightElement extends SVGElement { + y: SVGAnimatedNumber; + x: SVGAnimatedNumber; + z: SVGAnimatedNumber; +} +declare var SVGFEPointLightElement: { + prototype: SVGFEPointLightElement; + new(): SVGFEPointLightElement; +} + +interface CSSFontsProperties { + msFontFeatureSettings: string; + fontFeatureSettings: string; +} + +interface CloseEvent extends Event { + wasClean: bool; + reason: string; + code: number; + initCloseEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, wasCleanArg: bool, codeArg: number, reasonArg: string): void; +} +declare var CloseEvent: { + prototype: CloseEvent; + new(): CloseEvent; +} + +interface WebSocket extends EventTarget { + protocol: string; + readyState: number; + bufferedAmount: number; + onopen: (ev: Event) => any; + extensions: string; + onmessage: (ev: any) => any; + onclose: (ev: CloseEvent) => any; + onerror: (ev: ErrorEvent) => any; + binaryType: string; + url: string; + close(code?: number, reason?: string): void; + send(data: any): void; + OPEN: number; + CLOSING: number; + CONNECTING: number; + CLOSED: number; +} +declare var WebSocket: { + prototype: WebSocket; + new (url: string): WebSocket; + new (url: string, prototcol: string): WebSocket; + new (url: string, prototcol: string[]): WebSocket; + OPEN: number; + CLOSING: number; + CONNECTING: number; + CLOSED: number; +} + +interface ProgressEvent extends Event { + loaded: number; + lengthComputable: bool; + total: number; + initProgressEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, lengthComputableArg: bool, loadedArg: number, totalArg: number): void; +} +declare var ProgressEvent: { + prototype: ProgressEvent; + new(): ProgressEvent; +} + +interface HTMLCanvasElement { + msToBlob(): Blob; +} + +interface IDBObjectStore { + indexNames: DOMStringList; + name: string; + transaction: IDBTransaction; + keyPath: string; + count(key?: any): IDBRequest; + add(value: any, key?: any): IDBRequest; + clear(): IDBRequest; + createIndex(name: string, keyPath: string, optionalParameters?: any): IDBIndex; + put(value: any, key?: any): IDBRequest; + openCursor(range?: any, direction?: string): IDBRequest; + deleteIndex(indexName: string): void; + index(name: string): IDBIndex; + get(key: any): IDBRequest; + delet(key: any): IDBRequest; +} +declare var IDBObjectStore: { + prototype: IDBObjectStore; + new(): IDBObjectStore; +} + +interface ObjectURLOptions { + oneTimeOnly?: bool; +} + +interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + stdDeviationX: SVGAnimatedNumber; + in1: SVGAnimatedString; + stdDeviationY: SVGAnimatedNumber; + setStdDeviation(stdDeviationX: number, stdDeviationY: number): void; +} +declare var SVGFEGaussianBlurElement: { + prototype: SVGFEGaussianBlurElement; + new(): SVGFEGaussianBlurElement; +} + +interface MSHTMLDocumentExtensions { + onmspointerdown: (ev: any) => any; + onmspointercancel: (ev: any) => any; + onmsgesturedoubletap: (ev: any) => any; + onmsgesturetap: (ev: any) => any; + onmsgestureend: (ev: any) => any; + onmspointerout: (ev: any) => any; + onmsmanipulationstatechanged: (ev: any) => any; + onmsinertiastart: (ev: any) => any; + onmspointerhover: (ev: any) => any; + onmscontentzoom: (ev: any) => any; + onmsgesturehold: (ev: any) => any; + onmspointermove: (ev: any) => any; + onmspointerover: (ev: any) => any; + onmsgesturechange: (ev: any) => any; + onmsgesturestart: (ev: any) => any; + onmspointerup: (ev: any) => any; +} +declare var MSHTMLDocumentExtensions: { + prototype: MSHTMLDocumentExtensions; + new(): MSHTMLDocumentExtensions; +} + +interface MSCSSSelectionBoundaryProperties { + msUserSelect: string; +} + +interface SVGFilterPrimitiveStandardAttributes extends SVGStylable { + y: SVGAnimatedLength; + width: SVGAnimatedLength; + x: SVGAnimatedLength; + height: SVGAnimatedLength; + result: SVGAnimatedString; +} + +interface IDBVersionChangeEvent extends Event { + newVersion: number; + oldVersion: number; +} +declare var IDBVersionChangeEvent: { + prototype: IDBVersionChangeEvent; + new(): IDBVersionChangeEvent; +} + +interface IDBIndex { + unique: bool; + name: string; + keyPath: string; + objectStore: IDBObjectStore; + count(key?: any): IDBRequest; + getKey(key: any): IDBRequest; + openKeyCursor(range?: IDBKeyRange, direction?: string): IDBRequest; + get(key: any): IDBRequest; + openCursor(range?: IDBKeyRange, direction?: string): IDBRequest; +} +declare var IDBIndex: { + prototype: IDBIndex; + new(): IDBIndex; +} + +interface FileList { + length: number; + item(index: number): File; + [index: number]: File; +} +declare var FileList: { + prototype: FileList; + new(): FileList; +} + +interface IDBCursor { + source: any; + direction: string; + key: any; + primaryKey: any; + advance(count: number): void; + delet(): IDBRequest; + continu(key?: any): void; + update(value: any): IDBRequest; +} +declare var IDBCursor: { + prototype: IDBCursor; + new(): IDBCursor; +} + +interface CSSAnimationsProperties { + animationFillMode: string; + msAnimationDirection: string; + msAnimationDelay: string; + msAnimationFillMode: string; + animationIterationCount: string; + msAnimationPlayState: string; + msAnimationIterationCount: string; + animationDelay: string; + animationTimingFunction: string; + msAnimation: string; + animation: string; + animationDirection: string; + animationDuration: string; + animationName: string; + animationPlayState: string; + msAnimationTimingFunction: string; + msAnimationName: string; + msAnimationDuration: string; +} + +interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + kernelUnitLengthY: SVGAnimatedNumber; + surfaceScale: SVGAnimatedNumber; + specularExponent: SVGAnimatedNumber; + in1: SVGAnimatedString; + kernelUnitLengthX: SVGAnimatedNumber; + specularConstant: SVGAnimatedNumber; +} +declare var SVGFESpecularLightingElement: { + prototype: SVGFESpecularLightingElement; + new(): SVGFESpecularLightingElement; +} + +interface File extends Blob { + lastModifiedDate: any; + name: string; +} +declare var File: { + prototype: File; + new(): File; +} + +interface URL { + revokeObjectURL(url: string): void; + createObjectURL(object: any, options?: ObjectURLOptions): string; +} +declare var URL: URL; + +interface RangeException { + name: string; +} + +interface IDBCursorWithValue extends IDBCursor { + value: any; +} +declare var IDBCursorWithValue: { + prototype: IDBCursorWithValue; + new(): IDBCursorWithValue; +} + +interface HTMLTextAreaElement { + validationMessage: string; + autofocus: bool; + validity: ValidityState; + required: bool; + maxLength: number; + willValidate: bool; + placeholder: string; + checkValidity(): bool; + setCustomValidity(error: string): void; +} + +interface XMLHttpRequestEventTarget extends EventTarget { + onprogress: (ev: ProgressEvent) => any; + onerror: (ev: ErrorEvent) => any; + onload: (ev: any) => any; + ontimeout: (ev: any) => any; + onabort: (ev: any) => any; + onloadstart: (ev: any) => any; + onloadend: (ev: ProgressEvent) => any; +} +declare var XMLHttpRequestEventTarget: { + prototype: XMLHttpRequestEventTarget; + new(): XMLHttpRequestEventTarget; +} + +interface IDBEnvironment { + msIndexedDB: IDBFactory; + indexedDB: IDBFactory; +} + +interface AudioTrackList extends EventTarget { + length: number; + onchange: (ev: any) => any; + onaddtrack: (ev: TrackEvent) => any; + getTrackById(id: string): AudioTrack; + item(index: number): AudioTrack; + [index: number]: AudioTrack; +} +declare var AudioTrackList: { + prototype: AudioTrackList; + new(): AudioTrackList; +} + +interface MSBaseReader extends EventTarget { + onprogress: (ev: ProgressEvent) => any; + readyState: number; + onabort: (ev: any) => any; + onloadend: (ev: ProgressEvent) => any; + onerror: (ev: ErrorEvent) => any; + onload: (ev: any) => any; + onloadstart: (ev: any) => any; + result: any; + abort(): void; + LOADING: number; + EMPTY: number; + DONE: number; +} + +interface History { + state: any; + replaceState(statedata: any, title: string, url?: string): void; + pushState(statedata: any, title: string, url?: string): void; +} + +interface MSProtocol { + protocol: string; +} +declare var MSProtocol: { + prototype: MSProtocol; + new(): MSProtocol; +} + +interface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + operator: SVGAnimatedEnumeration; + radiusX: SVGAnimatedNumber; + radiusY: SVGAnimatedNumber; + in1: SVGAnimatedString; + SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; + SVG_MORPHOLOGY_OPERATOR_ERODE: number; + SVG_MORPHOLOGY_OPERATOR_DILATE: number; +} +declare var SVGFEMorphologyElement: { + prototype: SVGFEMorphologyElement; + new(): SVGFEMorphologyElement; + SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number; + SVG_MORPHOLOGY_OPERATOR_ERODE: number; + SVG_MORPHOLOGY_OPERATOR_DILATE: number; +} + +interface HTMLSelectElement { + validationMessage: string; + autofocus: bool; + validity: ValidityState; + required: bool; + willValidate: bool; + checkValidity(): bool; + setCustomValidity(error: string): void; +} + +interface CSSTransitionsProperties { + transition: string; + transitionDelay: string; + transitionDuration: string; + msTransitionTimingFunction: string; + msTransition: string; + msTransitionDuration: string; + transitionTimingFunction: string; + msTransitionDelay: string; + transitionProperty: string; + msTransitionProperty: string; +} + +interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { +} +declare var SVGFEFuncRElement: { + prototype: SVGFEFuncRElement; + new(): SVGFEFuncRElement; +} + +interface CSSRule { + KEYFRAMES_RULE: number; + KEYFRAME_RULE: number; + VIEWPORT_RULE: number; +} +//declare var CSSRule: { +// KEYFRAMES_RULE: number; +// KEYFRAME_RULE: number; +// VIEWPORT_RULE: number; +//} + +interface WindowTimersExtension { + msSetImmediate(expression: any, ...args: any[]): number; + clearImmediate(handle: number): void; + msClearImmediate(handle: number): void; + setImmediate(expression: any, ...args: any[]): number; +} + +interface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + in2: SVGAnimatedString; + xChannelSelector: SVGAnimatedEnumeration; + yChannelSelector: SVGAnimatedEnumeration; + scale: SVGAnimatedNumber; + in1: SVGAnimatedString; + SVG_CHANNEL_B: number; + SVG_CHANNEL_R: number; + SVG_CHANNEL_G: number; + SVG_CHANNEL_UNKNOWN: number; + SVG_CHANNEL_A: number; +} +declare var SVGFEDisplacementMapElement: { + prototype: SVGFEDisplacementMapElement; + new(): SVGFEDisplacementMapElement; + SVG_CHANNEL_B: number; + SVG_CHANNEL_R: number; + SVG_CHANNEL_G: number; + SVG_CHANNEL_UNKNOWN: number; + SVG_CHANNEL_A: number; +} + +interface MSCSSContentZoomProperties { + msContentZoomLimit: string; + msContentZooming: string; + msContentZoomSnapType: string; + msContentZoomLimitMax: any; + msContentZoomSnapPoints: string; + msContentZoomSnap: string; + msContentZoomLimitMin: any; + msContentZoomChaining: string; +} + +interface AnimationEvent extends Event { + animationName: string; + elapsedTime: number; + initAnimationEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, animationNameArg: string, elapsedTimeArg: number): void; +} +declare var AnimationEvent: { + prototype: AnimationEvent; + new(): AnimationEvent; +} + +interface SVGComponentTransferFunctionElement extends SVGElement { + tableValues: SVGAnimatedNumberList; + slope: SVGAnimatedNumber; + type: SVGAnimatedEnumeration; + exponent: SVGAnimatedNumber; + amplitude: SVGAnimatedNumber; + intercept: SVGAnimatedNumber; + offset: SVGAnimatedNumber; + SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; + SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; + SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY: number; + SVG_FECOMPONENTTRANSFER_TYPE_GAMMA: number; + SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE: number; + SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; +} +declare var SVGComponentTransferFunctionElement: { + prototype: SVGComponentTransferFunctionElement; + new(): SVGComponentTransferFunctionElement; + SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number; + SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number; + SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY: number; + SVG_FECOMPONENTTRANSFER_TYPE_GAMMA: number; + SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE: number; + SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number; +} + +interface MSRangeCollection { + length: number; + item(index: number): Range; + [index: number]: Range; +} +declare var MSRangeCollection: { + prototype: MSRangeCollection; + new(): MSRangeCollection; +} + +interface MSHTMLElementExtensions { + onmscontentzoom: (ev: any) => any; + onmsmanipulationstatechanged: (ev: any) => any; +} +declare var MSHTMLElementExtensions: { + prototype: MSHTMLElementExtensions; + new(): MSHTMLElementExtensions; +} + +interface MSCSSPositionedFloatsProperties { + msWrapMargin: any; + msWrapFlow: string; +} + +interface SVGException { + name: string; +} + +interface SVGFEDistantLightElement extends SVGElement { + azimuth: SVGAnimatedNumber; + elevation: SVGAnimatedNumber; +} +declare var SVGFEDistantLightElement: { + prototype: SVGFEDistantLightElement; + new(): SVGFEDistantLightElement; +} + +interface MSCSSRegionProperties { + msFlowFrom: string; + msFlowInto: string; + msWrapThrough: string; +} + +interface SVGFEFuncBElement extends SVGComponentTransferFunctionElement { +} +declare var SVGFEFuncBElement: { + prototype: SVGFEFuncBElement; + new(): SVGFEFuncBElement; +} + +interface IDBKeyRange { + upper: any; + upperOpen: bool; + lower: any; + lowerOpen: bool; + bound(lower: any, upper: any, lowerOpen?: bool, upperOpen?: bool): IDBKeyRange; + only(value: any): IDBKeyRange; + lowerBound(bound: any, open?: bool): IDBKeyRange; + upperBound(bound: any, open?: bool): IDBKeyRange; +} +declare var IDBKeyRange: { + prototype: IDBKeyRange; + new(): IDBKeyRange; +} + +interface WindowConsole { + console: Console; +} + +interface SVG1_1Properties { + floodOpacity: string; + floodColor: string; + filter: string; + lightingColor: string; + enableBackground: string; + colorInterpolationFilters: string; +} +declare var SVG1_1Properties: { + prototype: SVG1_1Properties; + new(): SVG1_1Properties; +} + +interface IDBTransaction extends EventTarget { + oncomplete: (ev: Event) => any; + db: IDBDatabase; + mode: string; + error: DOMError; + onerror: (ev: ErrorEvent) => any; + onabort: (ev: any) => any; + abort(): void; + objectStore(name: string): IDBObjectStore; +} +declare var IDBTransaction: { + prototype: IDBTransaction; + new(): IDBTransaction; +} + +interface MSWindowExtensions { + onmspointerdown: (ev: any) => any; + onmspointercancel: (ev: any) => any; + onmsgesturedoubletap: (ev: any) => any; + onmsgestureend: (ev: any) => any; + onmsgesturetap: (ev: any) => any; + onmspointerout: (ev: any) => any; + onmspointerhover: (ev: any) => any; + onmsinertiastart: (ev: any) => any; + onmspointermove: (ev: any) => any; + onmsgesturehold: (ev: any) => any; + onmspointerover: (ev: any) => any; + onmsgesturechange: (ev: any) => any; + onmsgesturestart: (ev: any) => any; + onmspointerup: (ev: any) => any; + msIsStaticHTML(html: string): bool; +} +declare var MSWindowExtensions: { + prototype: MSWindowExtensions; + new(): MSWindowExtensions; +} + +interface AudioTrack { + kind: string; + language: string; + id: string; + label: string; + enabled: bool; +} +declare var AudioTrack: { + prototype: AudioTrack; + new(): AudioTrack; +} + +interface SVGFEConvolveMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + orderY: SVGAnimatedInteger; + kernelUnitLengthY: SVGAnimatedNumber; + orderX: SVGAnimatedInteger; + preserveAlpha: SVGAnimatedBoolean; + kernelMatrix: SVGAnimatedNumberList; + edgeMode: SVGAnimatedEnumeration; + kernelUnitLengthX: SVGAnimatedNumber; + bias: SVGAnimatedNumber; + targetX: SVGAnimatedInteger; + targetY: SVGAnimatedInteger; + divisor: SVGAnimatedNumber; + in1: SVGAnimatedString; + SVG_EDGEMODE_WRAP: number; + SVG_EDGEMODE_DUPLICATE: number; + SVG_EDGEMODE_UNKNOWN: number; + SVG_EDGEMODE_NONE: number; +} +declare var SVGFEConvolveMatrixElement: { + prototype: SVGFEConvolveMatrixElement; + new(): SVGFEConvolveMatrixElement; + SVG_EDGEMODE_WRAP: number; + SVG_EDGEMODE_DUPLICATE: number; + SVG_EDGEMODE_UNKNOWN: number; + SVG_EDGEMODE_NONE: number; +} + +interface TextTrackCueList { + length: number; + item(index: number): TextTrackCue; + [index: number]: TextTrackCue; + getCueById(id: string): TextTrackCue; +} +declare var TextTrackCueList: { + prototype: TextTrackCueList; + new(): TextTrackCueList; +} + +interface CSSKeyframesRule extends CSSRule { + name: string; + cssRules: CSSRuleList; + findRule(rule: string): CSSKeyframeRule; + deleteRule(rule: string): void; + appendRule(rule: string): void; +} +declare var CSSKeyframesRule: { + prototype: CSSKeyframesRule; + new(): CSSKeyframesRule; +} + +interface MSCSSTouchManipulationProperties { + msScrollSnapPointsY: string; + msOverflowStyle: string; + msScrollLimitXMax: any; + msScrollSnapType: string; + msScrollSnapPointsX: string; + msScrollLimitYMax: any; + msScrollSnapY: string; + msScrollLimitXMin: any; + msScrollLimitYMin: any; + msScrollChaining: string; + msTouchAction: string; + msScrollSnapX: string; + msScrollLimit: string; + msScrollRails: string; + msTouchSelect: string; +} + +interface Window extends WindowAnimationTiming, WindowBase64, IDBEnvironment, WindowConsole { + onpopstate: (ev: PopStateEvent) => any; + applicationCache: ApplicationCache; + matchMedia(mediaQuery: string): MediaQueryList; + msMatchMedia(mediaQuery: string): MediaQueryList; +} + +interface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + baseFrequencyX: SVGAnimatedNumber; + numOctaves: SVGAnimatedInteger; + type: SVGAnimatedEnumeration; + baseFrequencyY: SVGAnimatedNumber; + stitchTiles: SVGAnimatedEnumeration; + seed: SVGAnimatedNumber; + SVG_STITCHTYPE_UNKNOWN: number; + SVG_STITCHTYPE_NOSTITCH: number; + SVG_TURBULENCE_TYPE_UNKNOWN: number; + SVG_TURBULENCE_TYPE_TURBULENCE: number; + SVG_TURBULENCE_TYPE_FRACTALNOISE: number; + SVG_STITCHTYPE_STITCH: number; +} +declare var SVGFETurbulenceElement: { + prototype: SVGFETurbulenceElement; + new(): SVGFETurbulenceElement; + SVG_STITCHTYPE_UNKNOWN: number; + SVG_STITCHTYPE_NOSTITCH: number; + SVG_TURBULENCE_TYPE_UNKNOWN: number; + SVG_TURBULENCE_TYPE_TURBULENCE: number; + SVG_TURBULENCE_TYPE_FRACTALNOISE: number; + SVG_STITCHTYPE_STITCH: number; +} + +interface TextTrackList { + length: number; + item(index: number): TextTrack; + [index: number]: TextTrack; +} +declare var TextTrackList: { + prototype: TextTrackList; + new(): TextTrackList; +} + +interface WindowAnimationTiming { + animationStartTime: number; + msAnimationStartTime: number; + msCancelRequestAnimationFrame(handle: number): void; + cancelAnimationFrame(handle: number): void; + requestAnimationFrame(callback: FrameRequestCallback): number; + msRequestAnimationFrame(callback: FrameRequestCallback): number; +} + +interface SVGFEFuncGElement extends SVGComponentTransferFunctionElement { +} +declare var SVGFEFuncGElement: { + prototype: SVGFEFuncGElement; + new(): SVGFEFuncGElement; +} + +interface SVGFEColorMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + in1: SVGAnimatedString; + type: SVGAnimatedEnumeration; + values: SVGAnimatedNumberList; + SVG_FECOLORMATRIX_TYPE_SATURATE: number; + SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; + SVG_FECOLORMATRIX_TYPE_MATRIX: number; + SVG_FECOLORMATRIX_TYPE_HUEROTATE: number; + SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA: number; +} +declare var SVGFEColorMatrixElement: { + prototype: SVGFEColorMatrixElement; + new(): SVGFEColorMatrixElement; + SVG_FECOLORMATRIX_TYPE_SATURATE: number; + SVG_FECOLORMATRIX_TYPE_UNKNOWN: number; + SVG_FECOLORMATRIX_TYPE_MATRIX: number; + SVG_FECOLORMATRIX_TYPE_HUEROTATE: number; + SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA: number; +} + +interface Console { + info(): void; + info(message: any, ...optionalParams: any[]): void; + profile(reportName?: string): bool; + assert(): void; + assert(test: bool): void; + assert(test: bool, message: any, ...optionalParams: any[]): void; + msIsIndependentlyComposed(element: Element): bool; + clear(): bool; + dir(): bool; + dir(value: any, ...optionalParams: any[]): bool; + warn(): void; + warn(message: any, ...optionalParams: any[]): void; + error(): void; + error(message: any, ...optionalParams: any[]): void; + log(): void; + log(message: any, ...optionalParams: any[]): void; + profileEnd(): bool; +} +declare var Console: { + prototype: Console; + new(): Console; +} + +interface SVGFESpotLightElement extends SVGElement { + pointsAtY: SVGAnimatedNumber; + y: SVGAnimatedNumber; + limitingConeAngle: SVGAnimatedNumber; + specularExponent: SVGAnimatedNumber; + x: SVGAnimatedNumber; + pointsAtZ: SVGAnimatedNumber; + z: SVGAnimatedNumber; + pointsAtX: SVGAnimatedNumber; +} +declare var SVGFESpotLightElement: { + prototype: SVGFESpotLightElement; + new(): SVGFESpotLightElement; +} + +interface DocumentVisibility { + msHidden: bool; + msVisibilityState: string; + visibilityState: string; + hidden: bool; +} + +interface WindowBase64 { + btoa(rawString: string): string; + atob(encodedString: string): string; +} + +interface IDBDatabase extends EventTarget { + version: string; + name: string; + objectStoreNames: DOMStringList; + onerror: (ev: ErrorEvent) => any; + onabort: (ev: any) => any; + createObjectStore(name: string, optionalParameters?: any): IDBObjectStore; + close(): void; + transaction(storeNames: any, mode?: string): IDBTransaction; + deleteObjectStore(name: string): void; +} +declare var IDBDatabase: { + prototype: IDBDatabase; + new(): IDBDatabase; +} + +interface MSProtocolsCollection { +} +declare var MSProtocolsCollection: { + prototype: MSProtocolsCollection; + new(): MSProtocolsCollection; +} + +interface DOMStringList { + length: number; + contains(str: string): bool; + item(index: number): string; + [index: number]: string; +} +declare var DOMStringList: { + prototype: DOMStringList; + new(): DOMStringList; +} + +interface CSSMultiColumnProperties { + breakAfter: string; + columnSpan: string; + columnRule: string; + columnFill: string; + columnRuleStyle: string; + breakBefore: string; + columnCount: any; + breakInside: string; + columnWidth: any; + columns: string; + columnRuleColor: any; + columnGap: any; + columnRuleWidth: any; +} + +interface IDBOpenDBRequest extends IDBRequest { + onupgradeneeded: (ev: IDBVersionChangeEvent) => any; + onblocked: (ev: Event) => any; +} +declare var IDBOpenDBRequest: { + prototype: IDBOpenDBRequest; + new(): IDBOpenDBRequest; +} + +interface HTMLButtonElement { + validationMessage: string; + formTarget: string; + willValidate: bool; + formAction: string; + autofocus: bool; + validity: ValidityState; + formNoValidate: string; + formEnctype: string; + formMethod: string; + checkValidity(): bool; + setCustomValidity(error: string): void; +} + +interface HTMLProgressElement extends HTMLElement { + value: number; + max: number; + position: number; + form: HTMLFormElement; +} +declare var HTMLProgressElement: { + prototype: HTMLProgressElement; + new(): HTMLProgressElement; +} + +interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + dy: SVGAnimatedNumber; + in1: SVGAnimatedString; + dx: SVGAnimatedNumber; +} +declare var SVGFEOffsetElement: { + prototype: SVGFEOffsetElement; + new(): SVGFEOffsetElement; +} + +interface HTMLFormElement { + autocomplete: string; + noValidate: bool; + checkValidity(): bool; +} + +interface MSUnsafeFunctionCallback { + (): any; +} + +interface Document extends DocumentVisibility { +} + +interface MessageEvent extends Event { + ports: any; +} + +interface HTMLScriptElement { + async: bool; +} + +interface HTMLMediaElement extends MSHTMLMediaElementExtensions { + textTracks: TextTrackList; + audioTracks: AudioTrackList; +} + +interface TextTrack extends EventTarget { + language: string; + mode: number; + readyState: string; + activeCues: TextTrackCueList; + cues: TextTrackCueList; + oncuechange: (ev: Event) => any; + kind: string; + onload: (ev: any) => any; + onerror: (ev: ErrorEvent) => any; + label: string; + ERROR: number; + SHOWING: number; + LOADING: number; + LOADED: number; + NONE: number; + HIDDEN: number; + DISABLED: number; +} +declare var TextTrack: { + prototype: TextTrack; + new(): TextTrack; + ERROR: number; + SHOWING: number; + LOADING: number; + LOADED: number; + NONE: number; + HIDDEN: number; + DISABLED: number; +} + +interface MediaQueryListListener { + (mql: MediaQueryList): void; +} + +interface IDBRequest extends EventTarget { + source: any; + onsuccess: (ev: Event) => any; + error: DOMError; + transaction: IDBTransaction; + onerror: (ev: ErrorEvent) => any; + readyState: string; + result: any; +} +declare var IDBRequest: { + prototype: IDBRequest; + new(): IDBRequest; +} + +interface MessagePort extends EventTarget { + onmessage: (ev: any) => any; + close(): void; + postMessage(message: any, ports?: any): void; + start(): void; +} +declare var MessagePort: { + prototype: MessagePort; + new(): MessagePort; +} + +interface FileReader extends MSBaseReader { + error: DOMError; + readAsArrayBuffer(blob: Blob): void; + readAsDataURL(blob: Blob): void; + readAsText(blob: Blob, encoding?: string): void; +} +declare var FileReader: { + prototype: FileReader; + new (): FileReader; +} + +interface Blob { + type: string; + size: number; + msDetachStream(): any; + slice(start?: number, end?: number, contentType?: string): Blob; + close(): void; + msClose(): void; +} +interface BlobPropertyBag { + /** Corresponds to the 'type' property of the Blob object */ + type?: string; + /** Either 'transparent' or 'native' */ + endings?: string; +} +declare var Blob: { + prototype: Blob; + new (blobParts?: any[], options?: BlobPropertyBag): Blob; +} + +interface ApplicationCache extends EventTarget { + status: number; + ondownloading: (ev: Event) => any; + onprogress: (ev: ProgressEvent) => any; + onupdateready: (ev: Event) => any; + oncached: (ev: Event) => any; + onobsolete: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; + onchecking: (ev: Event) => any; + onnoupdate: (ev: Event) => any; + swapCache(): void; + abort(): void; + update(): void; + CHECKING: number; + UNCACHED: number; + UPDATEREADY: number; + DOWNLOADING: number; + IDLE: number; + OBSOLETE: number; +} +declare var ApplicationCache: { + prototype: ApplicationCache; + new(): ApplicationCache; + CHECKING: number; + UNCACHED: number; + UPDATEREADY: number; + DOWNLOADING: number; + IDLE: number; + OBSOLETE: number; +} + +interface MSHTMLVideoElementExtensions { + msIsStereo3D: bool; + msStereo3DPackingMode: string; + onMSVideoOptimalLayoutChanged: (ev: any) => any; + onMSVideoFrameStepCompleted: (ev: any) => any; + msStereo3DRenderMode: string; + msIsLayoutOptimalForPlayback: bool; + msHorizontalMirror: bool; + onMSVideoFormatChanged: (ev: any) => any; + msZoom: bool; + msInsertVideoEffect(activatableClassId: string, effectRequired: bool, config?: any): void; + msSetVideoRectangle(left: number, top: number, right: number, bottom: number): void; + msFrameStep(forward: bool): void; +} + +interface FrameRequestCallback { + (time: number): void; +} + +interface CSS3DTransformsProperties { + perspective: string; + msBackfaceVisibility: string; + perspectiveOrigin: string; + transformStyle: string; + backfaceVisibility: string; + msPerspectiveOrigin: string; + msTransformStyle: string; + msPerspective: string; +} + +interface XMLHttpRequest { + withCredentials: bool; +} + +interface PopStateEvent extends Event { + state: any; + initPopStateEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, stateArg: any): void; +} +declare var PopStateEvent: { + prototype: PopStateEvent; + new(): PopStateEvent; +} + +interface CSSKeyframeRule extends CSSRule { + keyText: string; + style: CSSStyleDeclaration; +} +declare var CSSKeyframeRule: { + prototype: CSSKeyframeRule; + new(): CSSKeyframeRule; +} + +interface CSSGridProperties { + msGridRows: string; + msGridColumnSpan: any; + msGridRow: any; + msGridRowSpan: any; + msGridColumns: string; + msGridColumnAlign: string; + msGridRowAlign: string; + msGridColumn: any; +} + +interface MSFileSaver { + msSaveBlob(blob: any, defaultName?: string): bool; + msSaveOrOpenBlob(blob: any, defaultName?: string): bool; +} + +interface MSStream { + type: string; + msDetachStream(): any; + msClose(): void; +} +declare var MSStream: { + prototype: MSStream; + new(): MSStream; +} + +interface MediaError extends MSMediaErrorExtensions { +} + +interface HTMLFieldSetElement { + validationMessage: string; + validity: ValidityState; + willValidate: bool; + checkValidity(): bool; + setCustomValidity(error: string): void; +} + +interface MSBlobBuilder { + append(data: any, endings?: string): void; + getBlob(contentType?: string): Blob; +} +declare var MSBlobBuilder: { + prototype: MSBlobBuilder; + new (): MSBlobBuilder; +} + +interface MSRangeExtensions { + createContextualFragment(fragment: string): DocumentFragment; +} + +interface HTMLElement { + oncuechange: (ev: Event) => any; + spellcheck: bool; + classList: DOMTokenList; + draggable: bool; +} + +interface DataTransfer { + types: DOMStringList; + files: FileList; +} + +interface DOMSettableTokenList extends DOMTokenList { + value: string; +} +declare var DOMSettableTokenList: { + prototype: DOMSettableTokenList; + new(): DOMSettableTokenList; +} + +interface IDBFactory { + open(name: string, version?: number): IDBOpenDBRequest; + cmp(first: any, second: any): number; + deleteDatabase(name: string): IDBOpenDBRequest; +} +declare var IDBFactory: { + prototype: IDBFactory; + new(): IDBFactory; +} + +interface Range extends MSRangeExtensions { +} + +interface HTMLObjectElement { + validationMessage: string; + validity: ValidityState; + willValidate: bool; + checkValidity(): bool; + setCustomValidity(error: string): void; +} + +interface MSPointerEvent extends MouseEvent { + width: number; + rotation: number; + pressure: number; + pointerType: number; + isPrimary: bool; + tiltY: number; + height: number; + intermediatePoints: any; + currentPoint: any; + tiltX: number; + hwTimestamp: number; + pointerId: number; + initPointerEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: bool, altKeyArg: bool, shiftKeyArg: bool, metaKeyArg: bool, buttonArg: number, relatedTargetArg: EventTarget, offsetXArg: number, offsetYArg: number, widthArg: number, heightArg: number, pressure: number, rotation: number, tiltX: number, tiltY: number, pointerIdArg: number, pointerType: number, hwTimestampArg: number, isPrimary: bool): void; + getCurrentPoint(element: Element): void; + getIntermediatePoints(element: Element): void; + MSPOINTER_TYPE_PEN: number; + MSPOINTER_TYPE_MOUSE: number; + MSPOINTER_TYPE_TOUCH: number; +} +declare var MSPointerEvent: { + prototype: MSPointerEvent; + new(): MSPointerEvent; + MSPOINTER_TYPE_PEN: number; + MSPOINTER_TYPE_MOUSE: number; + MSPOINTER_TYPE_TOUCH: number; +} + +interface CSSTextProperties { + textShadow: string; + msHyphenateLimitLines: any; + msHyphens: string; + msHyphenateLimitChars: string; + msHyphenateLimitZone: any; +} + +interface CSS2DTransformsProperties { + transform: string; + transformOrigin: string; +} + +interface DOMException { + name: string; + INVALID_NODE_TYPE_ERR: number; + DATA_CLONE_ERR: number; + TIMEOUT_ERR: number; +} +//declare var DOMException: { +// INVALID_NODE_TYPE_ERR: number; +// DATA_CLONE_ERR: number; +// TIMEOUT_ERR: number; +//} + +interface MSCSSHighContrastProperties { + msHighContrastAdjust: string; +} + +interface MSManipulationEvent extends UIEvent { + lastState: number; + currentState: number; + initMSManipulationEvent(typeArg: string, canBubbleArg: bool, cancelableArg: bool, viewArg: AbstractView, detailArg: number, lastState: number, currentState: number): void; + MS_MANIPULATION_STATE_STOPPED: number; + MS_MANIPULATION_STATE_ACTIVE: number; + MS_MANIPULATION_STATE_INERTIA: number; +} +declare var MSManipulationEvent: { + prototype: MSManipulationEvent; + new(): MSManipulationEvent; + MS_MANIPULATION_STATE_STOPPED: number; + MS_MANIPULATION_STATE_ACTIVE: number; + MS_MANIPULATION_STATE_INERTIA: number; +} + +interface FormData { + append(name: any, value: any, blobName?: string): void; +} +declare var FormData: { + prototype: FormData; + new (): FormData; + new (form: HTMLFormElement): FormData; +} + +interface MSHTMLImageElementExtensions { + msPlayToPrimary: bool; + msPlayToDisabled: bool; + msPlayToSource: any; +} +declare var MSHTMLImageElementExtensions: { + prototype: MSHTMLImageElementExtensions; + new(): MSHTMLImageElementExtensions; +} + +interface MSHTMLMediaElementExtensions { + msAudioCategory: string; + msRealTime: bool; + msPlayToPrimary: bool; + msPlayToDisabled: bool; + msPlayToSource: any; + msAudioDeviceType: string; + msClearEffects(): void; + msSetMediaProtectionManager(mediaProtectionManager?: any): void; + msInsertAudioEffect(activatableClassId: string, effectRequired: bool, config?: any): void; +} + +interface SVGFEImageElement extends SVGElement, SVGLangSpace, SVGFilterPrimitiveStandardAttributes, SVGURIReference { + preserveAspectRatio: SVGAnimatedPreserveAspectRatio; +} +declare var SVGFEImageElement: { + prototype: SVGFEImageElement; + new(): SVGFEImageElement; +} + +interface HTMLDataListElement extends HTMLElement { + options: HTMLCollection; +} +declare var HTMLDataListElement: { + prototype: HTMLDataListElement; + new(): HTMLDataListElement; +} + +interface AbstractWorker extends EventTarget { + onerror: (ev: ErrorEvent) => any; +} + +interface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + operator: SVGAnimatedEnumeration; + in2: SVGAnimatedString; + k2: SVGAnimatedNumber; + k1: SVGAnimatedNumber; + k3: SVGAnimatedNumber; + in1: SVGAnimatedString; + k4: SVGAnimatedNumber; + SVG_FECOMPOSITE_OPERATOR_OUT: number; + SVG_FECOMPOSITE_OPERATOR_OVER: number; + SVG_FECOMPOSITE_OPERATOR_XOR: number; + SVG_FECOMPOSITE_OPERATOR_ARITHMETIC: number; + SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; + SVG_FECOMPOSITE_OPERATOR_IN: number; + SVG_FECOMPOSITE_OPERATOR_ATOP: number; +} +declare var SVGFECompositeElement: { + prototype: SVGFECompositeElement; + new(): SVGFECompositeElement; + SVG_FECOMPOSITE_OPERATOR_OUT: number; + SVG_FECOMPOSITE_OPERATOR_OVER: number; + SVG_FECOMPOSITE_OPERATOR_XOR: number; + SVG_FECOMPOSITE_OPERATOR_ARITHMETIC: number; + SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number; + SVG_FECOMPOSITE_OPERATOR_IN: number; + SVG_FECOMPOSITE_OPERATOR_ATOP: number; +} + +interface ValidityState { + customError: bool; + valueMissing: bool; + stepMismatch: bool; + rangeUnderflow: bool; + rangeOverflow: bool; + typeMismatch: bool; + patternMismatch: bool; + tooLong: bool; + valid: bool; +} +declare var ValidityState: { + prototype: ValidityState; + new(): ValidityState; +} + +interface HTMLVideoElement extends MSHTMLVideoElementExtensions { +} + +interface HTMLTrackElement extends HTMLElement { + kind: string; + src: string; + srclang: string; + track: TextTrack; + label: string; + defaul: bool; +} +declare var HTMLTrackElement: { + prototype: HTMLTrackElement; + new(): HTMLTrackElement; +} + +interface MSApp { + createFileFromStorageFile(storageFile: any): File; + createBlobFromRandomAccessStream(type: string, seeker: any): Blob; + createStreamFromInputStream(type: string, inputStream: any): MSStream; + terminateApp(exceptionObject: any): void; + createDataPackage(object: any): any; + execUnsafeLocalFunction(unsafeFunction: MSUnsafeFunctionCallback): any; + getHtmlPrintDocumentSource(htmlDoc: any, printTemplate?: string): any; + addPublicLocalApplicationUri(uri: string): void; + createDataPackageFromSelection(): any; +} +declare var MSApp: MSApp; + +interface MSXMLHttpRequestExtensions { + response: any; + onprogress: (ev: ProgressEvent) => any; + onabort: (ev: any) => any; + responseType: string; + onloadend: (ev: ProgressEvent) => any; + upload: XMLHttpRequestEventTarget; + onerror: (ev: ErrorEvent) => any; + onloadstart: (ev: any) => any; +} +declare var MSXMLHttpRequestExtensions: { + prototype: MSXMLHttpRequestExtensions; + new(): MSXMLHttpRequestExtensions; +} + +interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + kernelUnitLengthY: SVGAnimatedNumber; + surfaceScale: SVGAnimatedNumber; + in1: SVGAnimatedString; + kernelUnitLengthX: SVGAnimatedNumber; + diffuseConstant: SVGAnimatedNumber; +} +declare var SVGFEDiffuseLightingElement: { + prototype: SVGFEDiffuseLightingElement; + new(): SVGFEDiffuseLightingElement; +} + +interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { + in1: SVGAnimatedString; +} +declare var SVGFEComponentTransferElement: { + prototype: SVGFEComponentTransferElement; + new(): SVGFEComponentTransferElement; +} + +interface MSCSSMatrix { + m24: number; + m34: number; + a: number; + d: number; + m32: number; + m41: number; + m11: number; + f: number; + e: number; + m23: number; + m14: number; + m33: number; + m22: number; + m21: number; + c: number; + m12: number; + b: number; + m42: number; + m31: number; + m43: number; + m13: number; + m44: number; + multiply(secondMatrix: MSCSSMatrix): MSCSSMatrix; + skewY(angle: number): MSCSSMatrix; + setMatrixValue(value: string): void; + inverse(): MSCSSMatrix; + rotateAxisAngle(x: number, y: number, z: number, angle: number): MSCSSMatrix; + toString(): string; + rotate(angleX: number, angleY?: number, angleZ?: number): MSCSSMatrix; + translate(x: number, y: number, z?: number): MSCSSMatrix; + scale(scaleX: number, scaleY?: number, scaleZ?: number): MSCSSMatrix; + skewX(angle: number): MSCSSMatrix; +} +declare var MSCSSMatrix: { + prototype: MSCSSMatrix; + new (text?: string): MSCSSMatrix; +} + +interface Worker extends AbstractWorker { + onmessage: (ev: any) => any; + postMessage(message: any, ports?: any): void; + terminate(): void; +} +declare var Worker: { + prototype: Worker; + new (stringUrl: string): Worker; +} + +interface HTMLIFrameElement { + sandbox: DOMSettableTokenList; +} + +interface MSMediaErrorExtensions { + msExtendedCode: number; +} + +interface MSNavigatorAbilities { + msProtocols: MSProtocolsCollection; + msMaxTouchPoints: number; + msPointerEnabled: bool; + msManipulationViewsEnabled: bool; +} +declare var MSNavigatorAbilities: { + prototype: MSNavigatorAbilities; + new(): MSNavigatorAbilities; +} + +declare var onpopstate: (ev: PopStateEvent) => any; +declare var applicationCache: ApplicationCache; +declare function matchMedia(mediaQuery: string): MediaQueryList; +declare function msMatchMedia(mediaQuery: string): MediaQueryList; +declare var animationStartTime: number; +declare var msAnimationStartTime: number; +declare function msCancelRequestAnimationFrame(handle: number): void; +declare function cancelAnimationFrame(handle: number): void; +declare function requestAnimationFrame(callback: FrameRequestCallback): number; +declare function msRequestAnimationFrame(callback: FrameRequestCallback): number; +declare function btoa(rawString: string): string; +declare function atob(encodedString: string): string; +declare var msIndexedDB: IDBFactory; +declare var indexedDB: IDBFactory; +declare var console: Console; + + +///////////////////////////// +/// WorkerGlobalScope APIs +///////////////////////////// +// TODO: These are only available in a Web Worker - should be in a seperate lib file +declare function importScripts(...urls: string[]): void; + + +///////////////////////////// +/// Windows Script Host APIS +///////////////////////////// +declare var ActiveXObject: { new (s: string): any; }; + +interface ITextWriter { + Write(s: string): void; + WriteLine(s: string): void; + Close(): void; +} + +declare var WScript : { + Echo(s); + StdErr: ITextWriter; + StdOut: ITextWriter; + Arguments: { length: number; Item(n: number): string; }; + ScriptFullName: string; + Quit(exitCode?: number); +} + diff --git a/_infrastructure/tests/typescript_0.8.3/tsc b/_infrastructure/tests/typescript_0.8.3/tsc new file mode 100644 index 0000000000..3c0dab574f --- /dev/null +++ b/_infrastructure/tests/typescript_0.8.3/tsc @@ -0,0 +1,2 @@ +#!/usr/bin/env node +require('./tsc.js') diff --git a/_infrastructure/tests/typescript_0.8.3/tsc.js b/_infrastructure/tests/typescript_0.8.3/tsc.js new file mode 100644 index 0000000000..58a3b5e25c --- /dev/null +++ b/_infrastructure/tests/typescript_0.8.3/tsc.js @@ -0,0 +1,24836 @@ +/* ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + +var TypeScript; +(function (TypeScript) { + function hasFlag(val, flag) { + return (val & flag) != 0; + } + TypeScript.hasFlag = hasFlag; + (function (ErrorRecoverySet) { + ErrorRecoverySet._map = []; + ErrorRecoverySet.None = 0; + ErrorRecoverySet.Comma = 1; + ErrorRecoverySet.SColon = 1 << 1; + ErrorRecoverySet.Asg = 1 << 2; + ErrorRecoverySet.BinOp = 1 << 3; + ErrorRecoverySet.RBrack = 1 << 4; + ErrorRecoverySet.RCurly = 1 << 5; + ErrorRecoverySet.RParen = 1 << 6; + ErrorRecoverySet.Dot = 1 << 7; + ErrorRecoverySet.Colon = 1 << 8; + ErrorRecoverySet.PrimType = 1 << 9; + ErrorRecoverySet.AddOp = 1 << 10; + ErrorRecoverySet.LCurly = 1 << 11; + ErrorRecoverySet.PreOp = 1 << 12; + ErrorRecoverySet.RegExp = 1 << 13; + ErrorRecoverySet.LParen = 1 << 14; + ErrorRecoverySet.LBrack = 1 << 15; + ErrorRecoverySet.Scope = 1 << 16; + ErrorRecoverySet.In = 1 << 17; + ErrorRecoverySet.SCase = 1 << 18; + ErrorRecoverySet.Else = 1 << 19; + ErrorRecoverySet.Catch = 1 << 20; + ErrorRecoverySet.Var = 1 << 21; + ErrorRecoverySet.Stmt = 1 << 22; + ErrorRecoverySet.While = 1 << 23; + ErrorRecoverySet.ID = 1 << 24; + ErrorRecoverySet.Prefix = 1 << 25; + ErrorRecoverySet.Literal = 1 << 26; + ErrorRecoverySet.RLit = 1 << 27; + ErrorRecoverySet.Func = 1 << 28; + ErrorRecoverySet.EOF = 1 << 29; + ErrorRecoverySet.TypeScriptS = 1 << 30; + ErrorRecoverySet.ExprStart = ErrorRecoverySet.SColon | ErrorRecoverySet.AddOp | ErrorRecoverySet.LCurly | ErrorRecoverySet.PreOp | ErrorRecoverySet.RegExp | ErrorRecoverySet.LParen | ErrorRecoverySet.LBrack | ErrorRecoverySet.ID | ErrorRecoverySet.Prefix | ErrorRecoverySet.RLit | ErrorRecoverySet.Func | ErrorRecoverySet.Literal; + ErrorRecoverySet.StmtStart = ErrorRecoverySet.ExprStart | ErrorRecoverySet.SColon | ErrorRecoverySet.Var | ErrorRecoverySet.Stmt | ErrorRecoverySet.While | ErrorRecoverySet.TypeScriptS; + ErrorRecoverySet.Postfix = ErrorRecoverySet.Dot | ErrorRecoverySet.LParen | ErrorRecoverySet.LBrack; + })(TypeScript.ErrorRecoverySet || (TypeScript.ErrorRecoverySet = {})); + var ErrorRecoverySet = TypeScript.ErrorRecoverySet; + (function (AllowedElements) { + AllowedElements._map = []; + AllowedElements.None = 0; + AllowedElements.ModuleDeclarations = 1 << 2; + AllowedElements.ClassDeclarations = 1 << 3; + AllowedElements.InterfaceDeclarations = 1 << 4; + AllowedElements.AmbientDeclarations = 1 << 10; + AllowedElements.Properties = 1 << 11; + AllowedElements.Global = AllowedElements.ModuleDeclarations | AllowedElements.ClassDeclarations | AllowedElements.InterfaceDeclarations | AllowedElements.AmbientDeclarations; + AllowedElements.QuickParse = AllowedElements.Global | AllowedElements.Properties; + })(TypeScript.AllowedElements || (TypeScript.AllowedElements = {})); + var AllowedElements = TypeScript.AllowedElements; + (function (Modifiers) { + Modifiers._map = []; + Modifiers.None = 0; + Modifiers.Private = 1; + Modifiers.Public = 1 << 1; + Modifiers.Readonly = 1 << 2; + Modifiers.Ambient = 1 << 3; + Modifiers.Exported = 1 << 4; + Modifiers.Getter = 1 << 5; + Modifiers.Setter = 1 << 6; + Modifiers.Static = 1 << 7; + })(TypeScript.Modifiers || (TypeScript.Modifiers = {})); + var Modifiers = TypeScript.Modifiers; + (function (ASTFlags) { + ASTFlags._map = []; + ASTFlags.None = 0; + ASTFlags.ExplicitSemicolon = 1; + ASTFlags.AutomaticSemicolon = 1 << 1; + ASTFlags.Writeable = 1 << 2; + ASTFlags.Error = 1 << 3; + ASTFlags.DotLHSPartial = 1 << 4; + ASTFlags.DotLHS = 1 << 5; + ASTFlags.IsStatement = 1 << 6; + ASTFlags.StrictMode = 1 << 7; + ASTFlags.PossibleOptionalParameter = 1 << 8; + ASTFlags.ClassBaseConstructorCall = 1 << 9; + ASTFlags.OptionalName = 1 << 10; + ASTFlags.SkipNextRParen = 1 << 11; + })(TypeScript.ASTFlags || (TypeScript.ASTFlags = {})); + var ASTFlags = TypeScript.ASTFlags; + (function (DeclFlags) { + DeclFlags._map = []; + DeclFlags.None = 0; + DeclFlags.Exported = 1; + DeclFlags.Private = 1 << 1; + DeclFlags.Public = 1 << 2; + DeclFlags.Ambient = 1 << 3; + DeclFlags.Static = 1 << 4; + DeclFlags.LocalStatic = 1 << 5; + DeclFlags.GetAccessor = 1 << 6; + DeclFlags.SetAccessor = 1 << 7; + })(TypeScript.DeclFlags || (TypeScript.DeclFlags = {})); + var DeclFlags = TypeScript.DeclFlags; + (function (ModuleFlags) { + ModuleFlags._map = []; + ModuleFlags.None = 0; + ModuleFlags.Exported = 1; + ModuleFlags.Private = 1 << 1; + ModuleFlags.Public = 1 << 2; + ModuleFlags.Ambient = 1 << 3; + ModuleFlags.Static = 1 << 4; + ModuleFlags.LocalStatic = 1 << 5; + ModuleFlags.GetAccessor = 1 << 6; + ModuleFlags.SetAccessor = 1 << 7; + ModuleFlags.IsEnum = 1 << 8; + ModuleFlags.ShouldEmitModuleDecl = 1 << 9; + ModuleFlags.IsWholeFile = 1 << 10; + ModuleFlags.IsDynamic = 1 << 11; + ModuleFlags.MustCaptureThis = 1 << 12; + })(TypeScript.ModuleFlags || (TypeScript.ModuleFlags = {})); + var ModuleFlags = TypeScript.ModuleFlags; + (function (SymbolFlags) { + SymbolFlags._map = []; + SymbolFlags.None = 0; + SymbolFlags.Exported = 1; + SymbolFlags.Private = 1 << 1; + SymbolFlags.Public = 1 << 2; + SymbolFlags.Ambient = 1 << 3; + SymbolFlags.Static = 1 << 4; + SymbolFlags.LocalStatic = 1 << 5; + SymbolFlags.GetAccessor = 1 << 6; + SymbolFlags.SetAccessor = 1 << 7; + SymbolFlags.Property = 1 << 8; + SymbolFlags.Readonly = 1 << 9; + SymbolFlags.ModuleMember = 1 << 10; + SymbolFlags.InterfaceMember = 1 << 11; + SymbolFlags.ClassMember = 1 << 12; + SymbolFlags.BuiltIn = 1 << 13; + SymbolFlags.TypeSetDuringScopeAssignment = 1 << 14; + SymbolFlags.Constant = 1 << 15; + SymbolFlags.Optional = 1 << 16; + SymbolFlags.RecursivelyReferenced = 1 << 17; + SymbolFlags.Bound = 1 << 18; + SymbolFlags.CompilerGenerated = 1 << 19; + })(TypeScript.SymbolFlags || (TypeScript.SymbolFlags = {})); + var SymbolFlags = TypeScript.SymbolFlags; + (function (VarFlags) { + VarFlags._map = []; + VarFlags.None = 0; + VarFlags.Exported = 1; + VarFlags.Private = 1 << 1; + VarFlags.Public = 1 << 2; + VarFlags.Ambient = 1 << 3; + VarFlags.Static = 1 << 4; + VarFlags.LocalStatic = 1 << 5; + VarFlags.GetAccessor = 1 << 6; + VarFlags.SetAccessor = 1 << 7; + VarFlags.AutoInit = 1 << 8; + VarFlags.Property = 1 << 9; + VarFlags.Readonly = 1 << 10; + VarFlags.Class = 1 << 11; + VarFlags.ClassProperty = 1 << 12; + VarFlags.ClassBodyProperty = 1 << 13; + VarFlags.ClassConstructorProperty = 1 << 14; + VarFlags.ClassSuperMustBeFirstCallInConstructor = 1 << 15; + VarFlags.Constant = 1 << 16; + VarFlags.MustCaptureThis = 1 << 17; + })(TypeScript.VarFlags || (TypeScript.VarFlags = {})); + var VarFlags = TypeScript.VarFlags; + (function (FncFlags) { + FncFlags._map = []; + FncFlags.None = 0; + FncFlags.Exported = 1; + FncFlags.Private = 1 << 1; + FncFlags.Public = 1 << 2; + FncFlags.Ambient = 1 << 3; + FncFlags.Static = 1 << 4; + FncFlags.LocalStatic = 1 << 5; + FncFlags.GetAccessor = 1 << 6; + FncFlags.SetAccessor = 1 << 7; + FncFlags.Signature = 1 << 9; + FncFlags.Method = 1 << 10; + FncFlags.HasReturnExpression = 1 << 11; + FncFlags.CallMember = 1 << 12; + FncFlags.ConstructMember = 1 << 13; + FncFlags.HasSelfReference = 1 << 14; + FncFlags.IsFatArrowFunction = 1 << 15; + FncFlags.IndexerMember = 1 << 16; + FncFlags.IsFunctionExpression = 1 << 17; + FncFlags.ClassMethod = 1 << 18; + FncFlags.ClassPropertyMethodExported = 1 << 19; + FncFlags.HasSuperReferenceInFatArrowFunction = 1 << 20; + FncFlags.IsPropertyBound = 1 << 21; + })(TypeScript.FncFlags || (TypeScript.FncFlags = {})); + var FncFlags = TypeScript.FncFlags; + (function (SignatureFlags) { + SignatureFlags._map = []; + SignatureFlags.None = 0; + SignatureFlags.IsIndexer = 1; + SignatureFlags.IsStringIndexer = 1 << 1; + SignatureFlags.IsNumberIndexer = 1 << 2; + })(TypeScript.SignatureFlags || (TypeScript.SignatureFlags = {})); + var SignatureFlags = TypeScript.SignatureFlags; + function ToDeclFlags(fncOrVarOrSymbolOrModuleFlags) { + return fncOrVarOrSymbolOrModuleFlags; + } + TypeScript.ToDeclFlags = ToDeclFlags; + (function (TypeFlags) { + TypeFlags._map = []; + TypeFlags.None = 0; + TypeFlags.HasImplementation = 1; + TypeFlags.HasSelfReference = 1 << 1; + TypeFlags.MergeResult = 1 << 2; + TypeFlags.IsEnum = 1 << 3; + TypeFlags.BuildingName = 1 << 4; + TypeFlags.HasBaseType = 1 << 5; + TypeFlags.HasBaseTypeOfObject = 1 << 6; + TypeFlags.IsClass = 1 << 7; + })(TypeScript.TypeFlags || (TypeScript.TypeFlags = {})); + var TypeFlags = TypeScript.TypeFlags; + (function (TypeRelationshipFlags) { + TypeRelationshipFlags._map = []; + TypeRelationshipFlags.SuccessfulComparison = 0; + TypeRelationshipFlags.SourceIsNullTargetIsVoidOrUndefined = 1; + TypeRelationshipFlags.RequiredPropertyIsMissing = 1 << 1; + TypeRelationshipFlags.IncompatibleSignatures = 1 << 2; + TypeRelationshipFlags.SourceSignatureHasTooManyParameters = 3; + TypeRelationshipFlags.IncompatibleReturnTypes = 1 << 4; + TypeRelationshipFlags.IncompatiblePropertyTypes = 1 << 5; + TypeRelationshipFlags.IncompatibleParameterTypes = 1 << 6; + })(TypeScript.TypeRelationshipFlags || (TypeScript.TypeRelationshipFlags = {})); + var TypeRelationshipFlags = TypeScript.TypeRelationshipFlags; + (function (CodeGenTarget) { + CodeGenTarget._map = []; + CodeGenTarget.ES3 = 0; + CodeGenTarget.ES5 = 1; + })(TypeScript.CodeGenTarget || (TypeScript.CodeGenTarget = {})); + var CodeGenTarget = TypeScript.CodeGenTarget; + (function (ModuleGenTarget) { + ModuleGenTarget._map = []; + ModuleGenTarget.Synchronous = 0; + ModuleGenTarget.Asynchronous = 1; + ModuleGenTarget.Local = 1 << 1; + })(TypeScript.ModuleGenTarget || (TypeScript.ModuleGenTarget = {})); + var ModuleGenTarget = TypeScript.ModuleGenTarget; + TypeScript.codeGenTarget = CodeGenTarget.ES3; + TypeScript.moduleGenTarget = ModuleGenTarget.Synchronous; + TypeScript.optimizeModuleCodeGen = true; + function flagsToString(e, flags) { + var builder = ""; + for(var i = 1; i < (1 << 31); i = i << 1) { + if((flags & i) != 0) { + for(var k in e) { + if(e[k] == i) { + if(builder.length > 0) { + builder += "|"; + } + builder += k; + break; + } + } + } + } + return builder; + } + TypeScript.flagsToString = flagsToString; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (NodeType) { + NodeType._map = []; + NodeType._map[0] = "None"; + NodeType.None = 0; + NodeType._map[1] = "Empty"; + NodeType.Empty = 1; + NodeType._map[2] = "EmptyExpr"; + NodeType.EmptyExpr = 2; + NodeType._map[3] = "True"; + NodeType.True = 3; + NodeType._map[4] = "False"; + NodeType.False = 4; + NodeType._map[5] = "This"; + NodeType.This = 5; + NodeType._map[6] = "Super"; + NodeType.Super = 6; + NodeType._map[7] = "QString"; + NodeType.QString = 7; + NodeType._map[8] = "Regex"; + NodeType.Regex = 8; + NodeType._map[9] = "Null"; + NodeType.Null = 9; + NodeType._map[10] = "ArrayLit"; + NodeType.ArrayLit = 10; + NodeType._map[11] = "ObjectLit"; + NodeType.ObjectLit = 11; + NodeType._map[12] = "Void"; + NodeType.Void = 12; + NodeType._map[13] = "Comma"; + NodeType.Comma = 13; + NodeType._map[14] = "Pos"; + NodeType.Pos = 14; + NodeType._map[15] = "Neg"; + NodeType.Neg = 15; + NodeType._map[16] = "Delete"; + NodeType.Delete = 16; + NodeType._map[17] = "Await"; + NodeType.Await = 17; + NodeType._map[18] = "In"; + NodeType.In = 18; + NodeType._map[19] = "Dot"; + NodeType.Dot = 19; + NodeType._map[20] = "From"; + NodeType.From = 20; + NodeType._map[21] = "Is"; + NodeType.Is = 21; + NodeType._map[22] = "InstOf"; + NodeType.InstOf = 22; + NodeType._map[23] = "Typeof"; + NodeType.Typeof = 23; + NodeType._map[24] = "NumberLit"; + NodeType.NumberLit = 24; + NodeType._map[25] = "Name"; + NodeType.Name = 25; + NodeType._map[26] = "TypeRef"; + NodeType.TypeRef = 26; + NodeType._map[27] = "Index"; + NodeType.Index = 27; + NodeType._map[28] = "Call"; + NodeType.Call = 28; + NodeType._map[29] = "New"; + NodeType.New = 29; + NodeType._map[30] = "Asg"; + NodeType.Asg = 30; + NodeType._map[31] = "AsgAdd"; + NodeType.AsgAdd = 31; + NodeType._map[32] = "AsgSub"; + NodeType.AsgSub = 32; + NodeType._map[33] = "AsgDiv"; + NodeType.AsgDiv = 33; + NodeType._map[34] = "AsgMul"; + NodeType.AsgMul = 34; + NodeType._map[35] = "AsgMod"; + NodeType.AsgMod = 35; + NodeType._map[36] = "AsgAnd"; + NodeType.AsgAnd = 36; + NodeType._map[37] = "AsgXor"; + NodeType.AsgXor = 37; + NodeType._map[38] = "AsgOr"; + NodeType.AsgOr = 38; + NodeType._map[39] = "AsgLsh"; + NodeType.AsgLsh = 39; + NodeType._map[40] = "AsgRsh"; + NodeType.AsgRsh = 40; + NodeType._map[41] = "AsgRs2"; + NodeType.AsgRs2 = 41; + NodeType._map[42] = "ConditionalExpression"; + NodeType.ConditionalExpression = 42; + NodeType._map[43] = "LogOr"; + NodeType.LogOr = 43; + NodeType._map[44] = "LogAnd"; + NodeType.LogAnd = 44; + NodeType._map[45] = "Or"; + NodeType.Or = 45; + NodeType._map[46] = "Xor"; + NodeType.Xor = 46; + NodeType._map[47] = "And"; + NodeType.And = 47; + NodeType._map[48] = "Eq"; + NodeType.Eq = 48; + NodeType._map[49] = "Ne"; + NodeType.Ne = 49; + NodeType._map[50] = "Eqv"; + NodeType.Eqv = 50; + NodeType._map[51] = "NEqv"; + NodeType.NEqv = 51; + NodeType._map[52] = "Lt"; + NodeType.Lt = 52; + NodeType._map[53] = "Le"; + NodeType.Le = 53; + NodeType._map[54] = "Gt"; + NodeType.Gt = 54; + NodeType._map[55] = "Ge"; + NodeType.Ge = 55; + NodeType._map[56] = "Add"; + NodeType.Add = 56; + NodeType._map[57] = "Sub"; + NodeType.Sub = 57; + NodeType._map[58] = "Mul"; + NodeType.Mul = 58; + NodeType._map[59] = "Div"; + NodeType.Div = 59; + NodeType._map[60] = "Mod"; + NodeType.Mod = 60; + NodeType._map[61] = "Lsh"; + NodeType.Lsh = 61; + NodeType._map[62] = "Rsh"; + NodeType.Rsh = 62; + NodeType._map[63] = "Rs2"; + NodeType.Rs2 = 63; + NodeType._map[64] = "Not"; + NodeType.Not = 64; + NodeType._map[65] = "LogNot"; + NodeType.LogNot = 65; + NodeType._map[66] = "IncPre"; + NodeType.IncPre = 66; + NodeType._map[67] = "DecPre"; + NodeType.DecPre = 67; + NodeType._map[68] = "IncPost"; + NodeType.IncPost = 68; + NodeType._map[69] = "DecPost"; + NodeType.DecPost = 69; + NodeType._map[70] = "TypeAssertion"; + NodeType.TypeAssertion = 70; + NodeType._map[71] = "FuncDecl"; + NodeType.FuncDecl = 71; + NodeType._map[72] = "Member"; + NodeType.Member = 72; + NodeType._map[73] = "VarDecl"; + NodeType.VarDecl = 73; + NodeType._map[74] = "ArgDecl"; + NodeType.ArgDecl = 74; + NodeType._map[75] = "Return"; + NodeType.Return = 75; + NodeType._map[76] = "Break"; + NodeType.Break = 76; + NodeType._map[77] = "Continue"; + NodeType.Continue = 77; + NodeType._map[78] = "Throw"; + NodeType.Throw = 78; + NodeType._map[79] = "For"; + NodeType.For = 79; + NodeType._map[80] = "ForIn"; + NodeType.ForIn = 80; + NodeType._map[81] = "If"; + NodeType.If = 81; + NodeType._map[82] = "While"; + NodeType.While = 82; + NodeType._map[83] = "DoWhile"; + NodeType.DoWhile = 83; + NodeType._map[84] = "Block"; + NodeType.Block = 84; + NodeType._map[85] = "Case"; + NodeType.Case = 85; + NodeType._map[86] = "Switch"; + NodeType.Switch = 86; + NodeType._map[87] = "Try"; + NodeType.Try = 87; + NodeType._map[88] = "TryCatch"; + NodeType.TryCatch = 88; + NodeType._map[89] = "TryFinally"; + NodeType.TryFinally = 89; + NodeType._map[90] = "Finally"; + NodeType.Finally = 90; + NodeType._map[91] = "Catch"; + NodeType.Catch = 91; + NodeType._map[92] = "List"; + NodeType.List = 92; + NodeType._map[93] = "Script"; + NodeType.Script = 93; + NodeType._map[94] = "ClassDeclaration"; + NodeType.ClassDeclaration = 94; + NodeType._map[95] = "InterfaceDeclaration"; + NodeType.InterfaceDeclaration = 95; + NodeType._map[96] = "ModuleDeclaration"; + NodeType.ModuleDeclaration = 96; + NodeType._map[97] = "ImportDeclaration"; + NodeType.ImportDeclaration = 97; + NodeType._map[98] = "With"; + NodeType.With = 98; + NodeType._map[99] = "Label"; + NodeType.Label = 99; + NodeType._map[100] = "LabeledStatement"; + NodeType.LabeledStatement = 100; + NodeType._map[101] = "EBStart"; + NodeType.EBStart = 101; + NodeType._map[102] = "GotoEB"; + NodeType.GotoEB = 102; + NodeType._map[103] = "EndCode"; + NodeType.EndCode = 103; + NodeType._map[104] = "Error"; + NodeType.Error = 104; + NodeType._map[105] = "Comment"; + NodeType.Comment = 105; + NodeType._map[106] = "Debugger"; + NodeType.Debugger = 106; + NodeType.GeneralNode = NodeType.FuncDecl; + NodeType.LastAsg = NodeType.AsgRs2; + })(TypeScript.NodeType || (TypeScript.NodeType = {})); + var NodeType = TypeScript.NodeType; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var BlockIntrinsics = (function () { + function BlockIntrinsics() { + this.prototype = undefined; + this.toString = undefined; + this.toLocaleString = undefined; + this.valueOf = undefined; + this.hasOwnProperty = undefined; + this.propertyIsEnumerable = undefined; + this.isPrototypeOf = undefined; + this["constructor"] = undefined; + } + return BlockIntrinsics; + })(); + TypeScript.BlockIntrinsics = BlockIntrinsics; + var StringHashTable = (function () { + function StringHashTable() { + this.itemCount = 0; + this.table = (new BlockIntrinsics()); + } + StringHashTable.prototype.getAllKeys = function () { + var result = []; + for(var k in this.table) { + if(this.table[k] != undefined) { + result[result.length] = k; + } + } + return result; + }; + StringHashTable.prototype.add = function (key, data) { + if(this.table[key] != undefined) { + return false; + } + this.table[key] = data; + this.itemCount++; + return true; + }; + StringHashTable.prototype.addOrUpdate = function (key, data) { + if(this.table[key] != undefined) { + this.table[key] = data; + return false; + } + this.table[key] = data; + this.itemCount++; + return true; + }; + StringHashTable.prototype.map = function (fn, context) { + for(var k in this.table) { + var data = this.table[k]; + if(data != undefined) { + fn(k, this.table[k], context); + } + } + }; + StringHashTable.prototype.every = function (fn, context) { + for(var k in this.table) { + var data = this.table[k]; + if(data != undefined) { + if(!fn(k, this.table[k], context)) { + return false; + } + } + } + return true; + }; + StringHashTable.prototype.some = function (fn, context) { + for(var k in this.table) { + var data = this.table[k]; + if(data != undefined) { + if(fn(k, this.table[k], context)) { + return true; + } + } + } + return false; + }; + StringHashTable.prototype.count = function () { + return this.itemCount; + }; + StringHashTable.prototype.lookup = function (key) { + var data = this.table[key]; + if(data != undefined) { + return data; + } else { + return (null); + } + }; + return StringHashTable; + })(); + TypeScript.StringHashTable = StringHashTable; + var DualStringHashTable = (function () { + function DualStringHashTable(primaryTable, secondaryTable) { + this.primaryTable = primaryTable; + this.secondaryTable = secondaryTable; + this.insertPrimary = true; + } + DualStringHashTable.prototype.getAllKeys = function () { + return this.primaryTable.getAllKeys().concat(this.secondaryTable.getAllKeys()); + }; + DualStringHashTable.prototype.add = function (key, data) { + if(this.insertPrimary) { + return this.primaryTable.add(key, data); + } else { + return this.secondaryTable.add(key, data); + } + }; + DualStringHashTable.prototype.addOrUpdate = function (key, data) { + if(this.insertPrimary) { + return this.primaryTable.addOrUpdate(key, data); + } else { + return this.secondaryTable.addOrUpdate(key, data); + } + }; + DualStringHashTable.prototype.map = function (fn, context) { + this.primaryTable.map(fn, context); + this.secondaryTable.map(fn, context); + }; + DualStringHashTable.prototype.every = function (fn, context) { + return this.primaryTable.every(fn, context) && this.secondaryTable.every(fn, context); + }; + DualStringHashTable.prototype.some = function (fn, context) { + return this.primaryTable.some(fn, context) || this.secondaryTable.some(fn, context); + }; + DualStringHashTable.prototype.count = function () { + return this.primaryTable.count() + this.secondaryTable.count(); + }; + DualStringHashTable.prototype.lookup = function (key) { + var data = this.primaryTable.lookup(key); + if(data != undefined) { + return data; + } else { + return this.secondaryTable.lookup(key); + } + }; + return DualStringHashTable; + })(); + TypeScript.DualStringHashTable = DualStringHashTable; + function numberHashFn(key) { + var c2 = 0x27d4eb2d; + key = (key ^ 61) ^ (key >>> 16); + key = key + (key << 3); + key = key ^ (key >>> 4); + key = key * c2; + key = key ^ (key >>> 15); + return key; + } + TypeScript.numberHashFn = numberHashFn; + function combineHashes(key1, key2) { + return key2 ^ ((key1 >> 5) + key1); + } + TypeScript.combineHashes = combineHashes; + var HashEntry = (function () { + function HashEntry(key, data) { + this.key = key; + this.data = data; + } + return HashEntry; + })(); + TypeScript.HashEntry = HashEntry; + var HashTable = (function () { + function HashTable(size, hashFn, equalsFn) { + this.size = size; + this.hashFn = hashFn; + this.equalsFn = equalsFn; + this.itemCount = 0; + this.table = new Array(); + for(var i = 0; i < this.size; i++) { + this.table[i] = null; + } + } + HashTable.prototype.add = function (key, data) { + var current; + var entry = new HashEntry(key, data); + var val = this.hashFn(key); + val = val % this.size; + for(current = this.table[val]; current != null; current = current.next) { + if(this.equalsFn(key, current.key)) { + return false; + } + } + entry.next = this.table[val]; + this.table[val] = entry; + this.itemCount++; + return true; + }; + HashTable.prototype.remove = function (key) { + var current; + var val = this.hashFn(key); + val = val % this.size; + var result = null; + var prevEntry = null; + for(current = this.table[val]; current != null; current = current.next) { + if(this.equalsFn(key, current.key)) { + result = current.data; + this.itemCount--; + if(prevEntry) { + prevEntry.next = current.next; + } else { + this.table[val] = current.next; + } + break; + } + prevEntry = current; + } + return result; + }; + HashTable.prototype.count = function () { + return this.itemCount; + }; + HashTable.prototype.lookup = function (key) { + var current; + var val = this.hashFn(key); + val = val % this.size; + for(current = this.table[val]; current != null; current = current.next) { + if(this.equalsFn(key, current.key)) { + return (current.data); + } + } + return (null); + }; + return HashTable; + })(); + TypeScript.HashTable = HashTable; + var SimpleHashTable = (function () { + function SimpleHashTable() { + this.keys = []; + this.values = []; + } + SimpleHashTable.prototype.lookup = function (key, findValue) { + var searchArray = this.keys; + if(findValue) { + searchArray = this.values; + } + for(var i = 0; i < searchArray.length; i++) { + if(searchArray[i] == key) { + return { + key: this.keys[i], + data: this.values[i] + }; + } + } + return null; + }; + SimpleHashTable.prototype.add = function (key, data) { + var lookupData = this.lookup(key); + if(lookupData) { + return false; + } + this.keys[this.keys.length] = key; + this.values[this.values.length] = data; + return true; + }; + return SimpleHashTable; + })(); + TypeScript.SimpleHashTable = SimpleHashTable; +})(TypeScript || (TypeScript = {})); +var __extends = this.__extends || function (d, b) { + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var TypeScript; +(function (TypeScript) { + var ASTSpan = (function () { + function ASTSpan() { + this.minChar = -1; + this.limChar = -1; + } + return ASTSpan; + })(); + TypeScript.ASTSpan = ASTSpan; + var AST = (function (_super) { + __extends(AST, _super); + function AST(nodeType) { + _super.call(this); + this.nodeType = nodeType; + this.type = null; + this.flags = TypeScript.ASTFlags.Writeable; + this.passCreated = TypeScript.CompilerDiagnostics.analysisPass; + this.preComments = null; + this.postComments = null; + this.docComments = null; + this.isParenthesized = false; + } + AST.prototype.isExpression = function () { + return false; + }; + AST.prototype.isStatementOrExpression = function () { + return false; + }; + AST.prototype.isCompoundStatement = function () { + return false; + }; + AST.prototype.isLeaf = function () { + return this.isStatementOrExpression() && (!this.isCompoundStatement()); + }; + AST.prototype.isDeclaration = function () { + return false; + }; + AST.prototype.typeCheck = function (typeFlow) { + switch(this.nodeType) { + case TypeScript.NodeType.Error: + case TypeScript.NodeType.EmptyExpr: + this.type = typeFlow.anyType; + break; + case TypeScript.NodeType.This: + return typeFlow.typeCheckThis(this); + case TypeScript.NodeType.Null: + this.type = typeFlow.nullType; + break; + case TypeScript.NodeType.False: + case TypeScript.NodeType.True: + this.type = typeFlow.booleanType; + break; + case TypeScript.NodeType.Super: + return typeFlow.typeCheckSuper(this); + case TypeScript.NodeType.EndCode: + case TypeScript.NodeType.Empty: + case TypeScript.NodeType.Void: + this.type = typeFlow.voidType; + break; + default: + throw new Error("please implement in derived class"); + } + return this; + }; + AST.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + switch(this.nodeType) { + case TypeScript.NodeType.This: + emitter.recordSourceMappingStart(this); + if(emitter.thisFnc && (TypeScript.hasFlag(emitter.thisFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction))) { + emitter.writeToOutput("_this"); + } else { + emitter.writeToOutput("this"); + } + emitter.recordSourceMappingEnd(this); + break; + case TypeScript.NodeType.Null: + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("null"); + emitter.recordSourceMappingEnd(this); + break; + case TypeScript.NodeType.False: + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("false"); + emitter.recordSourceMappingEnd(this); + break; + case TypeScript.NodeType.True: + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("true"); + emitter.recordSourceMappingEnd(this); + break; + case TypeScript.NodeType.Super: + emitter.recordSourceMappingStart(this); + emitter.emitSuperReference(); + emitter.recordSourceMappingEnd(this); + break; + case TypeScript.NodeType.EndCode: + case TypeScript.NodeType.Error: + case TypeScript.NodeType.EmptyExpr: + break; + case TypeScript.NodeType.Empty: + emitter.recordSourceMappingStart(this); + emitter.recordSourceMappingEnd(this); + break; + case TypeScript.NodeType.Void: + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("void "); + emitter.recordSourceMappingEnd(this); + break; + default: + throw new Error("please implement in derived class"); + } + emitter.emitParensAndCommentsInPlace(this, false); + }; + AST.prototype.print = function (context) { + context.startLine(); + var lineCol = { + line: -1, + col: -1 + }; + var limLineCol = { + line: -1, + col: -1 + }; + if(context.parser !== null) { + context.parser.getSourceLineCol(lineCol, this.minChar); + context.parser.getSourceLineCol(limLineCol, this.limChar); + context.write("(" + lineCol.line + "," + lineCol.col + ")--" + "(" + limLineCol.line + "," + limLineCol.col + "): "); + } + var lab = this.printLabel(); + if(TypeScript.hasFlag(this.flags, TypeScript.ASTFlags.Error)) { + lab += " (Error)"; + } + context.writeLine(lab); + }; + AST.prototype.printLabel = function () { + if(TypeScript.nodeTypeTable[this.nodeType] !== undefined) { + return TypeScript.nodeTypeTable[this.nodeType]; + } else { + return (TypeScript.NodeType)._map[this.nodeType]; + } + }; + AST.prototype.addToControlFlow = function (context) { + context.walker.options.goChildren = false; + context.addContent(this); + }; + AST.prototype.netFreeUses = function (container, freeUses) { + }; + AST.prototype.treeViewLabel = function () { + return (TypeScript.NodeType)._map[this.nodeType]; + }; + AST.getResolvedIdentifierName = function getResolvedIdentifierName(name) { + if(!name) { + return ""; + } + var resolved = ""; + var start = 0; + var i = 0; + while(i <= name.length - 6) { + if(name.charAt(i) == '\\' && name.charAt(i + 1) == 'u') { + var charCode = parseInt(name.substr(i + 2, 4), 16); + resolved += name.substr(start, i - start); + resolved += String.fromCharCode(charCode); + i += 6; + start = i; + continue; + } + i++; + } + resolved += name.substring(start); + return resolved; + }; + AST.prototype.getDocComments = function () { + if(!this.isDeclaration() || !this.preComments || this.preComments.length == 0) { + return []; + } + if(!this.docComments) { + var preCommentsLength = this.preComments.length; + var docComments = []; + for(var i = preCommentsLength - 1; i >= 0; i--) { + if(this.preComments[i].isDocComment()) { + var prevDocComment = docComments.length > 0 ? docComments[docComments.length - 1] : null; + if(prevDocComment == null || (this.preComments[i].limLine == prevDocComment.minLine || this.preComments[i].limLine + 1 == prevDocComment.minLine)) { + docComments.push(this.preComments[i]); + continue; + } + } + break; + } + this.docComments = docComments.reverse(); + } + return this.docComments; + }; + return AST; + })(ASTSpan); + TypeScript.AST = AST; + var IncompleteAST = (function (_super) { + __extends(IncompleteAST, _super); + function IncompleteAST(min, lim) { + _super.call(this, TypeScript.NodeType.Error); + this.minChar = min; + this.limChar = lim; + } + return IncompleteAST; + })(AST); + TypeScript.IncompleteAST = IncompleteAST; + var ASTList = (function (_super) { + __extends(ASTList, _super); + function ASTList() { + _super.call(this, TypeScript.NodeType.List); + this.enclosingScope = null; + this.members = new Array(); + } + ASTList.prototype.addToControlFlow = function (context) { + var len = this.members.length; + for(var i = 0; i < len; i++) { + if(context.noContinuation) { + context.addUnreachable(this.members[i]); + break; + } else { + this.members[i] = context.walk(this.members[i], this); + } + } + context.walker.options.goChildren = false; + }; + ASTList.prototype.append = function (ast) { + this.members[this.members.length] = ast; + return this; + }; + ASTList.prototype.appendAll = function (ast) { + if(ast.nodeType == TypeScript.NodeType.List) { + var list = ast; + for(var i = 0, len = list.members.length; i < len; i++) { + this.append(list.members[i]); + } + } else { + this.append(ast); + } + return this; + }; + ASTList.prototype.emit = function (emitter, tokenId, startLine) { + emitter.recordSourceMappingStart(this); + emitter.emitJavascriptList(this, null, TypeScript.TokenID.Semicolon, startLine, false, false); + emitter.recordSourceMappingEnd(this); + }; + ASTList.prototype.typeCheck = function (typeFlow) { + var len = this.members.length; + typeFlow.nestingLevel++; + for(var i = 0; i < len; i++) { + if(this.members[i]) { + this.members[i] = this.members[i].typeCheck(typeFlow); + } + } + typeFlow.nestingLevel--; + return this; + }; + return ASTList; + })(AST); + TypeScript.ASTList = ASTList; + var Identifier = (function (_super) { + __extends(Identifier, _super); + function Identifier(actualText, hasEscapeSequence) { + _super.call(this, TypeScript.NodeType.Name); + this.actualText = actualText; + this.hasEscapeSequence = hasEscapeSequence; + this.sym = null; + this.cloId = -1; + this.setText(actualText, hasEscapeSequence); + } + Identifier.prototype.setText = function (actualText, hasEscapeSequence) { + this.actualText = actualText; + if(hasEscapeSequence) { + this.text = AST.getResolvedIdentifierName(actualText); + } else { + this.text = actualText; + } + }; + Identifier.prototype.isMissing = function () { + return false; + }; + Identifier.prototype.isLeaf = function () { + return true; + }; + Identifier.prototype.treeViewLabel = function () { + return "id: " + this.actualText; + }; + Identifier.prototype.printLabel = function () { + if(this.actualText) { + return "id: " + this.actualText; + } else { + return "name node"; + } + }; + Identifier.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckName(this); + }; + Identifier.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitJavascriptName(this, true); + }; + Identifier.fromToken = function fromToken(token) { + return new Identifier(token.getText(), (token).hasEscapeSequence); + }; + return Identifier; + })(AST); + TypeScript.Identifier = Identifier; + var MissingIdentifier = (function (_super) { + __extends(MissingIdentifier, _super); + function MissingIdentifier() { + _super.call(this, "__missing"); + } + MissingIdentifier.prototype.isMissing = function () { + return true; + }; + MissingIdentifier.prototype.emit = function (emitter, tokenId, startLine) { + }; + return MissingIdentifier; + })(Identifier); + TypeScript.MissingIdentifier = MissingIdentifier; + var Label = (function (_super) { + __extends(Label, _super); + function Label(id) { + _super.call(this, TypeScript.NodeType.Label); + this.id = id; + } + Label.prototype.printLabel = function () { + return this.id.actualText + ":"; + }; + Label.prototype.typeCheck = function (typeFlow) { + this.type = typeFlow.voidType; + return this; + }; + Label.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.recordSourceMappingStart(this.id); + emitter.writeToOutput(this.id.actualText); + emitter.recordSourceMappingEnd(this.id); + emitter.writeLineToOutput(":"); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return Label; + })(AST); + TypeScript.Label = Label; + var Expression = (function (_super) { + __extends(Expression, _super); + function Expression(nodeType) { + _super.call(this, nodeType); + } + Expression.prototype.isExpression = function () { + return true; + }; + Expression.prototype.isStatementOrExpression = function () { + return true; + }; + return Expression; + })(AST); + TypeScript.Expression = Expression; + var UnaryExpression = (function (_super) { + __extends(UnaryExpression, _super); + function UnaryExpression(nodeType, operand) { + _super.call(this, nodeType); + this.operand = operand; + this.targetType = null; + this.castTerm = null; + } + UnaryExpression.prototype.addToControlFlow = function (context) { + _super.prototype.addToControlFlow.call(this, context); + if(this.nodeType == TypeScript.NodeType.Throw) { + context.returnStmt(); + } + }; + UnaryExpression.prototype.typeCheck = function (typeFlow) { + switch(this.nodeType) { + case TypeScript.NodeType.Not: + return typeFlow.typeCheckBitNot(this); + case TypeScript.NodeType.LogNot: + return typeFlow.typeCheckLogNot(this); + case TypeScript.NodeType.Pos: + case TypeScript.NodeType.Neg: + return typeFlow.typeCheckUnaryNumberOperator(this); + case TypeScript.NodeType.IncPost: + case TypeScript.NodeType.IncPre: + case TypeScript.NodeType.DecPost: + case TypeScript.NodeType.DecPre: + return typeFlow.typeCheckIncOrDec(this); + case TypeScript.NodeType.ArrayLit: + typeFlow.typeCheckArrayLit(this); + return this; + case TypeScript.NodeType.ObjectLit: + typeFlow.typeCheckObjectLit(this); + return this; + case TypeScript.NodeType.Throw: + this.operand = typeFlow.typeCheck(this.operand); + this.type = typeFlow.voidType; + return this; + case TypeScript.NodeType.Typeof: + this.operand = typeFlow.typeCheck(this.operand); + this.type = typeFlow.stringType; + return this; + case TypeScript.NodeType.Delete: + this.operand = typeFlow.typeCheck(this.operand); + this.type = typeFlow.booleanType; + break; + case TypeScript.NodeType.TypeAssertion: + this.castTerm = typeFlow.typeCheck(this.castTerm); + var applyTargetType = !this.operand.isParenthesized; + var targetType = applyTargetType ? this.castTerm.type : null; + typeFlow.checker.typeCheckWithContextualType(targetType, typeFlow.checker.inProvisionalTypecheckMode(), true, this.operand); + typeFlow.castWithCoercion(this.operand, this.castTerm.type, false, true); + this.type = this.castTerm.type; + return this; + case TypeScript.NodeType.Void: + this.operand = typeFlow.typeCheck(this.operand); + this.type = typeFlow.checker.undefinedType; + break; + default: + throw new Error("please implement in derived class"); + } + return this; + }; + UnaryExpression.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + switch(this.nodeType) { + case TypeScript.NodeType.IncPost: + emitter.emitJavascript(this.operand, TypeScript.TokenID.PlusPlus, false); + emitter.writeToOutput("++"); + break; + case TypeScript.NodeType.LogNot: + emitter.writeToOutput("!"); + emitter.emitJavascript(this.operand, TypeScript.TokenID.Exclamation, false); + break; + case TypeScript.NodeType.DecPost: + emitter.emitJavascript(this.operand, TypeScript.TokenID.MinusMinus, false); + emitter.writeToOutput("--"); + break; + case TypeScript.NodeType.ObjectLit: + emitter.emitObjectLiteral(this.operand); + break; + case TypeScript.NodeType.ArrayLit: + emitter.emitArrayLiteral(this.operand); + break; + case TypeScript.NodeType.Not: + emitter.writeToOutput("~"); + emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); + break; + case TypeScript.NodeType.Neg: + emitter.writeToOutput("-"); + if(this.operand.nodeType == TypeScript.NodeType.Neg) { + this.operand.isParenthesized = true; + } + emitter.emitJavascript(this.operand, TypeScript.TokenID.Minus, false); + break; + case TypeScript.NodeType.Pos: + emitter.writeToOutput("+"); + if(this.operand.nodeType == TypeScript.NodeType.Pos) { + this.operand.isParenthesized = true; + } + emitter.emitJavascript(this.operand, TypeScript.TokenID.Plus, false); + break; + case TypeScript.NodeType.IncPre: + emitter.writeToOutput("++"); + emitter.emitJavascript(this.operand, TypeScript.TokenID.PlusPlus, false); + break; + case TypeScript.NodeType.DecPre: + emitter.writeToOutput("--"); + emitter.emitJavascript(this.operand, TypeScript.TokenID.MinusMinus, false); + break; + case TypeScript.NodeType.Throw: + emitter.writeToOutput("throw "); + emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); + emitter.writeToOutput(";"); + break; + case TypeScript.NodeType.Typeof: + emitter.writeToOutput("typeof "); + emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); + break; + case TypeScript.NodeType.Delete: + emitter.writeToOutput("delete "); + emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); + break; + case TypeScript.NodeType.Void: + emitter.writeToOutput("void "); + emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); + break; + case TypeScript.NodeType.TypeAssertion: + emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); + break; + default: + throw new Error("please implement in derived class"); + } + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return UnaryExpression; + })(Expression); + TypeScript.UnaryExpression = UnaryExpression; + var CallExpression = (function (_super) { + __extends(CallExpression, _super); + function CallExpression(nodeType, target, arguments) { + _super.call(this, nodeType); + this.target = target; + this.arguments = arguments; + this.signature = null; + this.minChar = this.target.minChar; + } + CallExpression.prototype.typeCheck = function (typeFlow) { + if(this.nodeType == TypeScript.NodeType.New) { + return typeFlow.typeCheckNew(this); + } else { + return typeFlow.typeCheckCall(this); + } + }; + CallExpression.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + if(this.nodeType == TypeScript.NodeType.New) { + emitter.emitNew(this.target, this.arguments); + } else { + emitter.emitCall(this, this.target, this.arguments); + } + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return CallExpression; + })(Expression); + TypeScript.CallExpression = CallExpression; + var BinaryExpression = (function (_super) { + __extends(BinaryExpression, _super); + function BinaryExpression(nodeType, operand1, operand2) { + _super.call(this, nodeType); + this.operand1 = operand1; + this.operand2 = operand2; + } + BinaryExpression.prototype.typeCheck = function (typeFlow) { + switch(this.nodeType) { + case TypeScript.NodeType.Dot: + return typeFlow.typeCheckDotOperator(this); + case TypeScript.NodeType.Asg: + return typeFlow.typeCheckAsgOperator(this); + case TypeScript.NodeType.Add: + case TypeScript.NodeType.Sub: + case TypeScript.NodeType.Mul: + case TypeScript.NodeType.Div: + case TypeScript.NodeType.Mod: + case TypeScript.NodeType.Or: + case TypeScript.NodeType.And: + return typeFlow.typeCheckArithmeticOperator(this, false); + case TypeScript.NodeType.Xor: + return typeFlow.typeCheckBitwiseOperator(this, false); + case TypeScript.NodeType.Ne: + case TypeScript.NodeType.Eq: + var text; + if(typeFlow.checker.styleSettings.eqeqeq) { + text = TypeScript.nodeTypeTable[this.nodeType]; + typeFlow.checker.errorReporter.styleError(this, "use of " + text); + } else if(typeFlow.checker.styleSettings.eqnull) { + text = TypeScript.nodeTypeTable[this.nodeType]; + if((this.operand2 !== null) && (this.operand2.nodeType == TypeScript.NodeType.Null)) { + typeFlow.checker.errorReporter.styleError(this, "use of " + text + " to compare with null"); + } + } + case TypeScript.NodeType.Eqv: + case TypeScript.NodeType.NEqv: + case TypeScript.NodeType.Lt: + case TypeScript.NodeType.Le: + case TypeScript.NodeType.Ge: + case TypeScript.NodeType.Gt: + return typeFlow.typeCheckBooleanOperator(this); + case TypeScript.NodeType.Index: + return typeFlow.typeCheckIndex(this); + case TypeScript.NodeType.Member: + this.type = typeFlow.voidType; + return this; + case TypeScript.NodeType.LogOr: + return typeFlow.typeCheckLogOr(this); + case TypeScript.NodeType.LogAnd: + return typeFlow.typeCheckLogAnd(this); + case TypeScript.NodeType.AsgAdd: + case TypeScript.NodeType.AsgSub: + case TypeScript.NodeType.AsgMul: + case TypeScript.NodeType.AsgDiv: + case TypeScript.NodeType.AsgMod: + case TypeScript.NodeType.AsgOr: + case TypeScript.NodeType.AsgAnd: + return typeFlow.typeCheckArithmeticOperator(this, true); + case TypeScript.NodeType.AsgXor: + return typeFlow.typeCheckBitwiseOperator(this, true); + case TypeScript.NodeType.Lsh: + case TypeScript.NodeType.Rsh: + case TypeScript.NodeType.Rs2: + return typeFlow.typeCheckShift(this, false); + case TypeScript.NodeType.AsgLsh: + case TypeScript.NodeType.AsgRsh: + case TypeScript.NodeType.AsgRs2: + return typeFlow.typeCheckShift(this, true); + case TypeScript.NodeType.Comma: + return typeFlow.typeCheckCommaOperator(this); + case TypeScript.NodeType.InstOf: + return typeFlow.typeCheckInstOf(this); + case TypeScript.NodeType.In: + return typeFlow.typeCheckInOperator(this); + case TypeScript.NodeType.From: + typeFlow.checker.errorReporter.simpleError(this, "Illegal use of 'from' keyword in binary expression"); + break; + default: + throw new Error("please implement in derived class"); + } + return this; + }; + BinaryExpression.prototype.emit = function (emitter, tokenId, startLine) { + var binTokenId = TypeScript.nodeTypeToTokTable[this.nodeType]; + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + if(binTokenId != undefined) { + emitter.emitJavascript(this.operand1, binTokenId, false); + if(TypeScript.tokenTable[binTokenId].text == "instanceof") { + emitter.writeToOutput(" instanceof "); + } else if(TypeScript.tokenTable[binTokenId].text == "in") { + emitter.writeToOutput(" in "); + } else { + emitter.writeToOutputTrimmable(" " + TypeScript.tokenTable[binTokenId].text + " "); + } + emitter.emitJavascript(this.operand2, binTokenId, false); + } else { + switch(this.nodeType) { + case TypeScript.NodeType.Dot: + if(!emitter.tryEmitConstant(this)) { + emitter.emitJavascript(this.operand1, TypeScript.TokenID.Dot, false); + emitter.writeToOutput("."); + emitter.emitJavascriptName(this.operand2, false); + } + break; + case TypeScript.NodeType.Index: + emitter.emitIndex(this.operand1, this.operand2); + break; + case TypeScript.NodeType.Member: + if(this.operand2.nodeType == TypeScript.NodeType.FuncDecl && (this.operand2).isAccessor()) { + var funcDecl = this.operand2; + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { + emitter.writeToOutput("get "); + } else { + emitter.writeToOutput("set "); + } + emitter.emitJavascript(this.operand1, TypeScript.TokenID.Colon, false); + } else { + emitter.emitJavascript(this.operand1, TypeScript.TokenID.Colon, false); + emitter.writeToOutputTrimmable(": "); + } + emitter.emitJavascript(this.operand2, TypeScript.TokenID.Comma, false); + break; + case TypeScript.NodeType.Comma: + emitter.emitJavascript(this.operand1, TypeScript.TokenID.Comma, false); + if(emitter.emitState.inObjectLiteral) { + emitter.writeLineToOutput(", "); + } else { + emitter.writeToOutput(","); + } + emitter.emitJavascript(this.operand2, TypeScript.TokenID.Comma, false); + break; + case TypeScript.NodeType.Is: + throw new Error("should be de-sugared during type check"); + default: + throw new Error("please implement in derived class"); + } + } + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return BinaryExpression; + })(Expression); + TypeScript.BinaryExpression = BinaryExpression; + var ConditionalExpression = (function (_super) { + __extends(ConditionalExpression, _super); + function ConditionalExpression(operand1, operand2, operand3) { + _super.call(this, TypeScript.NodeType.ConditionalExpression); + this.operand1 = operand1; + this.operand2 = operand2; + this.operand3 = operand3; + } + ConditionalExpression.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckQMark(this); + }; + ConditionalExpression.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.emitJavascript(this.operand1, TypeScript.TokenID.Question, false); + emitter.writeToOutput(" ? "); + emitter.emitJavascript(this.operand2, TypeScript.TokenID.Question, false); + emitter.writeToOutput(" : "); + emitter.emitJavascript(this.operand3, TypeScript.TokenID.Question, false); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return ConditionalExpression; + })(Expression); + TypeScript.ConditionalExpression = ConditionalExpression; + var NumberLiteral = (function (_super) { + __extends(NumberLiteral, _super); + function NumberLiteral(value, text) { + _super.call(this, TypeScript.NodeType.NumberLit); + this.value = value; + this.text = text; + } + NumberLiteral.prototype.typeCheck = function (typeFlow) { + this.type = typeFlow.doubleType; + return this; + }; + NumberLiteral.prototype.treeViewLabel = function () { + return "num: " + this.printLabel(); + }; + NumberLiteral.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput(this.text); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + NumberLiteral.prototype.printLabel = function () { + return this.text; + }; + return NumberLiteral; + })(Expression); + TypeScript.NumberLiteral = NumberLiteral; + var RegexLiteral = (function (_super) { + __extends(RegexLiteral, _super); + function RegexLiteral(text) { + _super.call(this, TypeScript.NodeType.Regex); + this.text = text; + } + RegexLiteral.prototype.typeCheck = function (typeFlow) { + this.type = typeFlow.regexType; + return this; + }; + RegexLiteral.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput(this.text); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return RegexLiteral; + })(Expression); + TypeScript.RegexLiteral = RegexLiteral; + var StringLiteral = (function (_super) { + __extends(StringLiteral, _super); + function StringLiteral(text) { + _super.call(this, TypeScript.NodeType.QString); + this.text = text; + } + StringLiteral.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.emitStringLiteral(this.text); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + StringLiteral.prototype.typeCheck = function (typeFlow) { + this.type = typeFlow.stringType; + return this; + }; + StringLiteral.prototype.treeViewLabel = function () { + return "st: " + this.text; + }; + StringLiteral.prototype.printLabel = function () { + return this.text; + }; + return StringLiteral; + })(Expression); + TypeScript.StringLiteral = StringLiteral; + var ModuleElement = (function (_super) { + __extends(ModuleElement, _super); + function ModuleElement(nodeType) { + _super.call(this, nodeType); + } + return ModuleElement; + })(AST); + TypeScript.ModuleElement = ModuleElement; + var ImportDeclaration = (function (_super) { + __extends(ImportDeclaration, _super); + function ImportDeclaration(id, alias) { + _super.call(this, TypeScript.NodeType.ImportDeclaration); + this.id = id; + this.alias = alias; + this.varFlags = TypeScript.VarFlags.None; + this.isDynamicImport = false; + } + ImportDeclaration.prototype.isStatementOrExpression = function () { + return true; + }; + ImportDeclaration.prototype.isDeclaration = function () { + return true; + }; + ImportDeclaration.prototype.emit = function (emitter, tokenId, startLine) { + var mod = this.alias.type; + if(!this.isDynamicImport || (this.id.sym && !(this.id.sym).onlyReferencedAsTypeRef)) { + var prevModAliasId = emitter.modAliasId; + var prevFirstModAlias = emitter.firstModAlias; + emitter.recordSourceMappingStart(this); + emitter.emitParensAndCommentsInPlace(this, true); + emitter.writeToOutput("var " + this.id.actualText + " = "); + emitter.modAliasId = this.id.actualText; + emitter.firstModAlias = this.firstAliasedModToString(); + emitter.emitJavascript(this.alias, TypeScript.TokenID.Tilde, false); + if(!this.isDynamicImport) { + emitter.writeToOutput(";"); + } + emitter.emitParensAndCommentsInPlace(this, false); + emitter.recordSourceMappingEnd(this); + emitter.modAliasId = prevModAliasId; + emitter.firstModAlias = prevFirstModAlias; + } + }; + ImportDeclaration.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckImportDecl(this); + }; + ImportDeclaration.prototype.getAliasName = function (aliasAST) { + if (typeof aliasAST === "undefined") { aliasAST = this.alias; } + if(aliasAST.nodeType == TypeScript.NodeType.Name) { + return (aliasAST).actualText; + } else { + var dotExpr = aliasAST; + return this.getAliasName(dotExpr.operand1) + "." + this.getAliasName(dotExpr.operand2); + } + }; + ImportDeclaration.prototype.firstAliasedModToString = function () { + if(this.alias.nodeType == TypeScript.NodeType.Name) { + return (this.alias).actualText; + } else { + var dotExpr = this.alias; + var firstMod = dotExpr.operand1; + return firstMod.actualText; + } + }; + return ImportDeclaration; + })(ModuleElement); + TypeScript.ImportDeclaration = ImportDeclaration; + var BoundDecl = (function (_super) { + __extends(BoundDecl, _super); + function BoundDecl(id, nodeType, nestingLevel) { + _super.call(this, nodeType); + this.id = id; + this.nestingLevel = nestingLevel; + this.init = null; + this.typeExpr = null; + this.varFlags = TypeScript.VarFlags.None; + this.sym = null; + } + BoundDecl.prototype.isDeclaration = function () { + return true; + }; + BoundDecl.prototype.isStatementOrExpression = function () { + return true; + }; + BoundDecl.prototype.isPrivate = function () { + return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Private); + }; + BoundDecl.prototype.isPublic = function () { + return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Public); + }; + BoundDecl.prototype.isProperty = function () { + return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Property); + }; + BoundDecl.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckBoundDecl(this); + }; + BoundDecl.prototype.printLabel = function () { + return this.treeViewLabel(); + }; + return BoundDecl; + })(AST); + TypeScript.BoundDecl = BoundDecl; + var VarDecl = (function (_super) { + __extends(VarDecl, _super); + function VarDecl(id, nest) { + _super.call(this, id, TypeScript.NodeType.VarDecl, nest); + } + VarDecl.prototype.isAmbient = function () { + return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Ambient); + }; + VarDecl.prototype.isExported = function () { + return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Exported); + }; + VarDecl.prototype.isStatic = function () { + return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Static); + }; + VarDecl.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitJavascriptVarDecl(this, tokenId); + }; + VarDecl.prototype.treeViewLabel = function () { + return "var " + this.id.actualText; + }; + return VarDecl; + })(BoundDecl); + TypeScript.VarDecl = VarDecl; + var ArgDecl = (function (_super) { + __extends(ArgDecl, _super); + function ArgDecl(id) { + _super.call(this, id, TypeScript.NodeType.ArgDecl, 0); + this.isOptional = false; + this.parameterPropertySym = null; + } + ArgDecl.prototype.isOptionalArg = function () { + return this.isOptional || this.init; + }; + ArgDecl.prototype.treeViewLabel = function () { + return "arg: " + this.id.actualText; + }; + ArgDecl.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput(this.id.actualText); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return ArgDecl; + })(BoundDecl); + TypeScript.ArgDecl = ArgDecl; + var internalId = 0; + var FuncDecl = (function (_super) { + __extends(FuncDecl, _super); + function FuncDecl(name, bod, isConstructor, arguments, vars, scopes, statics, nodeType) { + _super.call(this, nodeType); + this.name = name; + this.bod = bod; + this.isConstructor = isConstructor; + this.arguments = arguments; + this.vars = vars; + this.scopes = scopes; + this.statics = statics; + this.hint = null; + this.fncFlags = TypeScript.FncFlags.None; + this.returnTypeAnnotation = null; + this.variableArgList = false; + this.jumpRefs = null; + this.internalNameCache = null; + this.tmp1Declared = false; + this.enclosingFnc = null; + this.freeVariables = []; + this.unitIndex = -1; + this.classDecl = null; + this.boundToProperty = null; + this.isOverload = false; + this.innerStaticFuncs = []; + this.isInlineCallLiteral = false; + this.accessorSymbol = null; + this.leftCurlyCount = 0; + this.rightCurlyCount = 0; + this.returnStatementsWithExpressions = []; + this.scopeType = null; + this.endingToken = null; + this.constructorSpan = null; + } + FuncDecl.prototype.isDeclaration = function () { + return true; + }; + FuncDecl.prototype.internalName = function () { + if(this.internalNameCache == null) { + var extName = this.getNameText(); + if(extName) { + this.internalNameCache = "_internal_" + extName; + } else { + this.internalNameCache = "_internal_" + internalId++; + } + } + return this.internalNameCache; + }; + FuncDecl.prototype.hasSelfReference = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.HasSelfReference); + }; + FuncDecl.prototype.setHasSelfReference = function () { + this.fncFlags |= TypeScript.FncFlags.HasSelfReference; + }; + FuncDecl.prototype.hasSuperReferenceInFatArrowFunction = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.HasSuperReferenceInFatArrowFunction); + }; + FuncDecl.prototype.setHasSuperReferenceInFatArrowFunction = function () { + this.fncFlags |= TypeScript.FncFlags.HasSuperReferenceInFatArrowFunction; + }; + FuncDecl.prototype.addCloRef = function (id, sym) { + if(this.envids == null) { + this.envids = new Array(); + } + this.envids[this.envids.length] = id; + var outerFnc = this.enclosingFnc; + if(sym) { + while(outerFnc && (outerFnc.type.symbol != sym.container)) { + outerFnc.addJumpRef(sym); + outerFnc = outerFnc.enclosingFnc; + } + } + return this.envids.length - 1; + }; + FuncDecl.prototype.addJumpRef = function (sym) { + if(this.jumpRefs == null) { + this.jumpRefs = new Array(); + } + var id = new Identifier(sym.name); + this.jumpRefs[this.jumpRefs.length] = id; + id.sym = sym; + id.cloId = this.addCloRef(id, null); + }; + FuncDecl.prototype.buildControlFlow = function () { + var entry = new TypeScript.BasicBlock(); + var exit = new TypeScript.BasicBlock(); + var context = new TypeScript.ControlFlowContext(entry, exit); + var controlFlowPrefix = function (ast, parent, walker) { + ast.addToControlFlow(walker.state); + return ast; + }; + var walker = TypeScript.getAstWalkerFactory().getWalker(controlFlowPrefix, null, null, context); + context.walker = walker; + walker.walk(this.bod, this); + return context; + }; + FuncDecl.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckFunction(this); + }; + FuncDecl.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitJavascriptFunction(this); + }; + FuncDecl.prototype.getNameText = function () { + if(this.name) { + return this.name.actualText; + } else { + return this.hint; + } + }; + FuncDecl.prototype.isMethod = function () { + return (this.fncFlags & TypeScript.FncFlags.Method) != TypeScript.FncFlags.None; + }; + FuncDecl.prototype.isCallMember = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.CallMember); + }; + FuncDecl.prototype.isConstructMember = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.ConstructMember); + }; + FuncDecl.prototype.isIndexerMember = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.IndexerMember); + }; + FuncDecl.prototype.isSpecialFn = function () { + return this.isCallMember() || this.isIndexerMember() || this.isConstructMember(); + }; + FuncDecl.prototype.isAnonymousFn = function () { + return this.name === null; + }; + FuncDecl.prototype.isAccessor = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.GetAccessor) || TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.SetAccessor); + }; + FuncDecl.prototype.isGetAccessor = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.GetAccessor); + }; + FuncDecl.prototype.isSetAccessor = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.SetAccessor); + }; + FuncDecl.prototype.isAmbient = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Ambient); + }; + FuncDecl.prototype.isExported = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Exported); + }; + FuncDecl.prototype.isPrivate = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Private); + }; + FuncDecl.prototype.isPublic = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Public); + }; + FuncDecl.prototype.isStatic = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Static); + }; + FuncDecl.prototype.treeViewLabel = function () { + if(this.name == null) { + return "funcExpr"; + } else { + return "func: " + this.name.actualText; + } + }; + FuncDecl.prototype.ClearFlags = function () { + this.fncFlags = TypeScript.FncFlags.None; + }; + FuncDecl.prototype.isSignature = function () { + return (this.fncFlags & TypeScript.FncFlags.Signature) != TypeScript.FncFlags.None; + }; + return FuncDecl; + })(AST); + TypeScript.FuncDecl = FuncDecl; + var LocationInfo = (function () { + function LocationInfo(filename, lineMap, unitIndex) { + this.filename = filename; + this.lineMap = lineMap; + this.unitIndex = unitIndex; + } + return LocationInfo; + })(); + TypeScript.LocationInfo = LocationInfo; + TypeScript.unknownLocationInfo = new LocationInfo("unknown", null, -1); + var Script = (function (_super) { + __extends(Script, _super); + function Script(vars, scopes) { + _super.call(this, new Identifier("script"), null, false, null, vars, scopes, null, TypeScript.NodeType.Script); + this.locationInfo = null; + this.referencedFiles = []; + this.requiresGlobal = false; + this.requiresExtendsBlock = false; + this.isResident = false; + this.isDeclareFile = false; + this.hasBeenTypeChecked = false; + this.topLevelMod = null; + this.leftCurlyCount = 0; + this.rightCurlyCount = 0; + this.containsUnicodeChar = false; + this.containsUnicodeCharInComment = false; + this.externallyVisibleImportedSymbols = []; + this.vars = vars; + } + Script.prototype.setCachedEmitRequired = function (value) { + this.cachedEmitRequired = value; + return this.cachedEmitRequired; + }; + Script.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckScript(this); + }; + Script.prototype.treeViewLabel = function () { + return "Script"; + }; + Script.prototype.emitRequired = function (emitOptions) { + if(this.cachedEmitRequired != undefined) { + return this.cachedEmitRequired; + } + if(!this.isDeclareFile && !this.isResident && this.bod) { + if(this.bod.members.length == 0) { + return this.setCachedEmitRequired(true); + } + for(var i = 0, len = this.bod.members.length; i < len; i++) { + var stmt = this.bod.members[i]; + if(stmt.nodeType == TypeScript.NodeType.ModuleDeclaration) { + if(!TypeScript.hasFlag((stmt).modFlags, TypeScript.ModuleFlags.ShouldEmitModuleDecl | TypeScript.ModuleFlags.Ambient)) { + return this.setCachedEmitRequired(true); + } + } else if(stmt.nodeType == TypeScript.NodeType.ClassDeclaration) { + if(!TypeScript.hasFlag((stmt).varFlags, TypeScript.VarFlags.Ambient)) { + return this.setCachedEmitRequired(true); + } + } else if(stmt.nodeType == TypeScript.NodeType.VarDecl) { + if(!TypeScript.hasFlag((stmt).varFlags, TypeScript.VarFlags.Ambient)) { + return this.setCachedEmitRequired(true); + } + } else if(stmt.nodeType == TypeScript.NodeType.FuncDecl) { + if(!(stmt).isSignature()) { + return this.setCachedEmitRequired(true); + } + } else if(stmt.nodeType != TypeScript.NodeType.InterfaceDeclaration && stmt.nodeType != TypeScript.NodeType.Empty) { + return this.setCachedEmitRequired(true); + } + } + if(emitOptions.emitComments && ((this.bod.preComments && this.bod.preComments.length > 0) || (this.bod.postComments && this.bod.postComments.length > 0))) { + return this.setCachedEmitRequired(true); + } + } + return this.setCachedEmitRequired(false); + }; + Script.prototype.emit = function (emitter, tokenId, startLine) { + if(this.emitRequired(emitter.emitOptions)) { + emitter.emitJavascriptList(this.bod, null, TypeScript.TokenID.Semicolon, true, false, false, true, this.requiresExtendsBlock); + } + }; + Script.prototype.AddExternallyVisibleImportedSymbol = function (symbol, checker) { + if(this.isExternallyVisibleSymbol(symbol)) { + return; + } + if(!symbol.getType().symbol.isExternallyVisible(checker)) { + var quotes = ""; + var moduleName = symbol.getType().symbol.prettyName; + if(!TypeScript.isQuoted(moduleName)) { + quotes = "'"; + } + checker.errorReporter.simpleError(symbol.declAST, "Externally visible import statement uses non exported module " + quotes + moduleName + quotes); + } + this.externallyVisibleImportedSymbols.push(symbol); + }; + Script.prototype.isExternallyVisibleSymbol = function (symbol) { + for(var i = 0; i < this.externallyVisibleImportedSymbols.length; i++) { + if(this.externallyVisibleImportedSymbols[i] == symbol) { + return true; + } + } + return false; + }; + return Script; + })(FuncDecl); + TypeScript.Script = Script; + var NamedDeclaration = (function (_super) { + __extends(NamedDeclaration, _super); + function NamedDeclaration(nodeType, name, members) { + _super.call(this, nodeType); + this.name = name; + this.members = members; + this.leftCurlyCount = 0; + this.rightCurlyCount = 0; + } + NamedDeclaration.prototype.isDeclaration = function () { + return true; + }; + return NamedDeclaration; + })(ModuleElement); + TypeScript.NamedDeclaration = NamedDeclaration; + var ModuleDeclaration = (function (_super) { + __extends(ModuleDeclaration, _super); + function ModuleDeclaration(name, members, vars, endingToken) { + _super.call(this, TypeScript.NodeType.ModuleDeclaration, name, members); + this.endingToken = endingToken; + this.modFlags = TypeScript.ModuleFlags.ShouldEmitModuleDecl; + this.amdDependencies = []; + this.containsUnicodeChar = false; + this.containsUnicodeCharInComment = false; + this.vars = vars; + this.prettyName = this.name.actualText; + } + ModuleDeclaration.prototype.isExported = function () { + return TypeScript.hasFlag(this.modFlags, TypeScript.ModuleFlags.Exported); + }; + ModuleDeclaration.prototype.isAmbient = function () { + return TypeScript.hasFlag(this.modFlags, TypeScript.ModuleFlags.Ambient); + }; + ModuleDeclaration.prototype.isEnum = function () { + return TypeScript.hasFlag(this.modFlags, TypeScript.ModuleFlags.IsEnum); + }; + ModuleDeclaration.prototype.isWholeFile = function () { + return TypeScript.hasFlag(this.modFlags, TypeScript.ModuleFlags.IsWholeFile); + }; + ModuleDeclaration.prototype.recordNonInterface = function () { + this.modFlags &= ~TypeScript.ModuleFlags.ShouldEmitModuleDecl; + }; + ModuleDeclaration.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckModule(this); + }; + ModuleDeclaration.prototype.emit = function (emitter, tokenId, startLine) { + if(!TypeScript.hasFlag(this.modFlags, TypeScript.ModuleFlags.ShouldEmitModuleDecl)) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.emitJavascriptModule(this); + emitter.emitParensAndCommentsInPlace(this, false); + } + }; + return ModuleDeclaration; + })(NamedDeclaration); + TypeScript.ModuleDeclaration = ModuleDeclaration; + var TypeDeclaration = (function (_super) { + __extends(TypeDeclaration, _super); + function TypeDeclaration(nodeType, name, extendsList, implementsList, members) { + _super.call(this, nodeType, name, members); + this.extendsList = extendsList; + this.implementsList = implementsList; + this.varFlags = TypeScript.VarFlags.None; + } + TypeDeclaration.prototype.isExported = function () { + return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Exported); + }; + TypeDeclaration.prototype.isAmbient = function () { + return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Ambient); + }; + return TypeDeclaration; + })(NamedDeclaration); + TypeScript.TypeDeclaration = TypeDeclaration; + var ClassDeclaration = (function (_super) { + __extends(ClassDeclaration, _super); + function ClassDeclaration(name, members, extendsList, implementsList) { + _super.call(this, TypeScript.NodeType.ClassDeclaration, name, extendsList, implementsList, members); + this.knownMemberNames = { + }; + this.constructorDecl = null; + this.constructorNestingLevel = 0; + this.endingToken = null; + } + ClassDeclaration.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckClass(this); + }; + ClassDeclaration.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitJavascriptClass(this); + }; + return ClassDeclaration; + })(TypeDeclaration); + TypeScript.ClassDeclaration = ClassDeclaration; + var InterfaceDeclaration = (function (_super) { + __extends(InterfaceDeclaration, _super); + function InterfaceDeclaration(name, members, extendsList, implementsList) { + _super.call(this, TypeScript.NodeType.InterfaceDeclaration, name, extendsList, implementsList, members); + } + InterfaceDeclaration.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckInterface(this); + }; + InterfaceDeclaration.prototype.emit = function (emitter, tokenId, startLine) { + }; + return InterfaceDeclaration; + })(TypeDeclaration); + TypeScript.InterfaceDeclaration = InterfaceDeclaration; + var Statement = (function (_super) { + __extends(Statement, _super); + function Statement(nodeType) { + _super.call(this, nodeType); + this.flags |= TypeScript.ASTFlags.IsStatement; + } + Statement.prototype.isLoop = function () { + return false; + }; + Statement.prototype.isStatementOrExpression = function () { + return true; + }; + Statement.prototype.isCompoundStatement = function () { + return this.isLoop(); + }; + Statement.prototype.typeCheck = function (typeFlow) { + this.type = typeFlow.voidType; + return this; + }; + return Statement; + })(ModuleElement); + TypeScript.Statement = Statement; + var LabeledStatement = (function (_super) { + __extends(LabeledStatement, _super); + function LabeledStatement(labels, stmt) { + _super.call(this, TypeScript.NodeType.LabeledStatement); + this.labels = labels; + this.stmt = stmt; + } + LabeledStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + if(this.labels) { + var labelsLen = this.labels.members.length; + for(var i = 0; i < labelsLen; i++) { + this.labels.members[i].emit(emitter, tokenId, startLine); + } + } + this.stmt.emit(emitter, tokenId, true); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + LabeledStatement.prototype.typeCheck = function (typeFlow) { + typeFlow.typeCheck(this.labels); + this.stmt = this.stmt.typeCheck(typeFlow); + return this; + }; + LabeledStatement.prototype.addToControlFlow = function (context) { + var beforeBB = context.current; + var bb = new TypeScript.BasicBlock(); + context.current = bb; + beforeBB.addSuccessor(bb); + }; + return LabeledStatement; + })(Statement); + TypeScript.LabeledStatement = LabeledStatement; + var Block = (function (_super) { + __extends(Block, _super); + function Block(statements, isStatementBlock) { + _super.call(this, TypeScript.NodeType.Block); + this.statements = statements; + this.isStatementBlock = isStatementBlock; + } + Block.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + if(this.isStatementBlock) { + emitter.writeLineToOutput(" {"); + emitter.indenter.increaseIndent(); + } else { + emitter.setInVarBlock(this.statements.members.length); + } + var temp = emitter.setInObjectLiteral(false); + if(this.statements) { + emitter.emitJavascriptList(this.statements, null, TypeScript.TokenID.Semicolon, true, false, false); + } + if(this.isStatementBlock) { + emitter.indenter.decreaseIndent(); + emitter.emitIndent(); + emitter.writeToOutput("}"); + } + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + Block.prototype.addToControlFlow = function (context) { + var afterIfNeeded = new TypeScript.BasicBlock(); + context.pushStatement(this, context.current, afterIfNeeded); + if(this.statements) { + context.walk(this.statements, this); + } + context.walker.options.goChildren = false; + context.popStatement(); + if(afterIfNeeded.predecessors.length > 0) { + context.current.addSuccessor(afterIfNeeded); + context.current = afterIfNeeded; + } + }; + Block.prototype.typeCheck = function (typeFlow) { + if(!typeFlow.checker.styleSettings.emptyBlocks) { + if((this.statements === null) || (this.statements.members.length == 0)) { + typeFlow.checker.errorReporter.styleError(this, "empty block"); + } + } + typeFlow.typeCheck(this.statements); + return this; + }; + return Block; + })(Statement); + TypeScript.Block = Block; + var Jump = (function (_super) { + __extends(Jump, _super); + function Jump(nodeType) { + _super.call(this, nodeType); + this.target = null; + this.resolvedTarget = null; + } + Jump.prototype.hasExplicitTarget = function () { + return (this.target); + }; + Jump.prototype.setResolvedTarget = function (parser, stmt) { + if(stmt.isLoop()) { + this.resolvedTarget = stmt; + return true; + } + if(this.nodeType === TypeScript.NodeType.Continue) { + parser.reportParseError("continue statement applies only to loops"); + return false; + } else { + if((stmt.nodeType == TypeScript.NodeType.Switch) || this.hasExplicitTarget()) { + this.resolvedTarget = stmt; + return true; + } else { + parser.reportParseError("break statement with no label can apply only to a loop or switch statement"); + return false; + } + } + }; + Jump.prototype.addToControlFlow = function (context) { + _super.prototype.addToControlFlow.call(this, context); + context.unconditionalBranch(this.resolvedTarget, (this.nodeType == TypeScript.NodeType.Continue)); + }; + Jump.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + if(this.nodeType == TypeScript.NodeType.Break) { + emitter.writeToOutput("break"); + } else { + emitter.writeToOutput("continue"); + } + if(this.hasExplicitTarget()) { + emitter.writeToOutput(" " + this.target); + } + emitter.recordSourceMappingEnd(this); + emitter.writeToOutput(";"); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return Jump; + })(Statement); + TypeScript.Jump = Jump; + var WhileStatement = (function (_super) { + __extends(WhileStatement, _super); + function WhileStatement(cond) { + _super.call(this, TypeScript.NodeType.While); + this.cond = cond; + this.body = null; + } + WhileStatement.prototype.isLoop = function () { + return true; + }; + WhileStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + emitter.writeToOutput("while("); + emitter.emitJavascript(this.cond, TypeScript.TokenID.While, false); + emitter.writeToOutput(")"); + emitter.emitJavascriptStatements(this.body, false); + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + WhileStatement.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckWhile(this); + }; + WhileStatement.prototype.addToControlFlow = function (context) { + var loopHeader = context.current; + var loopStart = new TypeScript.BasicBlock(); + var afterLoop = new TypeScript.BasicBlock(); + loopHeader.addSuccessor(loopStart); + context.current = loopStart; + context.addContent(this.cond); + var condBlock = context.current; + var targetInfo = null; + if(this.body) { + context.current = new TypeScript.BasicBlock(); + condBlock.addSuccessor(context.current); + context.pushStatement(this, loopStart, afterLoop); + context.walk(this.body, this); + targetInfo = context.popStatement(); + } + if(!(context.noContinuation)) { + var loopEnd = context.current; + loopEnd.addSuccessor(loopStart); + } + context.current = afterLoop; + condBlock.addSuccessor(afterLoop); + context.noContinuation = false; + context.walker.options.goChildren = false; + }; + return WhileStatement; + })(Statement); + TypeScript.WhileStatement = WhileStatement; + var DoWhileStatement = (function (_super) { + __extends(DoWhileStatement, _super); + function DoWhileStatement() { + _super.call(this, TypeScript.NodeType.DoWhile); + this.body = null; + this.whileAST = null; + this.cond = null; + } + DoWhileStatement.prototype.isLoop = function () { + return true; + }; + DoWhileStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + emitter.writeToOutput("do"); + emitter.emitJavascriptStatements(this.body, true); + emitter.recordSourceMappingStart(this.whileAST); + emitter.writeToOutput("while"); + emitter.recordSourceMappingEnd(this.whileAST); + emitter.writeToOutput('('); + emitter.emitJavascript(this.cond, TypeScript.TokenID.CloseParen, false); + emitter.writeToOutput(")"); + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.writeToOutput(";"); + emitter.emitParensAndCommentsInPlace(this, false); + }; + DoWhileStatement.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckDoWhile(this); + }; + DoWhileStatement.prototype.addToControlFlow = function (context) { + var loopHeader = context.current; + var loopStart = new TypeScript.BasicBlock(); + var afterLoop = new TypeScript.BasicBlock(); + loopHeader.addSuccessor(loopStart); + context.current = loopStart; + var targetInfo = null; + if(this.body) { + context.pushStatement(this, loopStart, afterLoop); + context.walk(this.body, this); + targetInfo = context.popStatement(); + } + if(!(context.noContinuation)) { + var loopEnd = context.current; + loopEnd.addSuccessor(loopStart); + context.addContent(this.cond); + context.current = afterLoop; + loopEnd.addSuccessor(afterLoop); + } else { + context.addUnreachable(this.cond); + } + context.walker.options.goChildren = false; + }; + return DoWhileStatement; + })(Statement); + TypeScript.DoWhileStatement = DoWhileStatement; + var IfStatement = (function (_super) { + __extends(IfStatement, _super); + function IfStatement(cond) { + _super.call(this, TypeScript.NodeType.If); + this.cond = cond; + this.elseBod = null; + this.statement = new ASTSpan(); + } + IfStatement.prototype.isCompoundStatement = function () { + return true; + }; + IfStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + emitter.recordSourceMappingStart(this.statement); + emitter.writeToOutput("if("); + emitter.emitJavascript(this.cond, TypeScript.TokenID.If, false); + emitter.writeToOutput(")"); + emitter.recordSourceMappingEnd(this.statement); + emitter.emitJavascriptStatements(this.thenBod, true); + if(this.elseBod) { + if(this.elseBod.nodeType === TypeScript.NodeType.If) { + emitter.writeToOutput(" else "); + this.elseBod.emit(emitter, tokenId, false); + } else { + emitter.writeToOutput(" else"); + emitter.emitJavascriptStatements(this.elseBod, true); + } + } + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + IfStatement.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckIf(this); + }; + IfStatement.prototype.addToControlFlow = function (context) { + this.cond.addToControlFlow(context); + var afterIf = new TypeScript.BasicBlock(); + var beforeIf = context.current; + context.pushStatement(this, beforeIf, afterIf); + var hasContinuation = false; + context.current = new TypeScript.BasicBlock(); + beforeIf.addSuccessor(context.current); + context.walk(this.thenBod, this); + if(!context.noContinuation) { + hasContinuation = true; + context.current.addSuccessor(afterIf); + } + if(this.elseBod) { + context.current = new TypeScript.BasicBlock(); + context.noContinuation = false; + beforeIf.addSuccessor(context.current); + context.walk(this.elseBod, this); + if(!context.noContinuation) { + hasContinuation = true; + context.current.addSuccessor(afterIf); + } else { + if(hasContinuation) { + context.noContinuation = false; + } + } + } else { + beforeIf.addSuccessor(afterIf); + context.noContinuation = false; + hasContinuation = true; + } + var targetInfo = context.popStatement(); + if(afterIf.predecessors.length > 0) { + context.noContinuation = false; + hasContinuation = true; + } + if(hasContinuation) { + context.current = afterIf; + } + context.walker.options.goChildren = false; + }; + return IfStatement; + })(Statement); + TypeScript.IfStatement = IfStatement; + var ReturnStatement = (function (_super) { + __extends(ReturnStatement, _super); + function ReturnStatement() { + _super.call(this, TypeScript.NodeType.Return); + this.returnExpression = null; + } + ReturnStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + if(this.returnExpression) { + emitter.writeToOutput("return "); + emitter.emitJavascript(this.returnExpression, TypeScript.TokenID.Semicolon, false); + if(this.returnExpression.nodeType === TypeScript.NodeType.FuncDecl) { + emitter.writeToOutput(";"); + } + } else { + emitter.writeToOutput("return;"); + } + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + ReturnStatement.prototype.addToControlFlow = function (context) { + _super.prototype.addToControlFlow.call(this, context); + context.returnStmt(); + }; + ReturnStatement.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckReturn(this); + }; + return ReturnStatement; + })(Statement); + TypeScript.ReturnStatement = ReturnStatement; + var EndCode = (function (_super) { + __extends(EndCode, _super); + function EndCode() { + _super.call(this, TypeScript.NodeType.EndCode); + } + return EndCode; + })(AST); + TypeScript.EndCode = EndCode; + var ForInStatement = (function (_super) { + __extends(ForInStatement, _super); + function ForInStatement(lval, obj) { + _super.call(this, TypeScript.NodeType.ForIn); + this.lval = lval; + this.obj = obj; + this.statement = new ASTSpan(); + if(this.lval && (this.lval.nodeType == TypeScript.NodeType.VarDecl)) { + (this.lval).varFlags |= TypeScript.VarFlags.AutoInit; + } + } + ForInStatement.prototype.isLoop = function () { + return true; + }; + ForInStatement.prototype.isFiltered = function () { + if(this.body) { + var singleItem = null; + if(this.body.nodeType == TypeScript.NodeType.List) { + var stmts = this.body; + if(stmts.members.length == 1) { + singleItem = stmts.members[0]; + } + } else { + singleItem = this.body; + } + if(singleItem !== null) { + if(singleItem.nodeType == TypeScript.NodeType.Block) { + var block = singleItem; + if((block.statements !== null) && (block.statements.members.length == 1)) { + singleItem = block.statements.members[0]; + } + } + if(singleItem.nodeType == TypeScript.NodeType.If) { + var cond = (singleItem).cond; + if(cond.nodeType == TypeScript.NodeType.Call) { + var target = (cond).target; + if(target.nodeType == TypeScript.NodeType.Dot) { + var binex = target; + if((binex.operand1.nodeType == TypeScript.NodeType.Name) && (this.obj.nodeType == TypeScript.NodeType.Name) && ((binex.operand1).actualText == (this.obj).actualText)) { + var prop = binex.operand2; + if(prop.actualText == "hasOwnProperty") { + var args = (cond).arguments; + if((args !== null) && (args.members.length == 1)) { + var arg = args.members[0]; + if((arg.nodeType == TypeScript.NodeType.Name) && (this.lval.nodeType == TypeScript.NodeType.Name)) { + if(((this.lval).actualText) == (arg).actualText) { + return true; + } + } + } + } + } + } + } + } + } + } + return false; + }; + ForInStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + emitter.recordSourceMappingStart(this.statement); + emitter.writeToOutput("for("); + emitter.emitJavascript(this.lval, TypeScript.TokenID.For, false); + emitter.writeToOutput(" in "); + emitter.emitJavascript(this.obj, TypeScript.TokenID.For, false); + emitter.writeToOutput(")"); + emitter.recordSourceMappingEnd(this.statement); + emitter.emitJavascriptStatements(this.body, true); + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + ForInStatement.prototype.typeCheck = function (typeFlow) { + if(typeFlow.checker.styleSettings.forin) { + if(!this.isFiltered()) { + typeFlow.checker.errorReporter.styleError(this, "no hasOwnProperty filter"); + } + } + return typeFlow.typeCheckForIn(this); + }; + ForInStatement.prototype.addToControlFlow = function (context) { + if(this.lval) { + context.addContent(this.lval); + } + if(this.obj) { + context.addContent(this.obj); + } + var loopHeader = context.current; + var loopStart = new TypeScript.BasicBlock(); + var afterLoop = new TypeScript.BasicBlock(); + loopHeader.addSuccessor(loopStart); + context.current = loopStart; + if(this.body) { + context.pushStatement(this, loopStart, afterLoop); + context.walk(this.body, this); + context.popStatement(); + } + if(!(context.noContinuation)) { + var loopEnd = context.current; + loopEnd.addSuccessor(loopStart); + } + context.current = afterLoop; + context.noContinuation = false; + loopHeader.addSuccessor(afterLoop); + context.walker.options.goChildren = false; + }; + return ForInStatement; + })(Statement); + TypeScript.ForInStatement = ForInStatement; + var ForStatement = (function (_super) { + __extends(ForStatement, _super); + function ForStatement(init) { + _super.call(this, TypeScript.NodeType.For); + this.init = init; + } + ForStatement.prototype.isLoop = function () { + return true; + }; + ForStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + emitter.writeToOutput("for("); + if(this.init) { + if(this.init.nodeType != TypeScript.NodeType.List) { + emitter.emitJavascript(this.init, TypeScript.TokenID.For, false); + } else { + emitter.setInVarBlock((this.init).members.length); + emitter.emitJavascriptList(this.init, null, TypeScript.TokenID.For, false, false, false); + } + } + emitter.writeToOutput("; "); + emitter.emitJavascript(this.cond, TypeScript.TokenID.For, false); + emitter.writeToOutput("; "); + emitter.emitJavascript(this.incr, TypeScript.TokenID.For, false); + emitter.writeToOutput(")"); + emitter.emitJavascriptStatements(this.body, true); + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + ForStatement.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckFor(this); + }; + ForStatement.prototype.addToControlFlow = function (context) { + if(this.init) { + context.addContent(this.init); + } + var loopHeader = context.current; + var loopStart = new TypeScript.BasicBlock(); + var afterLoop = new TypeScript.BasicBlock(); + loopHeader.addSuccessor(loopStart); + context.current = loopStart; + var condBlock = null; + var continueTarget = loopStart; + var incrBB = null; + if(this.incr) { + incrBB = new TypeScript.BasicBlock(); + continueTarget = incrBB; + } + if(this.cond) { + condBlock = context.current; + context.addContent(this.cond); + context.current = new TypeScript.BasicBlock(); + condBlock.addSuccessor(context.current); + } + var targetInfo = null; + if(this.body) { + context.pushStatement(this, continueTarget, afterLoop); + context.walk(this.body, this); + targetInfo = context.popStatement(); + } + if(this.incr) { + if(context.noContinuation) { + if(incrBB.predecessors.length == 0) { + context.addUnreachable(this.incr); + } + } else { + context.current.addSuccessor(incrBB); + context.current = incrBB; + context.addContent(this.incr); + } + } + var loopEnd = context.current; + if(!(context.noContinuation)) { + loopEnd.addSuccessor(loopStart); + } + if(condBlock) { + condBlock.addSuccessor(afterLoop); + context.noContinuation = false; + } + if(afterLoop.predecessors.length > 0) { + context.noContinuation = false; + context.current = afterLoop; + } + context.walker.options.goChildren = false; + }; + return ForStatement; + })(Statement); + TypeScript.ForStatement = ForStatement; + var WithStatement = (function (_super) { + __extends(WithStatement, _super); + function WithStatement(expr) { + _super.call(this, TypeScript.NodeType.With); + this.expr = expr; + this.withSym = null; + } + WithStatement.prototype.isCompoundStatement = function () { + return true; + }; + WithStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("with ("); + if(this.expr) { + emitter.emitJavascript(this.expr, TypeScript.TokenID.With, false); + } + emitter.writeToOutput(")"); + emitter.emitJavascriptStatements(this.body, true); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + WithStatement.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckWith(this); + }; + return WithStatement; + })(Statement); + TypeScript.WithStatement = WithStatement; + var SwitchStatement = (function (_super) { + __extends(SwitchStatement, _super); + function SwitchStatement(val) { + _super.call(this, TypeScript.NodeType.Switch); + this.val = val; + this.defaultCase = null; + this.statement = new ASTSpan(); + } + SwitchStatement.prototype.isCompoundStatement = function () { + return true; + }; + SwitchStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + emitter.recordSourceMappingStart(this.statement); + emitter.writeToOutput("switch("); + emitter.emitJavascript(this.val, TypeScript.TokenID.Identifier, false); + emitter.writeToOutput(")"); + emitter.recordSourceMappingEnd(this.statement); + emitter.writeLineToOutput(" {"); + emitter.indenter.increaseIndent(); + var casesLen = this.caseList.members.length; + for(var i = 0; i < casesLen; i++) { + var caseExpr = this.caseList.members[i]; + emitter.emitJavascript(caseExpr, TypeScript.TokenID.Case, true); + } + emitter.indenter.decreaseIndent(); + emitter.emitIndent(); + emitter.writeToOutput("}"); + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + SwitchStatement.prototype.typeCheck = function (typeFlow) { + var len = this.caseList.members.length; + this.val = typeFlow.typeCheck(this.val); + for(var i = 0; i < len; i++) { + this.caseList.members[i] = typeFlow.typeCheck(this.caseList.members[i]); + } + this.defaultCase = typeFlow.typeCheck(this.defaultCase); + this.type = typeFlow.voidType; + return this; + }; + SwitchStatement.prototype.addToControlFlow = function (context) { + var condBlock = context.current; + context.addContent(this.val); + var execBlock = new TypeScript.BasicBlock(); + var afterSwitch = new TypeScript.BasicBlock(); + condBlock.addSuccessor(execBlock); + context.pushSwitch(execBlock); + context.current = execBlock; + context.pushStatement(this, execBlock, afterSwitch); + context.walk(this.caseList, this); + context.popSwitch(); + var targetInfo = context.popStatement(); + var hasCondContinuation = (this.defaultCase == null); + if(this.defaultCase == null) { + condBlock.addSuccessor(afterSwitch); + } + if(afterSwitch.predecessors.length > 0) { + context.noContinuation = false; + context.current = afterSwitch; + } else { + context.noContinuation = true; + } + context.walker.options.goChildren = false; + }; + return SwitchStatement; + })(Statement); + TypeScript.SwitchStatement = SwitchStatement; + var CaseStatement = (function (_super) { + __extends(CaseStatement, _super); + function CaseStatement() { + _super.call(this, TypeScript.NodeType.Case); + this.expr = null; + this.colonSpan = new ASTSpan(); + } + CaseStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + if(this.expr) { + emitter.writeToOutput("case "); + emitter.emitJavascript(this.expr, TypeScript.TokenID.Identifier, false); + } else { + emitter.writeToOutput("default"); + } + emitter.recordSourceMappingStart(this.colonSpan); + emitter.writeToOutput(":"); + emitter.recordSourceMappingEnd(this.colonSpan); + if(this.body.members.length == 1 && this.body.members[0].nodeType == TypeScript.NodeType.Block) { + emitter.emitJavascriptStatements(this.body, false); + } else { + emitter.writeLineToOutput(""); + emitter.indenter.increaseIndent(); + emitter.emitBareJavascriptStatements(this.body); + emitter.indenter.decreaseIndent(); + } + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + CaseStatement.prototype.typeCheck = function (typeFlow) { + this.expr = typeFlow.typeCheck(this.expr); + typeFlow.typeCheck(this.body); + this.type = typeFlow.voidType; + return this; + }; + CaseStatement.prototype.addToControlFlow = function (context) { + var execBlock = new TypeScript.BasicBlock(); + var sw = context.currentSwitch[context.currentSwitch.length - 1]; + if(this.expr) { + var exprBlock = new TypeScript.BasicBlock(); + context.current = exprBlock; + sw.addSuccessor(exprBlock); + context.addContent(this.expr); + exprBlock.addSuccessor(execBlock); + } else { + sw.addSuccessor(execBlock); + } + context.current = execBlock; + if(this.body) { + context.walk(this.body, this); + } + context.noContinuation = false; + context.walker.options.goChildren = false; + }; + return CaseStatement; + })(Statement); + TypeScript.CaseStatement = CaseStatement; + var TypeReference = (function (_super) { + __extends(TypeReference, _super); + function TypeReference(term, arrayCount) { + _super.call(this, TypeScript.NodeType.TypeRef); + this.term = term; + this.arrayCount = arrayCount; + } + TypeReference.prototype.emit = function (emitter, tokenId, startLine) { + throw new Error("should not emit a type ref"); + }; + TypeReference.prototype.typeCheck = function (typeFlow) { + var prevInTCTR = typeFlow.inTypeRefTypeCheck; + typeFlow.inTypeRefTypeCheck = true; + var typeLink = TypeScript.getTypeLink(this, typeFlow.checker, true); + typeFlow.checker.resolveTypeLink(typeFlow.scope, typeLink, false); + if(this.term) { + typeFlow.typeCheck(this.term); + } + typeFlow.checkForVoidConstructor(typeLink.type, this); + this.type = typeLink.type; + if(this.term) { + this.term.type = this.type; + } + typeFlow.inTypeRefTypeCheck = prevInTCTR; + return this; + }; + return TypeReference; + })(AST); + TypeScript.TypeReference = TypeReference; + var TryFinally = (function (_super) { + __extends(TryFinally, _super); + function TryFinally(tryNode, finallyNode) { + _super.call(this, TypeScript.NodeType.TryFinally); + this.tryNode = tryNode; + this.finallyNode = finallyNode; + } + TryFinally.prototype.isCompoundStatement = function () { + return true; + }; + TryFinally.prototype.emit = function (emitter, tokenId, startLine) { + emitter.recordSourceMappingStart(this); + emitter.emitJavascript(this.tryNode, TypeScript.TokenID.Try, false); + emitter.emitJavascript(this.finallyNode, TypeScript.TokenID.Finally, false); + emitter.recordSourceMappingEnd(this); + }; + TryFinally.prototype.typeCheck = function (typeFlow) { + this.tryNode = typeFlow.typeCheck(this.tryNode); + this.finallyNode = typeFlow.typeCheck(this.finallyNode); + this.type = typeFlow.voidType; + return this; + }; + TryFinally.prototype.addToControlFlow = function (context) { + var afterFinally = new TypeScript.BasicBlock(); + context.walk(this.tryNode, this); + var finBlock = new TypeScript.BasicBlock(); + if(context.current) { + context.current.addSuccessor(finBlock); + } + context.current = finBlock; + context.pushStatement(this, null, afterFinally); + context.walk(this.finallyNode, this); + if(!context.noContinuation && context.current) { + context.current.addSuccessor(afterFinally); + } + if(afterFinally.predecessors.length > 0) { + context.current = afterFinally; + } else { + context.noContinuation = true; + } + context.popStatement(); + context.walker.options.goChildren = false; + }; + return TryFinally; + })(Statement); + TypeScript.TryFinally = TryFinally; + var TryCatch = (function (_super) { + __extends(TryCatch, _super); + function TryCatch(tryNode, catchNode) { + _super.call(this, TypeScript.NodeType.TryCatch); + this.tryNode = tryNode; + this.catchNode = catchNode; + } + TryCatch.prototype.isCompoundStatement = function () { + return true; + }; + TryCatch.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.emitJavascript(this.tryNode, TypeScript.TokenID.Try, false); + emitter.emitJavascript(this.catchNode, TypeScript.TokenID.Catch, false); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + TryCatch.prototype.addToControlFlow = function (context) { + var beforeTry = context.current; + var tryBlock = new TypeScript.BasicBlock(); + beforeTry.addSuccessor(tryBlock); + context.current = tryBlock; + var afterTryCatch = new TypeScript.BasicBlock(); + context.pushStatement(this, null, afterTryCatch); + context.walk(this.tryNode, this); + if(!context.noContinuation) { + if(context.current) { + context.current.addSuccessor(afterTryCatch); + } + } + context.current = new TypeScript.BasicBlock(); + beforeTry.addSuccessor(context.current); + context.walk(this.catchNode, this); + context.popStatement(); + if(!context.noContinuation) { + if(context.current) { + context.current.addSuccessor(afterTryCatch); + } + } + context.current = afterTryCatch; + context.walker.options.goChildren = false; + }; + TryCatch.prototype.typeCheck = function (typeFlow) { + this.tryNode = typeFlow.typeCheck(this.tryNode); + this.catchNode = typeFlow.typeCheck(this.catchNode); + this.type = typeFlow.voidType; + return this; + }; + return TryCatch; + })(Statement); + TypeScript.TryCatch = TryCatch; + var Try = (function (_super) { + __extends(Try, _super); + function Try(body) { + _super.call(this, TypeScript.NodeType.Try); + this.body = body; + } + Try.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("try "); + emitter.emitJavascript(this.body, TypeScript.TokenID.Try, false); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + Try.prototype.typeCheck = function (typeFlow) { + this.body = typeFlow.typeCheck(this.body); + return this; + }; + Try.prototype.addToControlFlow = function (context) { + if(this.body) { + context.walk(this.body, this); + } + context.walker.options.goChildren = false; + context.noContinuation = false; + }; + return Try; + })(Statement); + TypeScript.Try = Try; + var Catch = (function (_super) { + __extends(Catch, _super); + function Catch(param, body) { + _super.call(this, TypeScript.NodeType.Catch); + this.param = param; + this.body = body; + this.statement = new ASTSpan(); + this.containedScope = null; + if(this.param) { + this.param.varFlags |= TypeScript.VarFlags.AutoInit; + } + } + Catch.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput(" "); + emitter.recordSourceMappingStart(this.statement); + emitter.writeToOutput("catch ("); + emitter.emitJavascript(this.param, TypeScript.TokenID.OpenParen, false); + emitter.writeToOutput(")"); + emitter.recordSourceMappingEnd(this.statement); + emitter.emitJavascript(this.body, TypeScript.TokenID.Catch, false); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + Catch.prototype.addToControlFlow = function (context) { + if(this.param) { + context.addContent(this.param); + var bodBlock = new TypeScript.BasicBlock(); + context.current.addSuccessor(bodBlock); + context.current = bodBlock; + } + if(this.body) { + context.walk(this.body, this); + } + context.noContinuation = false; + context.walker.options.goChildren = false; + }; + Catch.prototype.typeCheck = function (typeFlow) { + var prevScope = typeFlow.scope; + typeFlow.scope = this.containedScope; + this.param = typeFlow.typeCheck(this.param); + var exceptVar = new TypeScript.ValueLocation(); + var varSym = new TypeScript.VariableSymbol((this.param).id.text, this.param.minChar, typeFlow.checker.locationInfo.unitIndex, exceptVar); + exceptVar.symbol = varSym; + exceptVar.typeLink = new TypeScript.TypeLink(); + exceptVar.typeLink.type = typeFlow.anyType; + var thisFnc = typeFlow.thisFnc; + if(thisFnc && thisFnc.type) { + exceptVar.symbol.container = thisFnc.type.symbol; + } else { + exceptVar.symbol.container = null; + } + this.param.sym = exceptVar.symbol; + typeFlow.scope.enter(exceptVar.symbol.container, this.param, exceptVar.symbol, typeFlow.checker.errorReporter, false, false, false); + this.body = typeFlow.typeCheck(this.body); + if(typeFlow.checker.inProvisionalTypecheckMode()) { + var table = typeFlow.scope.getTable(); + (table).secondaryTable.table[exceptVar.symbol.name] = undefined; + } + this.type = typeFlow.voidType; + typeFlow.scope = prevScope; + return this; + }; + return Catch; + })(Statement); + TypeScript.Catch = Catch; + var Finally = (function (_super) { + __extends(Finally, _super); + function Finally(body) { + _super.call(this, TypeScript.NodeType.Finally); + this.body = body; + } + Finally.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("finally"); + emitter.emitJavascript(this.body, TypeScript.TokenID.Finally, false); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + Finally.prototype.addToControlFlow = function (context) { + if(this.body) { + context.walk(this.body, this); + } + context.walker.options.goChildren = false; + context.noContinuation = false; + }; + Finally.prototype.typeCheck = function (typeFlow) { + this.body = typeFlow.typeCheck(this.body); + return this; + }; + return Finally; + })(Statement); + TypeScript.Finally = Finally; + var Comment = (function (_super) { + __extends(Comment, _super); + function Comment(content, isBlockComment, endsLine) { + _super.call(this, TypeScript.NodeType.Comment); + this.content = content; + this.isBlockComment = isBlockComment; + this.endsLine = endsLine; + this.text = null; + this.docCommentText = null; + } + Comment.prototype.getText = function () { + if(this.text == null) { + if(this.isBlockComment) { + this.text = this.content.split("\n"); + for(var i = 0; i < this.text.length; i++) { + this.text[i] = this.text[i].replace(/^\s+|\s+$/g, ''); + } + } else { + this.text = [ + (this.content.replace(/^\s+|\s+$/g, '')) + ]; + } + } + return this.text; + }; + Comment.prototype.isDocComment = function () { + if(this.isBlockComment) { + return this.content.charAt(2) == "*" && this.content.charAt(3) != "/"; + } + return false; + }; + Comment.prototype.getDocCommentText = function () { + if(this.docCommentText == null) { + this.docCommentText = Comment.cleanJSDocComment(this.content); + } + return this.docCommentText; + }; + Comment.consumeLeadingSpace = function consumeLeadingSpace(line, startIndex, maxSpacesToRemove) { + var endIndex = line.length; + if(maxSpacesToRemove != undefined) { + endIndex = TypeScript.min(startIndex + maxSpacesToRemove, endIndex); + } + for(; startIndex < endIndex; startIndex++) { + var charCode = line.charCodeAt(startIndex); + if(charCode != TypeScript.LexCodeSpace && charCode != TypeScript.LexCodeTAB) { + return startIndex; + } + } + if(endIndex != line.length) { + return endIndex; + } + return -1; + }; + Comment.isSpaceChar = function isSpaceChar(line, index) { + var length = line.length; + if(index < length) { + var charCode = line.charCodeAt(index); + return charCode == TypeScript.LexCodeSpace || charCode == TypeScript.LexCodeTAB; + } + return index == length; + }; + Comment.cleanDocCommentLine = function cleanDocCommentLine(line, jsDocStyleComment, jsDocLineSpaceToRemove) { + var nonSpaceIndex = Comment.consumeLeadingSpace(line, 0); + if(nonSpaceIndex != -1) { + var jsDocSpacesRemoved = nonSpaceIndex; + if(jsDocStyleComment && line.charAt(nonSpaceIndex) == '*') { + var startIndex = nonSpaceIndex + 1; + nonSpaceIndex = Comment.consumeLeadingSpace(line, startIndex, jsDocLineSpaceToRemove); + if(nonSpaceIndex != -1) { + jsDocSpacesRemoved = nonSpaceIndex - startIndex; + } else { + return null; + } + } + return { + minChar: nonSpaceIndex, + limChar: line.charAt(line.length - 1) == "\r" ? line.length - 1 : line.length, + jsDocSpacesRemoved: jsDocSpacesRemoved + }; + } + return null; + }; + Comment.cleanJSDocComment = function cleanJSDocComment(content, spacesToRemove) { + var docCommentLines = []; + content = content.replace("/**", ""); + if(content.length >= 2 && content.charAt(content.length - 1) == "/" && content.charAt(content.length - 2) == "*") { + content = content.substring(0, content.length - 2); + } + var lines = content.split("\n"); + var inParamTag = false; + for(var l = 0; l < lines.length; l++) { + var line = lines[l]; + var cleanLinePos = Comment.cleanDocCommentLine(line, true, spacesToRemove); + if(!cleanLinePos) { + continue; + } + var docCommentText = ""; + var prevPos = cleanLinePos.minChar; + for(var i = line.indexOf("@", cleanLinePos.minChar); 0 <= i && i < cleanLinePos.limChar; i = line.indexOf("@", i + 1)) { + var wasInParamtag = inParamTag; + if(line.indexOf("param", i + 1) == i + 1 && Comment.isSpaceChar(line, i + 6)) { + if(!wasInParamtag) { + docCommentText += line.substring(prevPos, i); + } + prevPos = i; + inParamTag = true; + } else if(wasInParamtag) { + prevPos = i; + inParamTag = false; + } + } + if(!inParamTag) { + docCommentText += line.substring(prevPos, cleanLinePos.limChar); + } + var newCleanPos = Comment.cleanDocCommentLine(docCommentText, false); + if(newCleanPos) { + if(spacesToRemove == undefined) { + spacesToRemove = cleanLinePos.jsDocSpacesRemoved; + } + docCommentLines.push(docCommentText); + } + } + return docCommentLines.join("\n"); + }; + Comment.getDocCommentText = function getDocCommentText(comments) { + var docCommentText = []; + for(var c = 0; c < comments.length; c++) { + var commentText = comments[c].getDocCommentText(); + if(commentText != "") { + docCommentText.push(commentText); + } + } + return docCommentText.join("\n"); + }; + Comment.getParameterDocCommentText = function getParameterDocCommentText(param, fncDocComments) { + if(fncDocComments.length == 0 || !fncDocComments[0].isBlockComment) { + return ""; + } + for(var i = 0; i < fncDocComments.length; i++) { + var commentContents = fncDocComments[i].content; + for(var j = commentContents.indexOf("@param", 0); 0 <= j; j = commentContents.indexOf("@param", j)) { + j += 6; + if(!Comment.isSpaceChar(commentContents, j)) { + continue; + } + j = Comment.consumeLeadingSpace(commentContents, j); + if(j == -1) { + break; + } + if(commentContents.charCodeAt(j) == TypeScript.LexCodeLC) { + j++; + var charCode = 0; + for(var curlies = 1; j < commentContents.length; j++) { + charCode = commentContents.charCodeAt(j); + if(charCode == TypeScript.LexCodeLC) { + curlies++; + continue; + } + if(charCode == TypeScript.LexCodeRC) { + curlies--; + if(curlies == 0) { + break; + } else { + continue; + } + } + if(charCode == TypeScript.LexCodeAtSign) { + break; + } + } + if(j == commentContents.length) { + break; + } + if(charCode == TypeScript.LexCodeAtSign) { + continue; + } + j = Comment.consumeLeadingSpace(commentContents, j + 1); + if(j == -1) { + break; + } + } + if(param != commentContents.substr(j, param.length) || !Comment.isSpaceChar(commentContents, j + param.length)) { + continue; + } + j = Comment.consumeLeadingSpace(commentContents, j + param.length); + if(j == -1) { + return ""; + } + var endOfParam = commentContents.indexOf("@", j); + var paramHelpString = commentContents.substring(j, endOfParam < 0 ? commentContents.length : endOfParam); + var paramSpacesToRemove = undefined; + var paramLineIndex = commentContents.substring(0, j).lastIndexOf("\n") + 1; + if(paramLineIndex != 0) { + if(paramLineIndex < j && commentContents.charAt(paramLineIndex + 1) == "\r") { + paramLineIndex++; + } + } + var startSpaceRemovalIndex = Comment.consumeLeadingSpace(commentContents, paramLineIndex); + if(startSpaceRemovalIndex != j && commentContents.charAt(startSpaceRemovalIndex) == "*") { + paramSpacesToRemove = j - startSpaceRemovalIndex - 1; + } + return Comment.cleanJSDocComment(paramHelpString, paramSpacesToRemove); + } + } + return ""; + }; + Comment.getDocCommentFirstOverloadSignature = function getDocCommentFirstOverloadSignature(signatureGroup) { + for(var i = 0; i < signatureGroup.signatures.length; i++) { + var signature = signatureGroup.signatures[i]; + if(signature == signatureGroup.definitionSignature) { + continue; + } + return TypeScript.Comment.getDocCommentText(signature.declAST.getDocComments()); + } + return ""; + }; + return Comment; + })(AST); + TypeScript.Comment = Comment; + var DebuggerStatement = (function (_super) { + __extends(DebuggerStatement, _super); + function DebuggerStatement() { + _super.call(this, TypeScript.NodeType.Debugger); + } + DebuggerStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("debugger"); + emitter.recordSourceMappingEnd(this); + emitter.writeLineToOutput(";"); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return DebuggerStatement; + })(Statement); + TypeScript.DebuggerStatement = DebuggerStatement; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var AstWalkOptions = (function () { + function AstWalkOptions() { + this.goChildren = true; + this.goNextSibling = true; + this.reverseSiblings = false; + } + AstWalkOptions.prototype.stopWalk = function (stop) { + if (typeof stop === "undefined") { stop = true; } + this.goChildren = !stop; + this.goNextSibling = !stop; + }; + return AstWalkOptions; + })(); + TypeScript.AstWalkOptions = AstWalkOptions; + var AstWalker = (function () { + function AstWalker(childrenWalkers, pre, post, options, state) { + this.childrenWalkers = childrenWalkers; + this.pre = pre; + this.post = post; + this.options = options; + this.state = state; + } + AstWalker.prototype.walk = function (ast, parent) { + var preAst = this.pre(ast, parent, this); + if(preAst === undefined) { + preAst = ast; + } + if(this.options.goChildren) { + var svGoSib = this.options.goNextSibling; + this.options.goNextSibling = true; + this.childrenWalkers[ast.nodeType](ast, parent, this); + this.options.goNextSibling = svGoSib; + } else { + this.options.goChildren = true; + } + if(this.post) { + var postAst = this.post(preAst, parent, this); + if(postAst === undefined) { + postAst = preAst; + } + return postAst; + } else { + return preAst; + } + }; + return AstWalker; + })(); + var AstWalkerFactory = (function () { + function AstWalkerFactory() { + this.childrenWalkers = []; + this.initChildrenWalkers(); + } + AstWalkerFactory.prototype.walk = function (ast, pre, post, options, state) { + return this.getWalker(pre, post, options, state).walk(ast, null); + }; + AstWalkerFactory.prototype.getWalker = function (pre, post, options, state) { + return this.getSlowWalker(pre, post, options, state); + }; + AstWalkerFactory.prototype.getSlowWalker = function (pre, post, options, state) { + if(!options) { + options = new AstWalkOptions(); + } + return new AstWalker(this.childrenWalkers, pre, post, options, state); + }; + AstWalkerFactory.prototype.initChildrenWalkers = function () { + this.childrenWalkers[TypeScript.NodeType.None] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Empty] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.EmptyExpr] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.True] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.False] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.This] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Super] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.QString] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Regex] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Null] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.ArrayLit] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.ObjectLit] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Void] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Comma] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Pos] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Neg] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Delete] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Await] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.In] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Dot] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.From] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Is] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.InstOf] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Typeof] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.NumberLit] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Name] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.TypeRef] = ChildrenWalkers.walkTypeReferenceChildren; + this.childrenWalkers[TypeScript.NodeType.Index] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Call] = ChildrenWalkers.walkCallExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.New] = ChildrenWalkers.walkCallExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Asg] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgAdd] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgSub] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgDiv] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgMul] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgMod] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgAnd] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgXor] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgOr] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgLsh] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgRsh] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgRs2] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.ConditionalExpression] = ChildrenWalkers.walkTrinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.LogOr] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.LogAnd] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Or] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Xor] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.And] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Eq] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Ne] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Eqv] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.NEqv] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Lt] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Le] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Gt] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Ge] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Add] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Sub] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Mul] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Div] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Mod] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Lsh] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Rsh] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Rs2] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Not] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.LogNot] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.IncPre] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.DecPre] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.IncPost] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.DecPost] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.TypeAssertion] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.FuncDecl] = ChildrenWalkers.walkFuncDeclChildren; + this.childrenWalkers[TypeScript.NodeType.Member] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.VarDecl] = ChildrenWalkers.walkBoundDeclChildren; + this.childrenWalkers[TypeScript.NodeType.ArgDecl] = ChildrenWalkers.walkBoundDeclChildren; + this.childrenWalkers[TypeScript.NodeType.Return] = ChildrenWalkers.walkReturnStatementChildren; + this.childrenWalkers[TypeScript.NodeType.Break] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Continue] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Throw] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.For] = ChildrenWalkers.walkForStatementChildren; + this.childrenWalkers[TypeScript.NodeType.ForIn] = ChildrenWalkers.walkForInStatementChildren; + this.childrenWalkers[TypeScript.NodeType.If] = ChildrenWalkers.walkIfStatementChildren; + this.childrenWalkers[TypeScript.NodeType.While] = ChildrenWalkers.walkWhileStatementChildren; + this.childrenWalkers[TypeScript.NodeType.DoWhile] = ChildrenWalkers.walkDoWhileStatementChildren; + this.childrenWalkers[TypeScript.NodeType.Block] = ChildrenWalkers.walkBlockChildren; + this.childrenWalkers[TypeScript.NodeType.Case] = ChildrenWalkers.walkCaseStatementChildren; + this.childrenWalkers[TypeScript.NodeType.Switch] = ChildrenWalkers.walkSwitchStatementChildren; + this.childrenWalkers[TypeScript.NodeType.Try] = ChildrenWalkers.walkTryChildren; + this.childrenWalkers[TypeScript.NodeType.TryCatch] = ChildrenWalkers.walkTryCatchChildren; + this.childrenWalkers[TypeScript.NodeType.TryFinally] = ChildrenWalkers.walkTryFinallyChildren; + this.childrenWalkers[TypeScript.NodeType.Finally] = ChildrenWalkers.walkFinallyChildren; + this.childrenWalkers[TypeScript.NodeType.Catch] = ChildrenWalkers.walkCatchChildren; + this.childrenWalkers[TypeScript.NodeType.List] = ChildrenWalkers.walkListChildren; + this.childrenWalkers[TypeScript.NodeType.Script] = ChildrenWalkers.walkScriptChildren; + this.childrenWalkers[TypeScript.NodeType.ClassDeclaration] = ChildrenWalkers.walkClassDeclChildren; + this.childrenWalkers[TypeScript.NodeType.InterfaceDeclaration] = ChildrenWalkers.walkTypeDeclChildren; + this.childrenWalkers[TypeScript.NodeType.ModuleDeclaration] = ChildrenWalkers.walkModuleDeclChildren; + this.childrenWalkers[TypeScript.NodeType.ImportDeclaration] = ChildrenWalkers.walkImportDeclChildren; + this.childrenWalkers[TypeScript.NodeType.With] = ChildrenWalkers.walkWithStatementChildren; + this.childrenWalkers[TypeScript.NodeType.Label] = ChildrenWalkers.walkLabelChildren; + this.childrenWalkers[TypeScript.NodeType.LabeledStatement] = ChildrenWalkers.walkLabeledStatementChildren; + this.childrenWalkers[TypeScript.NodeType.EBStart] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.GotoEB] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.EndCode] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Error] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Comment] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Debugger] = ChildrenWalkers.walkNone; + for(var e in (TypeScript.NodeType)._map) { + if((this.childrenWalkers)[e] === undefined) { + throw new Error("initWalkers function is not up to date with enum content!"); + } + } + }; + return AstWalkerFactory; + })(); + TypeScript.AstWalkerFactory = AstWalkerFactory; + var globalAstWalkerFactory; + function getAstWalkerFactory() { + if(!globalAstWalkerFactory) { + globalAstWalkerFactory = new AstWalkerFactory(); + } + return globalAstWalkerFactory; + } + TypeScript.getAstWalkerFactory = getAstWalkerFactory; + var ChildrenWalkers; + (function (ChildrenWalkers) { + function walkNone(preAst, parent, walker) { + } + ChildrenWalkers.walkNone = walkNone; + function walkListChildren(preAst, parent, walker) { + var len = preAst.members.length; + if(walker.options.reverseSiblings) { + for(var i = len - 1; i >= 0; i--) { + if(walker.options.goNextSibling) { + preAst.members[i] = walker.walk(preAst.members[i], preAst); + } + } + } else { + for(var i = 0; i < len; i++) { + if(walker.options.goNextSibling) { + preAst.members[i] = walker.walk(preAst.members[i], preAst); + } + } + } + } + ChildrenWalkers.walkListChildren = walkListChildren; + function walkUnaryExpressionChildren(preAst, parent, walker) { + if(preAst.castTerm) { + preAst.castTerm = walker.walk(preAst.castTerm, preAst); + } + if(preAst.operand) { + preAst.operand = walker.walk(preAst.operand, preAst); + } + } + ChildrenWalkers.walkUnaryExpressionChildren = walkUnaryExpressionChildren; + function walkBinaryExpressionChildren(preAst, parent, walker) { + if(walker.options.reverseSiblings) { + if(preAst.operand2) { + preAst.operand2 = walker.walk(preAst.operand2, preAst); + } + if((preAst.operand1) && (walker.options.goNextSibling)) { + preAst.operand1 = walker.walk(preAst.operand1, preAst); + } + } else { + if(preAst.operand1) { + preAst.operand1 = walker.walk(preAst.operand1, preAst); + } + if((preAst.operand2) && (walker.options.goNextSibling)) { + preAst.operand2 = walker.walk(preAst.operand2, preAst); + } + } + } + ChildrenWalkers.walkBinaryExpressionChildren = walkBinaryExpressionChildren; + function walkTypeReferenceChildren(preAst, parent, walker) { + if(preAst.term) { + preAst.term = walker.walk(preAst.term, preAst); + } + } + ChildrenWalkers.walkTypeReferenceChildren = walkTypeReferenceChildren; + function walkCallExpressionChildren(preAst, parent, walker) { + if(!walker.options.reverseSiblings) { + preAst.target = walker.walk(preAst.target, preAst); + } + if(preAst.arguments && (walker.options.goNextSibling)) { + preAst.arguments = walker.walk(preAst.arguments, preAst); + } + if((walker.options.reverseSiblings) && (walker.options.goNextSibling)) { + preAst.target = walker.walk(preAst.target, preAst); + } + } + ChildrenWalkers.walkCallExpressionChildren = walkCallExpressionChildren; + function walkTrinaryExpressionChildren(preAst, parent, walker) { + if(preAst.operand1) { + preAst.operand1 = walker.walk(preAst.operand1, preAst); + } + if(preAst.operand2 && (walker.options.goNextSibling)) { + preAst.operand2 = walker.walk(preAst.operand2, preAst); + } + if(preAst.operand3 && (walker.options.goNextSibling)) { + preAst.operand3 = walker.walk(preAst.operand3, preAst); + } + } + ChildrenWalkers.walkTrinaryExpressionChildren = walkTrinaryExpressionChildren; + function walkFuncDeclChildren(preAst, parent, walker) { + if(preAst.name) { + preAst.name = walker.walk(preAst.name, preAst); + } + if(preAst.arguments && (walker.options.goNextSibling)) { + preAst.arguments = walker.walk(preAst.arguments, preAst); + } + if(preAst.returnTypeAnnotation && (walker.options.goNextSibling)) { + preAst.returnTypeAnnotation = walker.walk(preAst.returnTypeAnnotation, preAst); + } + if(preAst.bod && (walker.options.goNextSibling)) { + preAst.bod = walker.walk(preAst.bod, preAst); + } + } + ChildrenWalkers.walkFuncDeclChildren = walkFuncDeclChildren; + function walkBoundDeclChildren(preAst, parent, walker) { + if(preAst.id) { + preAst.id = walker.walk(preAst.id, preAst); + } + if(preAst.init) { + preAst.init = walker.walk(preAst.init, preAst); + } + if((preAst.typeExpr) && (walker.options.goNextSibling)) { + preAst.typeExpr = walker.walk(preAst.typeExpr, preAst); + } + } + ChildrenWalkers.walkBoundDeclChildren = walkBoundDeclChildren; + function walkReturnStatementChildren(preAst, parent, walker) { + if(preAst.returnExpression) { + preAst.returnExpression = walker.walk(preAst.returnExpression, preAst); + } + } + ChildrenWalkers.walkReturnStatementChildren = walkReturnStatementChildren; + function walkForStatementChildren(preAst, parent, walker) { + if(preAst.init) { + preAst.init = walker.walk(preAst.init, preAst); + } + if(preAst.cond && walker.options.goNextSibling) { + preAst.cond = walker.walk(preAst.cond, preAst); + } + if(preAst.incr && walker.options.goNextSibling) { + preAst.incr = walker.walk(preAst.incr, preAst); + } + if(preAst.body && walker.options.goNextSibling) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkForStatementChildren = walkForStatementChildren; + function walkForInStatementChildren(preAst, parent, walker) { + preAst.lval = walker.walk(preAst.lval, preAst); + if(walker.options.goNextSibling) { + preAst.obj = walker.walk(preAst.obj, preAst); + } + if(preAst.body && (walker.options.goNextSibling)) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkForInStatementChildren = walkForInStatementChildren; + function walkIfStatementChildren(preAst, parent, walker) { + preAst.cond = walker.walk(preAst.cond, preAst); + if(preAst.thenBod && (walker.options.goNextSibling)) { + preAst.thenBod = walker.walk(preAst.thenBod, preAst); + } + if(preAst.elseBod && (walker.options.goNextSibling)) { + preAst.elseBod = walker.walk(preAst.elseBod, preAst); + } + } + ChildrenWalkers.walkIfStatementChildren = walkIfStatementChildren; + function walkWhileStatementChildren(preAst, parent, walker) { + preAst.cond = walker.walk(preAst.cond, preAst); + if(preAst.body && (walker.options.goNextSibling)) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkWhileStatementChildren = walkWhileStatementChildren; + function walkDoWhileStatementChildren(preAst, parent, walker) { + preAst.cond = walker.walk(preAst.cond, preAst); + if(preAst.body && (walker.options.goNextSibling)) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkDoWhileStatementChildren = walkDoWhileStatementChildren; + function walkBlockChildren(preAst, parent, walker) { + if(preAst.statements) { + preAst.statements = walker.walk(preAst.statements, preAst); + } + } + ChildrenWalkers.walkBlockChildren = walkBlockChildren; + function walkCaseStatementChildren(preAst, parent, walker) { + if(preAst.expr) { + preAst.expr = walker.walk(preAst.expr, preAst); + } + if(preAst.body && walker.options.goNextSibling) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkCaseStatementChildren = walkCaseStatementChildren; + function walkSwitchStatementChildren(preAst, parent, walker) { + if(preAst.val) { + preAst.val = walker.walk(preAst.val, preAst); + } + if((preAst.caseList) && walker.options.goNextSibling) { + preAst.caseList = walker.walk(preAst.caseList, preAst); + } + } + ChildrenWalkers.walkSwitchStatementChildren = walkSwitchStatementChildren; + function walkTryChildren(preAst, parent, walker) { + if(preAst.body) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkTryChildren = walkTryChildren; + function walkTryCatchChildren(preAst, parent, walker) { + if(preAst.tryNode) { + preAst.tryNode = walker.walk(preAst.tryNode, preAst); + } + if((preAst.catchNode) && walker.options.goNextSibling) { + preAst.catchNode = walker.walk(preAst.catchNode, preAst); + } + } + ChildrenWalkers.walkTryCatchChildren = walkTryCatchChildren; + function walkTryFinallyChildren(preAst, parent, walker) { + if(preAst.tryNode) { + preAst.tryNode = walker.walk(preAst.tryNode, preAst); + } + if(preAst.finallyNode && walker.options.goNextSibling) { + preAst.finallyNode = walker.walk(preAst.finallyNode, preAst); + } + } + ChildrenWalkers.walkTryFinallyChildren = walkTryFinallyChildren; + function walkFinallyChildren(preAst, parent, walker) { + if(preAst.body) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkFinallyChildren = walkFinallyChildren; + function walkCatchChildren(preAst, parent, walker) { + if(preAst.param) { + preAst.param = walker.walk(preAst.param, preAst); + } + if((preAst.body) && walker.options.goNextSibling) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkCatchChildren = walkCatchChildren; + function walkRecordChildren(preAst, parent, walker) { + preAst.name = walker.walk(preAst.name, preAst); + if(walker.options.goNextSibling && preAst.members) { + preAst.members = walker.walk(preAst.members, preAst); + } + } + ChildrenWalkers.walkRecordChildren = walkRecordChildren; + function walkNamedTypeChildren(preAst, parent, walker) { + walkRecordChildren(preAst, parent, walker); + } + ChildrenWalkers.walkNamedTypeChildren = walkNamedTypeChildren; + function walkClassDeclChildren(preAst, parent, walker) { + walkNamedTypeChildren(preAst, parent, walker); + if(walker.options.goNextSibling && preAst.extendsList) { + preAst.extendsList = walker.walk(preAst.extendsList, preAst); + } + if(walker.options.goNextSibling && preAst.implementsList) { + preAst.implementsList = walker.walk(preAst.implementsList, preAst); + } + } + ChildrenWalkers.walkClassDeclChildren = walkClassDeclChildren; + function walkScriptChildren(preAst, parent, walker) { + if(preAst.bod) { + preAst.bod = walker.walk(preAst.bod, preAst); + } + } + ChildrenWalkers.walkScriptChildren = walkScriptChildren; + function walkTypeDeclChildren(preAst, parent, walker) { + walkNamedTypeChildren(preAst, parent, walker); + if(walker.options.goNextSibling && preAst.extendsList) { + preAst.extendsList = walker.walk(preAst.extendsList, preAst); + } + if(walker.options.goNextSibling && preAst.implementsList) { + preAst.implementsList = walker.walk(preAst.implementsList, preAst); + } + } + ChildrenWalkers.walkTypeDeclChildren = walkTypeDeclChildren; + function walkModuleDeclChildren(preAst, parent, walker) { + walkRecordChildren(preAst, parent, walker); + } + ChildrenWalkers.walkModuleDeclChildren = walkModuleDeclChildren; + function walkImportDeclChildren(preAst, parent, walker) { + if(preAst.id) { + preAst.id = walker.walk(preAst.id, preAst); + } + if(preAst.alias) { + preAst.alias = walker.walk(preAst.alias, preAst); + } + } + ChildrenWalkers.walkImportDeclChildren = walkImportDeclChildren; + function walkWithStatementChildren(preAst, parent, walker) { + if(preAst.expr) { + preAst.expr = walker.walk(preAst.expr, preAst); + } + if(preAst.body && walker.options.goNextSibling) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkWithStatementChildren = walkWithStatementChildren; + function walkLabelChildren(preAst, parent, walker) { + } + ChildrenWalkers.walkLabelChildren = walkLabelChildren; + function walkLabeledStatementChildren(preAst, parent, walker) { + preAst.labels = walker.walk(preAst.labels, preAst); + if(walker.options.goNextSibling) { + preAst.stmt = walker.walk(preAst.stmt, preAst); + } + } + ChildrenWalkers.walkLabeledStatementChildren = walkLabeledStatementChildren; + })(ChildrenWalkers || (ChildrenWalkers = {})); +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (AstWalkerWithDetailCallback) { + function walk(script, callback) { + var pre = function (cur, parent) { + walker.options.goChildren = AstWalkerCallback(true, cur, callback); + return cur; + }; + var post = function (cur, parent) { + AstWalkerCallback(false, cur, callback); + return cur; + }; + var walker = TypeScript.getAstWalkerFactory().getWalker(pre, post); + walker.walk(script, null); + } + AstWalkerWithDetailCallback.walk = walk; + function AstWalkerCallback(pre, ast, callback) { + var nodeType = ast.nodeType; + var callbackString = (TypeScript.NodeType)._map[nodeType] + "Callback"; + if(callback[callbackString]) { + return callback[callbackString](pre, ast); + } + if(callback.DefaultCallback) { + return callback.DefaultCallback(pre, ast); + } + return true; + } + })(TypeScript.AstWalkerWithDetailCallback || (TypeScript.AstWalkerWithDetailCallback = {})); + var AstWalkerWithDetailCallback = TypeScript.AstWalkerWithDetailCallback; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + function lastOf(items) { + return (items === null || items.length === 0) ? null : items[items.length - 1]; + } + TypeScript.lastOf = lastOf; + function max(a, b) { + return a >= b ? a : b; + } + TypeScript.max = max; + function min(a, b) { + return a <= b ? a : b; + } + TypeScript.min = min; + var AstPath = (function () { + function AstPath() { + this.asts = []; + this.top = -1; + } + AstPath.reverseIndexOf = function reverseIndexOf(items, index) { + return (items === null || items.length <= index) ? null : items[items.length - index - 1]; + }; + AstPath.prototype.clone = function () { + var clone = new AstPath(); + clone.asts = this.asts.map(function (value) { + return value; + }); + clone.top = this.top; + return clone; + }; + AstPath.prototype.pop = function () { + var head = this.ast(); + this.up(); + while(this.asts.length > this.count()) { + this.asts.pop(); + } + return head; + }; + AstPath.prototype.push = function (ast) { + while(this.asts.length > this.count()) { + this.asts.pop(); + } + this.top = this.asts.length; + this.asts.push(ast); + }; + AstPath.prototype.up = function () { + if(this.top <= -1) { + throw new Error("Invalid call to 'up'"); + } + this.top--; + }; + AstPath.prototype.down = function () { + if(this.top == this.ast.length - 1) { + throw new Error("Invalid call to 'down'"); + } + this.top++; + }; + AstPath.prototype.nodeType = function () { + if(this.ast() == null) { + return TypeScript.NodeType.None; + } + return this.ast().nodeType; + }; + AstPath.prototype.ast = function () { + return AstPath.reverseIndexOf(this.asts, this.asts.length - (this.top + 1)); + }; + AstPath.prototype.parent = function () { + return AstPath.reverseIndexOf(this.asts, this.asts.length - this.top); + }; + AstPath.prototype.count = function () { + return this.top + 1; + }; + AstPath.prototype.get = function (index) { + return this.asts[index]; + }; + AstPath.prototype.isNameOfClass = function () { + if(this.ast() === null || this.parent() === null) { + return false; + } + return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.ClassDeclaration) && ((this.parent()).name === this.ast()); + }; + AstPath.prototype.isNameOfInterface = function () { + if(this.ast() === null || this.parent() === null) { + return false; + } + return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.InterfaceDeclaration) && ((this.parent()).name === this.ast()); + }; + AstPath.prototype.isNameOfArgument = function () { + if(this.ast() === null || this.parent() === null) { + return false; + } + return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.ArgDecl) && ((this.parent()).id === this.ast()); + }; + AstPath.prototype.isNameOfVariable = function () { + if(this.ast() === null || this.parent() === null) { + return false; + } + return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.VarDecl) && ((this.parent()).id === this.ast()); + }; + AstPath.prototype.isNameOfModule = function () { + if(this.ast() === null || this.parent() === null) { + return false; + } + return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.ModuleDeclaration) && ((this.parent()).name === this.ast()); + }; + AstPath.prototype.isNameOfFunction = function () { + if(this.ast() === null || this.parent() === null) { + return false; + } + return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.FuncDecl) && ((this.parent()).name === this.ast()); + }; + AstPath.prototype.isChildOfScript = function () { + var ast = lastOf(this.asts); + return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.Script; + }; + AstPath.prototype.isChildOfModule = function () { + var ast = lastOf(this.asts); + return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.ModuleDeclaration; + }; + AstPath.prototype.isChildOfClass = function () { + var ast = lastOf(this.asts); + return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.ClassDeclaration; + }; + AstPath.prototype.isArgumentOfClassConstructor = function () { + var ast = lastOf(this.asts); + return this.count() >= 5 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.FuncDecl && this.asts[this.top - 3].nodeType === TypeScript.NodeType.List && this.asts[this.top - 4].nodeType === TypeScript.NodeType.ClassDeclaration && ((this.asts[this.top - 2]).isConstructor) && ((this.asts[this.top - 2]).arguments === this.asts[this.top - 1]) && ((this.asts[this.top - 4]).constructorDecl === this.asts[this.top - 2]); + }; + AstPath.prototype.isChildOfInterface = function () { + var ast = lastOf(this.asts); + return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.InterfaceDeclaration; + }; + AstPath.prototype.isTopLevelImplicitModule = function () { + return this.count() >= 1 && this.asts[this.top].nodeType === TypeScript.NodeType.ModuleDeclaration && TypeScript.hasFlag((this.asts[this.top]).modFlags, TypeScript.ModuleFlags.IsWholeFile); + }; + AstPath.prototype.isBodyOfTopLevelImplicitModule = function () { + return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ModuleDeclaration && (this.asts[this.top - 1]).members == this.asts[this.top - 0] && TypeScript.hasFlag((this.asts[this.top - 1]).modFlags, TypeScript.ModuleFlags.IsWholeFile); + }; + AstPath.prototype.isBodyOfScript = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Script && (this.asts[this.top - 1]).bod == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfSwitch = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Switch && (this.asts[this.top - 1]).caseList == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfModule = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ModuleDeclaration && (this.asts[this.top - 1]).members == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfClass = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ClassDeclaration && (this.asts[this.top - 1]).members == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfFunction = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.FuncDecl && (this.asts[this.top - 1]).bod == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfInterface = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.InterfaceDeclaration && (this.asts[this.top - 1]).members == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfBlock = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Block && (this.asts[this.top - 1]).statements == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfFor = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.For && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfCase = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Case && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfTry = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Try && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfCatch = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Catch && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfDoWhile = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.DoWhile && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfWhile = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.While && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfForIn = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ForIn && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfWith = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.With && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfFinally = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Finally && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + }; + AstPath.prototype.isCaseOfSwitch = function () { + return this.count() >= 3 && this.asts[this.top - 2].nodeType === TypeScript.NodeType.Switch && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 2]).caseList == this.asts[this.top - 1]; + }; + AstPath.prototype.isDefaultCaseOfSwitch = function () { + return this.count() >= 3 && this.asts[this.top - 2].nodeType === TypeScript.NodeType.Switch && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 2]).caseList == this.asts[this.top - 1] && (this.asts[this.top - 2]).defaultCase == this.asts[this.top - 0]; + }; + AstPath.prototype.isListOfObjectLit = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 1]).operand == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfObjectLit = function () { + return this.isListOfObjectLit(); + }; + AstPath.prototype.isEmptyListOfObjectLit = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 1]).operand == this.asts[this.top - 0] && (this.asts[this.top - 0]).members.length == 0; + }; + AstPath.prototype.isMemberOfObjectLit = function () { + return this.count() >= 3 && this.asts[this.top - 2].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 0].nodeType === TypeScript.NodeType.Member && (this.asts[this.top - 2]).operand == this.asts[this.top - 1]; + }; + AstPath.prototype.isNameOfMemberOfObjectLit = function () { + return this.count() >= 4 && this.asts[this.top - 3].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 2].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Member && this.asts[this.top - 0].nodeType === TypeScript.NodeType.Name && (this.asts[this.top - 3]).operand == this.asts[this.top - 2]; + }; + AstPath.prototype.isListOfArrayLit = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ArrayLit && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 1]).operand == this.asts[this.top - 0]; + }; + AstPath.prototype.isTargetOfMember = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Member && (this.asts[this.top - 1]).operand1 === this.asts[this.top - 0]; + }; + AstPath.prototype.isMemberOfMember = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Member && (this.asts[this.top - 1]).operand2 === this.asts[this.top - 0]; + }; + AstPath.prototype.isItemOfList = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List; + }; + AstPath.prototype.isThenOfIf = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.If && (this.asts[this.top - 1]).thenBod == this.asts[this.top - 0]; + }; + AstPath.prototype.isElseOfIf = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.If && (this.asts[this.top - 1]).elseBod == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfDefaultCase = function () { + return this.isBodyOfCase(); + }; + AstPath.prototype.isSingleStatementList = function () { + return this.count() >= 1 && this.asts[this.top].nodeType === TypeScript.NodeType.List && (this.asts[this.top]).members.length === 1; + }; + AstPath.prototype.isArgumentListOfFunction = function () { + return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.FuncDecl && (this.asts[this.top - 1]).arguments === this.asts[this.top - 0]; + }; + AstPath.prototype.isArgumentOfFunction = function () { + return this.count() >= 3 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.FuncDecl && (this.asts[this.top - 2]).arguments === this.asts[this.top - 1]; + }; + AstPath.prototype.isArgumentListOfCall = function () { + return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Call && (this.asts[this.top - 1]).arguments === this.asts[this.top - 0]; + }; + AstPath.prototype.isArgumentListOfNew = function () { + return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.New && (this.asts[this.top - 1]).arguments === this.asts[this.top - 0]; + }; + AstPath.prototype.isSynthesizedBlock = function () { + return this.count() >= 1 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.Block && (this.asts[this.top - 0]).isStatementBlock === false; + }; + return AstPath; + })(); + TypeScript.AstPath = AstPath; + function isValidAstNode(ast) { + if(ast === null) { + return false; + } + if(ast.minChar === -1 || ast.limChar === -1) { + return false; + } + return true; + } + TypeScript.isValidAstNode = isValidAstNode; + var AstPathContext = (function () { + function AstPathContext() { + this.path = new TypeScript.AstPath(); + } + return AstPathContext; + })(); + TypeScript.AstPathContext = AstPathContext; + (function (GetAstPathOptions) { + GetAstPathOptions._map = []; + GetAstPathOptions.Default = 0; + GetAstPathOptions.EdgeInclusive = 1; + GetAstPathOptions.DontPruneSearchBasedOnPosition = 1 << 1; + })(TypeScript.GetAstPathOptions || (TypeScript.GetAstPathOptions = {})); + var GetAstPathOptions = TypeScript.GetAstPathOptions; + function getAstPathToPosition(script, pos, options) { + if (typeof options === "undefined") { options = GetAstPathOptions.Default; } + var lookInComments = function (comments) { + if(comments && comments.length > 0) { + for(var i = 0; i < comments.length; i++) { + var minChar = comments[i].minChar; + var limChar = comments[i].limChar; + if(!comments[i].isBlockComment) { + limChar++; + } + if(pos >= minChar && pos < limChar) { + ctx.path.push(comments[i]); + } + } + } + }; + var pre = function (cur, parent, walker) { + if(isValidAstNode(cur)) { + var inclusive = TypeScript.hasFlag(options, GetAstPathOptions.EdgeInclusive) || cur.nodeType === TypeScript.NodeType.Name || pos === script.limChar; + var minChar = cur.minChar; + var limChar = cur.limChar + (inclusive ? 1 : 0); + if(pos >= minChar && pos < limChar) { + var previous = ctx.path.ast(); + if(previous == null || (cur.minChar >= previous.minChar && cur.limChar <= previous.limChar)) { + ctx.path.push(cur); + } else { + } + } + if(pos < limChar) { + lookInComments(cur.preComments); + } + if(pos >= minChar) { + lookInComments(cur.postComments); + } + if(!TypeScript.hasFlag(options, GetAstPathOptions.DontPruneSearchBasedOnPosition)) { + walker.options.goChildren = (minChar <= pos && pos <= limChar); + } + } + return cur; + }; + var ctx = new AstPathContext(); + TypeScript.getAstWalkerFactory().walk(script, pre, null, null, ctx); + return ctx.path; + } + TypeScript.getAstPathToPosition = getAstPathToPosition; + function getTokenizationOffset(script, position) { + var bestOffset = 0; + var pre = function (cur, parent, walker) { + if(TypeScript.isValidAstNode(cur)) { + if(cur.minChar <= position) { + bestOffset = max(bestOffset, cur.minChar); + } + if(cur.minChar > position || cur.limChar < bestOffset) { + walker.options.goChildren = false; + } + } + return cur; + }; + TypeScript.getAstWalkerFactory().walk(script, pre); + return bestOffset; + } + TypeScript.getTokenizationOffset = getTokenizationOffset; + function walkAST(ast, callback) { + var pre = function (cur, parent, walker) { + var path = walker.state; + path.push(cur); + callback(path, walker); + return cur; + }; + var post = function (cur, parent, walker) { + var path = walker.state; + path.pop(); + return cur; + }; + var path = new AstPath(); + TypeScript.getAstWalkerFactory().walk(ast, pre, post, null, path); + } + TypeScript.walkAST = walkAST; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var AstLogger = (function () { + function AstLogger(logger) { + this.logger = logger; + } + AstLogger.prototype.logScript = function (script) { + var _this = this; + this.logLinemap(script.locationInfo.lineMap); + var stack = []; + var pre = function (cur, parent) { + stack.push(cur); + var indent = (stack.length - 1) * 2; + _this.logComments(script, cur.preComments, indent); + _this.logNode(script, cur, indent); + _this.logComments(script, cur.postComments, indent); + return cur; + }; + var post = function (cur, parent) { + stack.pop(); + return cur; + }; + TypeScript.getAstWalkerFactory().walk(script, pre, post); + }; + AstLogger.prototype.logNode = function (script, cur, indent) { + var msg = this.addPadding("", indent, "| ", true); + msg = msg.concat("+ " + cur.treeViewLabel()); + msg = this.addPadding(msg, 70, " ", false); + msg = msg + this.addLineColumn(script, cur.minChar); + msg = this.addPadding(msg, 80, " ", false); + msg = msg + "=> "; + msg = msg + this.addLineColumn(script, cur.limChar); + msg = this.addPadding(msg, 102, " ", false); + msg = msg.concat("[" + this.addPadding(cur.minChar.toString(), 1, " ", true) + ", " + this.addPadding(cur.limChar.toString(), 1, " ", true) + "]"); + msg = this.addPadding(msg, 115, " ", false); + msg = msg.concat("sym=" + (cur).sym); + msg = this.addPadding(msg, 135, " ", false); + msg = msg.concat("type=" + (cur.type === null ? "null" : cur.type.getTypeName())); + this.logger.log(msg); + }; + AstLogger.prototype.logComments = function (script, comments, indent) { + if(comments == null) { + return; + } + for(var i = 0; i < comments.length; i++) { + this.logNode(script, comments[i], indent); + } + }; + AstLogger.prototype.logLinemap = function (linemap) { + var result = "["; + for(var i = 0; i < linemap.length; i++) { + if(i > 0) { + result += ","; + } + result += linemap[i]; + } + result += "]"; + this.logger.log("linemap: " + result); + }; + AstLogger.prototype.addPadding = function (s, targetLength, paddingString, leftPadding) { + var result = (leftPadding ? "" : s); + for(var i = s.length; i < targetLength; i++) { + result = result + paddingString; + } + result = result + (leftPadding ? s : ""); + return result; + }; + AstLogger.prototype.addLineColumn = function (script, position) { + var lineInfo = { + line: -1, + col: -1 + }; + TypeScript.getSourceLineColFromMap(lineInfo, position, script.locationInfo.lineMap); + if(lineInfo.col !== -1) { + lineInfo.col++; + } + return "(" + lineInfo.line + ", " + lineInfo.col + ")"; + }; + return AstLogger; + })(); + TypeScript.AstLogger = AstLogger; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Binder = (function () { + function Binder(checker) { + this.checker = checker; + } + Binder.prototype.resolveBaseTypeLinks = function (typeLinks, scope) { + var extendsList = null; + if(typeLinks) { + extendsList = new Array(); + for(var i = 0, len = typeLinks.length; i < len; i++) { + extendsList[i] = this.checker.resolveBaseTypeLink(typeLinks[i], scope); + } + } + return extendsList; + }; + Binder.prototype.resolveBases = function (scope, type) { + type.extendsList = this.resolveBaseTypeLinks(type.extendsTypeLinks, scope); + var i = 0, len = type.extendsList.length; + var derivedIsClass = type.isClassInstance(); + for(; i < len; i++) { + var baseIsClass = type.extendsList[i].isClassInstance(); + if(type.extendsList[i] != this.checker.anyType) { + var baseRef = type.extendsTypeLinks[i].ast; + if(derivedIsClass) { + if(!baseIsClass) { + this.checker.errorReporter.simpleError(baseRef, "A class may only extend other classes, " + type.extendsList[i].symbol.fullName() + " is not a class."); + } + } else { + if(baseIsClass) { + this.checker.errorReporter.simpleError(baseRef, "An interface may only extend other interfaces, " + type.extendsList[i].symbol.fullName() + " is a class."); + } + } + } + } + type.implementsList = this.resolveBaseTypeLinks(type.implementsTypeLinks, scope); + if(type.implementsList) { + for(i = 0 , len = type.implementsList.length; i < len; i++) { + var iface = type.implementsList[i]; + var baseRef = type.implementsTypeLinks[i].ast; + if(iface.isClassInstance()) { + if(derivedIsClass) { + this.checker.errorReporter.simpleError(baseRef, "A class may only implement an interface; " + iface.symbol.fullName() + " is a class."); + } + } + } + } + }; + Binder.prototype.resolveSignatureGroup = function (signatureGroup, scope, instanceType) { + var supplyVar = !(signatureGroup.hasImplementation); + for(var i = 0, len = signatureGroup.signatures.length; i < len; i++) { + var signature = signatureGroup.signatures[i]; + if(instanceType) { + signature.returnType.type = instanceType; + } else { + this.checker.resolveTypeLink(scope, signature.returnType, supplyVar); + } + var paramLen = signature.parameters.length; + for(var j = 0; j < paramLen; j++) { + this.bindSymbol(scope, signature.parameters[j]); + } + if(signature.hasVariableArgList) { + var lastParam = signature.parameters[paramLen - 1]; + lastParam.argsOffset = paramLen - 1; + if(!lastParam.getType().isArray()) { + this.checker.errorReporter.simpleErrorFromSym(lastParam, "... parameter must have array type"); + lastParam.parameter.typeLink.type = this.checker.makeArrayType(lastParam.parameter.typeLink.type); + } + } + } + }; + Binder.prototype.bindType = function (scope, type, instanceType) { + if(instanceType) { + this.bindType(scope, instanceType, null); + } + var callAndConstructScope = scope; + if(type.hasMembers()) { + var members = type.members; + var ambientMembers = type.ambientMembers; + var typeMembers = type.getAllEnclosedTypes(); + var ambientTypeMembers = type.getAllAmbientEnclosedTypes(); + var memberScope = new TypeScript.SymbolTableScope(members, ambientMembers, typeMembers, ambientTypeMembers, type.symbol); + var agg = new TypeScript.SymbolAggregateScope(type.symbol); + var prevCurrentModDecl = this.checker.currentModDecl; + var prevBindStatus = this.checker.inBind; + agg.addParentScope(memberScope); + agg.addParentScope(scope); + if(type.isModuleType()) { + this.checker.currentModDecl = type.symbol.declAST; + this.checker.inBind = true; + } + if(members) { + this.bind(agg, type.members.allMembers); + } + if(typeMembers) { + this.bind(agg, typeMembers.allMembers); + } + if(ambientMembers) { + this.bind(agg, ambientMembers.allMembers); + } + if(ambientTypeMembers) { + this.bind(agg, ambientTypeMembers.allMembers); + } + if(type.isModuleType()) { + callAndConstructScope = agg; + } + this.checker.currentModDecl = prevCurrentModDecl; + this.checker.inBind = prevBindStatus; + } + if(type.extendsTypeLinks) { + this.resolveBases(scope, type); + } + if(type.construct) { + this.resolveSignatureGroup(type.construct, callAndConstructScope, instanceType); + } + if(type.call) { + this.resolveSignatureGroup(type.call, callAndConstructScope, null); + } + if(type.index) { + this.resolveSignatureGroup(type.index, scope, null); + } + if(type.elementType) { + this.bindType(scope, type.elementType, null); + } + }; + Binder.prototype.bindSymbol = function (scope, symbol) { + if(!symbol.bound) { + var prevLocationInfo = this.checker.locationInfo; + if((this.checker.units) && (symbol.unitIndex >= 0) && (symbol.unitIndex < this.checker.units.length)) { + this.checker.locationInfo = this.checker.units[symbol.unitIndex]; + } + switch(symbol.kind()) { + case TypeScript.SymbolKind.Type: + if(symbol.flags & TypeScript.SymbolFlags.Bound) { + break; + } + var typeSymbol = symbol; + typeSymbol.flags |= TypeScript.SymbolFlags.Bound; + if(typeSymbol.aliasLink && !typeSymbol.type && typeSymbol.aliasLink.alias.nodeType == TypeScript.NodeType.Name) { + var modPath = (typeSymbol.aliasLink.alias).text; + var modSym = this.checker.findSymbolForDynamicModule(modPath, this.checker.locationInfo.filename, function (id) { + return scope.find(id, false, true); + }); + if(modSym) { + typeSymbol.type = modSym.getType(); + } + } + if(typeSymbol.type && typeSymbol.type != this.checker.gloModType) { + this.bindType(scope, typeSymbol.type, typeSymbol.instanceType); + if(typeSymbol.type.isModuleType()) { + for(var i = 0; i < typeSymbol.expansions.length; i++) { + this.bindType(scope, typeSymbol.expansions[i], typeSymbol.instanceType); + } + } + } + break; + case TypeScript.SymbolKind.Field: + this.checker.resolveTypeLink(scope, (symbol).field.typeLink, false); + break; + case TypeScript.SymbolKind.Parameter: + this.checker.resolveTypeLink(scope, (symbol).parameter.typeLink, true); + break; + } + this.checker.locationInfo = prevLocationInfo; + } + symbol.bound = true; + }; + Binder.prototype.bind = function (scope, table) { + table.map(function (key, sym, binder) { + binder.bindSymbol(scope, sym); + }, this); + }; + return Binder; + })(); + TypeScript.Binder = Binder; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Base64Format = (function () { + function Base64Format() { } + Base64Format.encodedValues = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + Base64Format.encode = function encode(inValue) { + if(inValue < 64) { + return Base64Format.encodedValues.charAt(inValue); + } + throw TypeError(inValue + ": not a 64 based value"); + }; + Base64Format.decodeChar = function decodeChar(inChar) { + if(inChar.length === 1) { + return Base64Format.encodedValues.indexOf(inChar); + } else { + throw TypeError('"' + inChar + '" must have length 1'); + } + }; + return Base64Format; + })(); + var Base64VLQFormat = (function () { + function Base64VLQFormat() { } + Base64VLQFormat.encode = function encode(inValue) { + if(inValue < 0) { + inValue = ((-inValue) << 1) + 1; + } else { + inValue = inValue << 1; + } + var encodedStr = ""; + do { + var currentDigit = inValue & 31; + inValue = inValue >> 5; + if(inValue > 0) { + currentDigit = currentDigit | 32; + } + encodedStr = encodedStr + Base64Format.encode(currentDigit); + }while(inValue > 0); + return encodedStr; + }; + Base64VLQFormat.decode = function decode(inString) { + var result = 0; + var negative = false; + var shift = 0; + for(var i = 0; i < inString.length; i++) { + var byte = Base64Format.decodeChar(inString[i]); + if(i === 0) { + if((byte & 1) === 1) { + negative = true; + } + result = (byte >> 1) & 15; + } else { + result = result | ((byte & 31) << shift); + } + shift += (i == 0) ? 4 : 5; + if((byte & 32) === 32) { + } else { + return { + value: negative ? -(result) : result, + rest: inString.substr(i + 1) + }; + } + } + throw new Error('Base64 value "' + inString + '" finished with a continuation bit'); + }; + return Base64VLQFormat; + })(); + TypeScript.Base64VLQFormat = Base64VLQFormat; +})(TypeScript || (TypeScript = {})); +var JSON2 = { +}; +((function () { + 'use strict'; + function f(n) { + return n < 10 ? '0' + n : n; + } + if(typeof Date.prototype.toJSON !== 'function') { + Date.prototype.toJSON = function (key) { + return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; + }; + var strProto = String.prototype; + var numProto = Number.prototype; + numProto.JSON = strProto.JSON = (Boolean).prototype.toJSON = function (key) { + return this.valueOf(); + }; + } + var escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { + '\b': '\\b', + '\t': '\\t', + '\n': '\\n', + '\f': '\\f', + '\r': '\\r', + '"': '\\"', + '\\': '\\\\' + }, rep; + function quote(string) { + escapable.lastIndex = 0; + return escapable.test(string) ? '"' + string.replace(escapable, function (a) { + var c = meta[a]; + return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); + }) + '"' : '"' + string + '"'; + } + function str(key, holder) { + var i, k = null, v, length, mind = gap, partial, value = holder[key]; + if(value && typeof value === 'object' && typeof value.toJSON === 'function') { + value = value.toJSON(key); + } + if(typeof rep === 'function') { + value = rep.call(holder, key, value); + } + switch(typeof value) { + case 'string': + return quote(value); + case 'number': + return isFinite(value) ? String(value) : 'null'; + case 'boolean': + case 'null': + return String(value); + case 'object': + if(!value) { + return 'null'; + } + gap += indent; + partial = []; + if(Object.prototype.toString.apply(value, []) === '[object Array]') { + length = value.length; + for(i = 0; i < length; i += 1) { + partial[i] = str(i, value) || 'null'; + } + v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; + gap = mind; + return v; + } + if(rep && typeof rep === 'object') { + length = rep.length; + for(i = 0; i < length; i += 1) { + if(typeof rep[i] === 'string') { + k = rep[i]; + v = str(k, value); + if(v) { + partial.push(quote(k) + (gap ? ': ' : ':') + v); + } + } + } + } else { + for(k in value) { + if(Object.prototype.hasOwnProperty.call(value, k)) { + v = str(k, value); + if(v) { + partial.push(quote(k) + (gap ? ': ' : ':') + v); + } + } + } + } + v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; + gap = mind; + return v; + } + } + if(typeof JSON2.stringify !== 'function') { + JSON2.stringify = function (value, replacer, space) { + var i; + gap = ''; + indent = ''; + if(typeof space === 'number') { + for(i = 0; i < space; i += 1) { + indent += ' '; + } + } else if(typeof space === 'string') { + indent = space; + } + rep = replacer; + if(replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { + throw new Error('JSON.stringify'); + } + return str('', { + '': value + }); + }; + } +})()); +var TypeScript; +(function (TypeScript) { + var SourceMapPosition = (function () { + function SourceMapPosition() { } + return SourceMapPosition; + })(); + TypeScript.SourceMapPosition = SourceMapPosition; + var SourceMapping = (function () { + function SourceMapping() { + this.start = new SourceMapPosition(); + this.end = new SourceMapPosition(); + this.nameIndex = -1; + this.childMappings = []; + } + return SourceMapping; + })(); + TypeScript.SourceMapping = SourceMapping; + var SourceMapper = (function () { + function SourceMapper(tsFileName, jsFileName, jsFile, sourceMapOut, errorReporter, emitFullPathOfSourceMap) { + this.jsFile = jsFile; + this.sourceMapOut = sourceMapOut; + this.errorReporter = errorReporter; + this.sourceMappings = []; + this.currentMappings = []; + this.names = []; + this.currentNameIndex = []; + this.currentMappings.push(this.sourceMappings); + jsFileName = TypeScript.switchToForwardSlashes(jsFileName); + this.jsFileName = TypeScript.getPrettyName(jsFileName, false, true); + var removalIndex = jsFileName.lastIndexOf(this.jsFileName); + var fixedPath = jsFileName.substring(0, removalIndex); + if(emitFullPathOfSourceMap) { + if(jsFileName.indexOf("://") == -1) { + jsFileName = "file:///" + jsFileName; + } + this.jsFileName = jsFileName; + } + this.tsFileName = TypeScript.getRelativePathToFixedPath(fixedPath, tsFileName); + } + SourceMapper.MapFileExtension = ".map"; + SourceMapper.EmitSourceMapping = function EmitSourceMapping(allSourceMappers) { + var sourceMapper = allSourceMappers[0]; + sourceMapper.jsFile.WriteLine("//@ sourceMappingURL=" + sourceMapper.jsFileName + SourceMapper.MapFileExtension); + var sourceMapOut = sourceMapper.sourceMapOut; + var mappingsString = ""; + var tsFiles = []; + var prevEmittedColumn = 0; + var prevEmittedLine = 0; + var prevSourceColumn = 0; + var prevSourceLine = 0; + var prevSourceIndex = 0; + var prevNameIndex = 0; + var namesList = []; + var namesCount = 0; + var emitComma = false; + var recordedPosition = null; + for(var sourceMapperIndex = 0; sourceMapperIndex < allSourceMappers.length; sourceMapperIndex++) { + sourceMapper = allSourceMappers[sourceMapperIndex]; + var currentSourceIndex = tsFiles.length; + tsFiles.push(sourceMapper.tsFileName); + if(sourceMapper.names.length > 0) { + namesList.push.apply(namesList, sourceMapper.names); + } + var recordSourceMapping = function (mappedPosition, nameIndex) { + if(recordedPosition != null && recordedPosition.emittedColumn == mappedPosition.emittedColumn && recordedPosition.emittedLine == mappedPosition.emittedLine) { + return; + } + if(prevEmittedLine !== mappedPosition.emittedLine) { + while(prevEmittedLine < mappedPosition.emittedLine) { + prevEmittedColumn = 0; + mappingsString = mappingsString + ";"; + prevEmittedLine++; + } + emitComma = false; + } else if(emitComma) { + mappingsString = mappingsString + ","; + } + mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(mappedPosition.emittedColumn - prevEmittedColumn); + prevEmittedColumn = mappedPosition.emittedColumn; + mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(currentSourceIndex - prevSourceIndex); + prevSourceIndex = currentSourceIndex; + mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(mappedPosition.sourceLine - 1 - prevSourceLine); + prevSourceLine = mappedPosition.sourceLine - 1; + mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(mappedPosition.sourceColumn - prevSourceColumn); + prevSourceColumn = mappedPosition.sourceColumn; + if(nameIndex >= 0) { + mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(namesCount + nameIndex - prevNameIndex); + prevNameIndex = namesCount + nameIndex; + } + emitComma = true; + recordedPosition = mappedPosition; + }; + var recordSourceMappingSiblings = function (sourceMappings) { + for(var i = 0; i < sourceMappings.length; i++) { + var sourceMapping = sourceMappings[i]; + recordSourceMapping(sourceMapping.start, sourceMapping.nameIndex); + recordSourceMappingSiblings(sourceMapping.childMappings); + recordSourceMapping(sourceMapping.end, sourceMapping.nameIndex); + } + }; + recordSourceMappingSiblings(sourceMapper.sourceMappings, -1); + namesCount = namesCount + sourceMapper.names.length; + } + sourceMapOut.Write(JSON2.stringify({ + version: 3, + file: sourceMapper.jsFileName, + sources: tsFiles, + names: namesList, + mappings: mappingsString + })); + try { + sourceMapOut.Close(); + } catch (ex) { + sourceMapper.errorReporter.emitterError(null, ex.message); + } + }; + return SourceMapper; + })(); + TypeScript.SourceMapper = SourceMapper; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (EmitContainer) { + EmitContainer._map = []; + EmitContainer._map[0] = "Prog"; + EmitContainer.Prog = 0; + EmitContainer._map[1] = "Module"; + EmitContainer.Module = 1; + EmitContainer._map[2] = "DynamicModule"; + EmitContainer.DynamicModule = 2; + EmitContainer._map[3] = "Class"; + EmitContainer.Class = 3; + EmitContainer._map[4] = "Constructor"; + EmitContainer.Constructor = 4; + EmitContainer._map[5] = "Function"; + EmitContainer.Function = 5; + EmitContainer._map[6] = "Args"; + EmitContainer.Args = 6; + EmitContainer._map[7] = "Interface"; + EmitContainer.Interface = 7; + })(TypeScript.EmitContainer || (TypeScript.EmitContainer = {})); + var EmitContainer = TypeScript.EmitContainer; + var EmitState = (function () { + function EmitState() { + this.column = 0; + this.line = 0; + this.pretty = false; + this.inObjectLiteral = false; + this.container = EmitContainer.Prog; + } + return EmitState; + })(); + TypeScript.EmitState = EmitState; + var EmitOptions = (function () { + function EmitOptions(settings) { + this.ioHost = null; + this.outputMany = true; + this.commonDirectoryPath = ""; + this.minWhitespace = settings.minWhitespace; + this.propagateConstants = settings.propagateConstants; + this.emitComments = settings.emitComments; + this.outputOption = settings.outputOption; + this.emitFullSourceMapPath = settings.emitFullSourceMapPath; + } + EmitOptions.prototype.mapOutputFileName = function (fileName, extensionChanger) { + if(this.outputMany) { + var updatedFileName = fileName; + if(this.outputOption != "") { + updatedFileName = fileName.replace(this.commonDirectoryPath, ""); + updatedFileName = this.outputOption + updatedFileName; + } + return extensionChanger(updatedFileName, false); + } else { + return extensionChanger(this.outputOption, true); + } + }; + return EmitOptions; + })(); + TypeScript.EmitOptions = EmitOptions; + var Indenter = (function () { + function Indenter() { + this.indentAmt = 0; + } + Indenter.indentStep = 4; + Indenter.indentStepString = " "; + Indenter.indentStrings = []; + Indenter.prototype.increaseIndent = function () { + this.indentAmt += Indenter.indentStep; + }; + Indenter.prototype.decreaseIndent = function () { + this.indentAmt -= Indenter.indentStep; + }; + Indenter.prototype.getIndent = function () { + var indentString = Indenter.indentStrings[this.indentAmt]; + if(indentString === undefined) { + indentString = ""; + for(var i = 0; i < this.indentAmt; i = i + Indenter.indentStep) { + indentString += Indenter.indentStepString; + } + Indenter.indentStrings[this.indentAmt] = indentString; + } + return indentString; + }; + return Indenter; + })(); + TypeScript.Indenter = Indenter; + var Emitter = (function () { + function Emitter(checker, emittingFileName, outfile, emitOptions, errorReporter) { + this.checker = checker; + this.emittingFileName = emittingFileName; + this.outfile = outfile; + this.emitOptions = emitOptions; + this.errorReporter = errorReporter; + this.globalThisCapturePrologueEmitted = false; + this.extendsPrologueEmitted = false; + this.thisClassNode = null; + this.thisFnc = null; + this.moduleDeclList = []; + this.moduleName = ""; + this.emitState = new EmitState(); + this.indenter = new Indenter(); + this.ambientModule = false; + this.modAliasId = null; + this.firstModAlias = null; + this.allSourceMappers = []; + this.sourceMapper = null; + this.captureThisStmtString = "var _this = this;"; + this.varListCountStack = [ + 0 + ]; + } + Emitter.prototype.setSourceMappings = function (mapper) { + this.allSourceMappers.push(mapper); + this.sourceMapper = mapper; + }; + Emitter.prototype.writeToOutput = function (s) { + this.outfile.Write(s); + this.emitState.column += s.length; + }; + Emitter.prototype.writeToOutputTrimmable = function (s) { + if(this.emitOptions.minWhitespace) { + s = s.replace(/[\s]*/g, ''); + } + this.writeToOutput(s); + }; + Emitter.prototype.writeLineToOutput = function (s) { + if(this.emitOptions.minWhitespace) { + this.writeToOutput(s); + var c = s.charCodeAt(s.length - 1); + if(!((c == TypeScript.LexCodeSpace) || (c == TypeScript.LexCodeSMC) || (c == TypeScript.LexCodeLBR))) { + this.writeToOutput(' '); + } + } else { + this.outfile.WriteLine(s); + this.emitState.column = 0; + this.emitState.line++; + } + }; + Emitter.prototype.writeCaptureThisStatement = function (ast) { + this.emitIndent(); + this.recordSourceMappingStart(ast); + this.writeToOutput(this.captureThisStmtString); + this.recordSourceMappingEnd(ast); + this.writeLineToOutput(""); + }; + Emitter.prototype.setInVarBlock = function (count) { + this.varListCountStack[this.varListCountStack.length - 1] = count; + }; + Emitter.prototype.setInObjectLiteral = function (val) { + var temp = this.emitState.inObjectLiteral; + this.emitState.inObjectLiteral = val; + return temp; + }; + Emitter.prototype.setContainer = function (c) { + var temp = this.emitState.container; + this.emitState.container = c; + return temp; + }; + Emitter.prototype.getIndentString = function () { + if(this.emitOptions.minWhitespace) { + return ""; + } else { + return this.indenter.getIndent(); + } + }; + Emitter.prototype.emitIndent = function () { + this.writeToOutput(this.getIndentString()); + }; + Emitter.prototype.emitCommentInPlace = function (comment) { + var text = comment.getText(); + var hadNewLine = false; + if(comment.isBlockComment) { + if(this.emitState.column == 0) { + this.emitIndent(); + } + this.recordSourceMappingStart(comment); + this.writeToOutput(text[0]); + if(text.length > 1 || comment.endsLine) { + for(var i = 1; i < text.length; i++) { + this.writeLineToOutput(""); + this.emitIndent(); + this.writeToOutput(text[i]); + } + this.recordSourceMappingEnd(comment); + this.writeLineToOutput(""); + hadNewLine = true; + } else { + this.recordSourceMappingEnd(comment); + } + } else { + if(this.emitState.column == 0) { + this.emitIndent(); + } + this.recordSourceMappingStart(comment); + this.writeToOutput(text[0]); + this.recordSourceMappingEnd(comment); + this.writeLineToOutput(""); + hadNewLine = true; + } + if(hadNewLine) { + this.emitIndent(); + } else { + this.writeToOutput(" "); + } + }; + Emitter.prototype.emitParensAndCommentsInPlace = function (ast, pre) { + var comments = pre ? ast.preComments : ast.postComments; + if(ast.isParenthesized && !pre) { + this.writeToOutput(")"); + } + if(this.emitOptions.emitComments && comments && comments.length != 0) { + for(var i = 0; i < comments.length; i++) { + this.emitCommentInPlace(comments[i]); + } + } + if(ast.isParenthesized && pre) { + this.writeToOutput("("); + } + }; + Emitter.prototype.emitObjectLiteral = function (content) { + this.writeLineToOutput("{"); + this.indenter.increaseIndent(); + var inObjectLiteral = this.setInObjectLiteral(true); + this.emitJavascriptList(content, ",", TypeScript.TokenID.Comma, true, false, false); + this.setInObjectLiteral(inObjectLiteral); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeToOutput("}"); + }; + Emitter.prototype.emitArrayLiteral = function (content) { + this.writeToOutput("["); + if(content) { + this.writeLineToOutput(""); + this.indenter.increaseIndent(); + this.emitJavascriptList(content, ", ", TypeScript.TokenID.Comma, true, false, false); + this.indenter.decreaseIndent(); + this.emitIndent(); + } + this.writeToOutput("]"); + }; + Emitter.prototype.emitNew = function (target, args) { + this.writeToOutput("new "); + if(target.nodeType == TypeScript.NodeType.TypeRef) { + var typeRef = target; + if(typeRef.arrayCount) { + this.writeToOutput("Array()"); + } else { + this.emitJavascript(typeRef.term, TypeScript.TokenID.Tilde, false); + this.writeToOutput("()"); + } + } else { + this.emitJavascript(target, TypeScript.TokenID.Tilde, false); + this.recordSourceMappingStart(args); + this.writeToOutput("("); + this.emitJavascriptList(args, ", ", TypeScript.TokenID.Comma, false, false, false); + this.writeToOutput(")"); + this.recordSourceMappingEnd(args); + } + }; + Emitter.prototype.getConstantValue = function (init) { + if(init) { + if(init.nodeType === TypeScript.NodeType.NumberLit) { + var numLit = init; + return numLit.value; + } else if(init.nodeType === TypeScript.NodeType.Lsh) { + var binop = init; + if(binop.operand1.nodeType === TypeScript.NodeType.NumberLit && binop.operand2.nodeType === TypeScript.NodeType.NumberLit) { + return (binop.operand1).value << (binop.operand2).value; + } + } else if(init.nodeType === TypeScript.NodeType.Name) { + var ident = init; + if(ident.sym !== null && ident.sym.declAST.nodeType === TypeScript.NodeType.VarDecl) { + var varDecl = ident.sym.declAST; + return this.getConstantValue(varDecl.init); + } + } + } + return null; + }; + Emitter.prototype.tryEmitConstant = function (dotExpr) { + if(!this.emitOptions.propagateConstants) { + return false; + } + var propertyName = dotExpr.operand2; + if(propertyName && propertyName.sym && propertyName.sym.isVariable()) { + if(TypeScript.hasFlag(propertyName.sym.flags, TypeScript.SymbolFlags.Constant)) { + if(propertyName.sym.declAST) { + var boundDecl = propertyName.sym.declAST; + var value = this.getConstantValue(boundDecl.init); + if(value !== null) { + this.writeToOutput(value.toString()); + var comment = " /* "; + comment += propertyName.actualText; + comment += " */ "; + this.writeToOutput(comment); + return true; + } + } + } + } + return false; + }; + Emitter.prototype.emitCall = function (callNode, target, args) { + if(!this.emitSuperCall(callNode)) { + if(!TypeScript.hasFlag(callNode.flags, TypeScript.ASTFlags.ClassBaseConstructorCall)) { + if(target.nodeType == TypeScript.NodeType.FuncDecl && !target.isParenthesized) { + this.writeToOutput("("); + } + if(callNode.target.nodeType == TypeScript.NodeType.Super && this.emitState.container == EmitContainer.Constructor) { + this.writeToOutput("_super.call"); + } else { + this.emitJavascript(target, TypeScript.TokenID.OpenParen, false); + } + if(target.nodeType == TypeScript.NodeType.FuncDecl && !target.isParenthesized) { + this.writeToOutput(")"); + } + this.recordSourceMappingStart(args); + this.writeToOutput("("); + if(callNode.target.nodeType == TypeScript.NodeType.Super && this.emitState.container == EmitContainer.Constructor) { + this.writeToOutput("this"); + if(args && args.members.length) { + this.writeToOutput(", "); + } + } + this.emitJavascriptList(args, ", ", TypeScript.TokenID.Comma, false, false, false); + this.writeToOutput(")"); + this.recordSourceMappingEnd(args); + } else { + this.indenter.decreaseIndent(); + this.indenter.decreaseIndent(); + var constructorCall = new TypeScript.ASTList(); + constructorCall.members[0] = callNode; + this.emitConstructorCalls(constructorCall, this.thisClassNode); + this.indenter.increaseIndent(); + this.indenter.increaseIndent(); + } + } + }; + Emitter.prototype.emitConstructorCalls = function (bases, classDecl) { + if(bases == null) { + return; + } + var basesLen = bases.members.length; + this.recordSourceMappingStart(classDecl); + for(var i = 0; i < basesLen; i++) { + var baseExpr = bases.members[i]; + var baseSymbol = null; + if(baseExpr.nodeType == TypeScript.NodeType.Call) { + baseSymbol = (baseExpr).target.type.symbol; + } else { + baseSymbol = baseExpr.type.symbol; + } + var baseName = baseSymbol.name; + if(baseSymbol.declModule != classDecl.type.symbol.declModule) { + baseName = baseSymbol.fullName(); + } + if(baseExpr.nodeType == TypeScript.NodeType.Call) { + this.emitIndent(); + this.writeToOutput("_super.call(this"); + var args = (baseExpr).arguments; + if(args && (args.members.length > 0)) { + this.writeToOutput(", "); + this.emitJavascriptList(args, ", ", TypeScript.TokenID.Comma, false, false, false); + } + this.writeToOutput(")"); + } else { + if(baseExpr.type && (baseExpr.type.isClassInstance())) { + this.emitIndent(); + this.writeToOutput(classDecl.name.actualText + "._super.constructor"); + this.writeToOutput(".call(this)"); + } + } + } + this.recordSourceMappingEnd(classDecl); + }; + Emitter.prototype.emitInnerFunction = function (funcDecl, printName, isMember, bases, hasSelfRef, classDecl) { + var isClassConstructor = funcDecl.isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod); + var hasNonObjectBaseType = isClassConstructor && TypeScript.hasFlag(this.thisClassNode.type.instanceType.typeFlags, TypeScript.TypeFlags.HasBaseType) && !TypeScript.hasFlag(this.thisClassNode.type.instanceType.typeFlags, TypeScript.TypeFlags.HasBaseTypeOfObject); + var classPropertiesMustComeAfterSuperCall = hasNonObjectBaseType && TypeScript.hasFlag((this.thisClassNode).varFlags, TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor); + var shouldParenthesize = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFunctionExpression) && !funcDecl.isParenthesized && !funcDecl.isAccessor() && (TypeScript.hasFlag(funcDecl.flags, TypeScript.ASTFlags.ExplicitSemicolon) || TypeScript.hasFlag(funcDecl.flags, TypeScript.ASTFlags.AutomaticSemicolon)); + this.emitParensAndCommentsInPlace(funcDecl, true); + if(shouldParenthesize) { + this.writeToOutput("("); + } + this.recordSourceMappingStart(funcDecl); + if(!(funcDecl.isAccessor() && (funcDecl.accessorSymbol).isObjectLitField)) { + this.writeToOutput("function "); + } + if(printName) { + var id = funcDecl.getNameText(); + if(id && !funcDecl.isAccessor()) { + if(funcDecl.name) { + this.recordSourceMappingStart(funcDecl.name); + } + this.writeToOutput(id); + if(funcDecl.name) { + this.recordSourceMappingEnd(funcDecl.name); + } + } + } + this.writeToOutput("("); + var argsLen = 0; + var i = 0; + var arg; + var defaultArgs = []; + if(funcDecl.arguments) { + var tempContainer = this.setContainer(EmitContainer.Args); + argsLen = funcDecl.arguments.members.length; + var printLen = argsLen; + if(funcDecl.variableArgList) { + printLen--; + } + for(i = 0; i < printLen; i++) { + arg = funcDecl.arguments.members[i]; + if(arg.init) { + defaultArgs.push(arg); + } + this.emitJavascript(arg, TypeScript.TokenID.OpenParen, false); + if(i < (printLen - 1)) { + this.writeToOutput(", "); + } + } + this.setContainer(tempContainer); + } + this.writeLineToOutput(") {"); + if(funcDecl.isConstructor) { + this.recordSourceMappingNameStart("constructor"); + } else if(funcDecl.isGetAccessor()) { + this.recordSourceMappingNameStart("get_" + funcDecl.getNameText()); + } else if(funcDecl.isSetAccessor()) { + this.recordSourceMappingNameStart("set_" + funcDecl.getNameText()); + } else { + this.recordSourceMappingNameStart(funcDecl.getNameText()); + } + this.indenter.increaseIndent(); + for(i = 0; i < defaultArgs.length; i++) { + var arg = defaultArgs[i]; + this.emitIndent(); + this.recordSourceMappingStart(arg); + this.writeToOutput("if (typeof " + arg.id.actualText + " === \"undefined\") { "); + this.recordSourceMappingStart(arg.id); + this.writeToOutput(arg.id.actualText); + this.recordSourceMappingEnd(arg.id); + this.writeToOutput(" = "); + this.emitJavascript(arg.init, TypeScript.TokenID.OpenParen, false); + this.writeLineToOutput("; }"); + this.recordSourceMappingEnd(arg); + } + if(funcDecl.isConstructor && ((funcDecl.classDecl).varFlags & TypeScript.VarFlags.MustCaptureThis)) { + this.writeCaptureThisStatement(funcDecl); + } + if(funcDecl.isConstructor && !classPropertiesMustComeAfterSuperCall) { + if(funcDecl.arguments) { + argsLen = funcDecl.arguments.members.length; + for(i = 0; i < argsLen; i++) { + arg = funcDecl.arguments.members[i]; + if((arg.varFlags & TypeScript.VarFlags.Property) != TypeScript.VarFlags.None) { + this.emitIndent(); + this.recordSourceMappingStart(arg); + this.recordSourceMappingStart(arg.id); + this.writeToOutput("this." + arg.id.actualText); + this.recordSourceMappingEnd(arg.id); + this.writeToOutput(" = "); + this.recordSourceMappingStart(arg.id); + this.writeToOutput(arg.id.actualText); + this.recordSourceMappingEnd(arg.id); + this.writeLineToOutput(";"); + this.recordSourceMappingEnd(arg); + } + } + } + if(!TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { + this.emitConstructorCalls(bases, classDecl); + } + } + if(hasSelfRef) { + this.writeCaptureThisStatement(funcDecl); + } + if(funcDecl.variableArgList) { + argsLen = funcDecl.arguments.members.length; + var lastArg = funcDecl.arguments.members[argsLen - 1]; + this.emitIndent(); + this.recordSourceMappingStart(lastArg); + this.writeToOutput("var "); + this.recordSourceMappingStart(lastArg.id); + this.writeToOutput(lastArg.id.actualText); + this.recordSourceMappingEnd(lastArg.id); + this.writeLineToOutput(" = [];"); + this.recordSourceMappingEnd(lastArg); + this.emitIndent(); + this.writeToOutput("for ("); + this.recordSourceMappingStart(lastArg); + this.writeToOutput("var _i = 0;"); + this.recordSourceMappingEnd(lastArg); + this.writeToOutput(" "); + this.recordSourceMappingStart(lastArg); + this.writeToOutput("_i < (arguments.length - " + (argsLen - 1) + ")"); + this.recordSourceMappingEnd(lastArg); + this.writeToOutput("; "); + this.recordSourceMappingStart(lastArg); + this.writeToOutput("_i++"); + this.recordSourceMappingEnd(lastArg); + this.writeLineToOutput(") {"); + this.indenter.increaseIndent(); + this.emitIndent(); + this.recordSourceMappingStart(lastArg); + this.writeToOutput(lastArg.id.actualText + "[_i] = arguments[_i + " + (argsLen - 1) + "];"); + this.recordSourceMappingEnd(lastArg); + this.writeLineToOutput(""); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeLineToOutput("}"); + } + if(funcDecl.isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod) && !classPropertiesMustComeAfterSuperCall) { + var nProps = (this.thisClassNode.members).members.length; + for(var i = 0; i < nProps; i++) { + if((this.thisClassNode.members).members[i].nodeType == TypeScript.NodeType.VarDecl) { + var varDecl = (this.thisClassNode.members).members[i]; + if(!TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static) && varDecl.init) { + this.emitIndent(); + this.emitJavascriptVarDecl(varDecl, TypeScript.TokenID.Tilde); + this.writeLineToOutput(""); + } + } + } + } + this.emitBareJavascriptStatements(funcDecl.bod, classPropertiesMustComeAfterSuperCall); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.recordSourceMappingStart(funcDecl.endingToken); + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(funcDecl.endingToken); + this.recordSourceMappingEnd(funcDecl); + if(shouldParenthesize) { + this.writeToOutput(")"); + } + this.recordSourceMappingEnd(funcDecl); + this.emitParensAndCommentsInPlace(funcDecl, false); + if(!isMember && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFunctionExpression) && (!TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Signature) || funcDecl.isConstructor)) { + this.writeLineToOutput(""); + } else if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFunctionExpression)) { + if(TypeScript.hasFlag(funcDecl.flags, TypeScript.ASTFlags.ExplicitSemicolon) || TypeScript.hasFlag(funcDecl.flags, TypeScript.ASTFlags.AutomaticSemicolon)) { + this.writeLineToOutput(";"); + } + } + }; + Emitter.prototype.emitJavascriptModule = function (moduleDecl) { + var modName = moduleDecl.name.actualText; + if(TypeScript.isTSFile(modName)) { + moduleDecl.name.setText(modName.substring(0, modName.length - 3)); + } else if(TypeScript.isSTRFile(modName)) { + moduleDecl.name.setText(modName.substring(0, modName.length - 4)); + } + if(!TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.Ambient)) { + var isDynamicMod = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsDynamic); + var prevOutFile = this.outfile; + var prevOutFileName = this.emittingFileName; + var prevAllSourceMappers = this.allSourceMappers; + var prevSourceMapper = this.sourceMapper; + var prevColumn = this.emitState.column; + var prevLine = this.emitState.line; + var temp = this.setContainer(EmitContainer.Module); + var svModuleName = this.moduleName; + var isExported = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.Exported); + this.moduleDeclList[this.moduleDeclList.length] = moduleDecl; + var isWholeFile = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsWholeFile); + this.moduleName = moduleDecl.name.actualText; + if(isDynamicMod) { + var tsModFileName = TypeScript.stripQuotes(moduleDecl.name.actualText); + var modFilePath = TypeScript.trimModName(tsModFileName) + ".js"; + modFilePath = this.emitOptions.mapOutputFileName(modFilePath, TypeScript.TypeScriptCompiler.mapToJSFileName); + if(this.emitOptions.ioHost) { + if(TypeScript.switchToForwardSlashes(modFilePath) != TypeScript.switchToForwardSlashes(this.emittingFileName)) { + this.emittingFileName = modFilePath; + var useUTF8InOutputfile = moduleDecl.containsUnicodeChar || (this.emitOptions.emitComments && moduleDecl.containsUnicodeCharInComment); + this.outfile = this.createFile(this.emittingFileName, useUTF8InOutputfile); + if(prevSourceMapper != null) { + this.allSourceMappers = []; + var sourceMappingFile = this.createFile(this.emittingFileName + TypeScript.SourceMapper.MapFileExtension, false); + this.setSourceMappings(new TypeScript.SourceMapper(tsModFileName, this.emittingFileName, this.outfile, sourceMappingFile, this.errorReporter, this.emitOptions.emitFullSourceMapPath)); + this.emitState.column = 0; + this.emitState.line = 0; + } + } else { + TypeScript.CompilerDiagnostics.assert(this.emitOptions.outputMany, "Cannot have dynamic modules compiling into single file"); + } + } + this.setContainer(EmitContainer.DynamicModule); + this.recordSourceMappingStart(moduleDecl); + if(TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { + var dependencyList = "[\"require\", \"exports\""; + var importList = "require, exports"; + var importStatement = null; + for(var i = 0; i < (moduleDecl.mod).importedModules.length; i++) { + importStatement = (moduleDecl.mod).importedModules[i]; + if(importStatement.id.sym && !(importStatement.id.sym).onlyReferencedAsTypeRef) { + if(i <= (moduleDecl.mod).importedModules.length - 1) { + dependencyList += ", "; + importList += ", "; + } + importList += "__" + importStatement.id.actualText + "__"; + dependencyList += importStatement.firstAliasedModToString(); + } + } + for(var i = 0; i < moduleDecl.amdDependencies.length; i++) { + dependencyList += ", \"" + moduleDecl.amdDependencies[i] + "\""; + } + dependencyList += "]"; + this.writeLineToOutput("define(" + dependencyList + "," + " function(" + importList + ") {"); + } else { + } + } else { + if(!isExported) { + this.recordSourceMappingStart(moduleDecl); + this.writeToOutput("var "); + this.recordSourceMappingStart(moduleDecl.name); + this.writeToOutput(this.moduleName); + this.recordSourceMappingEnd(moduleDecl.name); + this.writeLineToOutput(";"); + this.recordSourceMappingEnd(moduleDecl); + this.emitIndent(); + } + this.writeToOutput("("); + this.recordSourceMappingStart(moduleDecl); + this.writeToOutput("function ("); + this.recordSourceMappingStart(moduleDecl.name); + this.writeToOutput(this.moduleName); + this.recordSourceMappingEnd(moduleDecl.name); + this.writeLineToOutput(") {"); + } + if(!isWholeFile) { + this.recordSourceMappingNameStart(this.moduleName); + } + if(!isDynamicMod || TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { + this.indenter.increaseIndent(); + } + if(moduleDecl.modFlags & TypeScript.ModuleFlags.MustCaptureThis) { + this.writeCaptureThisStatement(moduleDecl); + } + this.emitJavascriptList(moduleDecl.members, null, TypeScript.TokenID.Semicolon, true, false, false); + if(!isDynamicMod || TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { + this.indenter.decreaseIndent(); + } + this.emitIndent(); + if(isDynamicMod) { + if(TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { + this.writeLineToOutput("})"); + } else { + } + if(!isWholeFile) { + this.recordSourceMappingNameEnd(); + } + this.recordSourceMappingEnd(moduleDecl); + if(this.outfile != prevOutFile) { + this.Close(); + if(prevSourceMapper != null) { + this.allSourceMappers = prevAllSourceMappers; + this.sourceMapper = prevSourceMapper; + this.emitState.column = prevColumn; + this.emitState.line = prevLine; + } + this.outfile = prevOutFile; + this.emittingFileName = prevOutFileName; + } + } else { + var containingMod = null; + if(moduleDecl.type && moduleDecl.type.symbol.container && moduleDecl.type.symbol.container.declAST) { + containingMod = moduleDecl.type.symbol.container.declAST; + } + var parentIsDynamic = containingMod && TypeScript.hasFlag(containingMod.modFlags, TypeScript.ModuleFlags.IsDynamic); + this.recordSourceMappingStart(moduleDecl.endingToken); + if(temp == EmitContainer.Prog && isExported) { + this.writeToOutput("}"); + if(!isWholeFile) { + this.recordSourceMappingNameEnd(); + } + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeToOutput(")(this." + this.moduleName + " || (this." + this.moduleName + " = {}));"); + } else if(isExported || temp == EmitContainer.Prog) { + var dotMod = svModuleName != "" ? (parentIsDynamic ? "exports" : svModuleName) + "." : svModuleName; + this.writeToOutput("}"); + if(!isWholeFile) { + this.recordSourceMappingNameEnd(); + } + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeToOutput(")(" + dotMod + this.moduleName + " || (" + dotMod + this.moduleName + " = {}));"); + } else if(!isExported && temp != EmitContainer.Prog) { + this.writeToOutput("}"); + if(!isWholeFile) { + this.recordSourceMappingNameEnd(); + } + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeToOutput(")(" + this.moduleName + " || (" + this.moduleName + " = {}));"); + } else { + this.writeToOutput("}"); + if(!isWholeFile) { + this.recordSourceMappingNameEnd(); + } + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeToOutput(")();"); + } + this.recordSourceMappingEnd(moduleDecl); + this.writeLineToOutput(""); + if(temp != EmitContainer.Prog && isExported) { + this.emitIndent(); + this.recordSourceMappingStart(moduleDecl); + if(parentIsDynamic) { + this.writeLineToOutput("var " + this.moduleName + " = exports." + this.moduleName + ";"); + } else { + this.writeLineToOutput("var " + this.moduleName + " = " + svModuleName + "." + this.moduleName + ";"); + } + this.recordSourceMappingEnd(moduleDecl); + } + } + this.setContainer(temp); + this.moduleName = svModuleName; + this.moduleDeclList.length--; + } + }; + Emitter.prototype.emitIndex = function (operand1, operand2) { + var temp = this.setInObjectLiteral(false); + this.emitJavascript(operand1, TypeScript.TokenID.Tilde, false); + this.writeToOutput("["); + this.emitJavascriptList(operand2, ", ", TypeScript.TokenID.Comma, false, false, false); + this.writeToOutput("]"); + this.setInObjectLiteral(temp); + }; + Emitter.prototype.emitStringLiteral = function (text) { + this.writeToOutput(text); + }; + Emitter.prototype.emitJavascriptFunction = function (funcDecl) { + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Signature) || funcDecl.isOverload) { + return; + } + var temp; + var tempFnc = this.thisFnc; + this.thisFnc = funcDecl; + if(funcDecl.isConstructor) { + temp = this.setContainer(EmitContainer.Constructor); + } else { + temp = this.setContainer(EmitContainer.Function); + } + var bases = null; + var hasSelfRef = false; + var funcName = funcDecl.getNameText(); + if((this.emitState.inObjectLiteral || !funcDecl.isAccessor()) && ((temp != EmitContainer.Constructor) || ((funcDecl.fncFlags & TypeScript.FncFlags.Method) == TypeScript.FncFlags.None))) { + var tempLit = this.setInObjectLiteral(false); + if(this.thisClassNode) { + bases = this.thisClassNode.extendsList; + } + hasSelfRef = Emitter.shouldCaptureThis(funcDecl); + this.recordSourceMappingStart(funcDecl); + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Exported | TypeScript.FncFlags.ClassPropertyMethodExported) && funcDecl.type.symbol.container == this.checker.gloMod && !funcDecl.isConstructor) { + this.writeToOutput("this." + funcName + " = "); + this.emitInnerFunction(funcDecl, false, false, bases, hasSelfRef, this.thisClassNode); + } else { + this.emitInnerFunction(funcDecl, (funcDecl.name && !funcDecl.name.isMissing()), false, bases, hasSelfRef, this.thisClassNode); + } + this.setInObjectLiteral(tempLit); + } + this.setContainer(temp); + this.thisFnc = tempFnc; + if(!TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Signature)) { + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static)) { + if(this.thisClassNode) { + if(funcDecl.isAccessor()) { + this.emitPropertyAccessor(funcDecl, this.thisClassNode.name.actualText, false); + } else { + this.emitIndent(); + this.recordSourceMappingStart(funcDecl); + this.writeLineToOutput(this.thisClassNode.name.actualText + "." + funcName + " = " + funcName + ";"); + this.recordSourceMappingEnd(funcDecl); + } + } + } else if((this.emitState.container == EmitContainer.Module || this.emitState.container == EmitContainer.DynamicModule) && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Exported | TypeScript.FncFlags.ClassPropertyMethodExported)) { + this.emitIndent(); + var modName = this.emitState.container == EmitContainer.Module ? this.moduleName : "exports"; + this.recordSourceMappingStart(funcDecl); + this.writeLineToOutput(modName + "." + funcName + " = " + funcName + ";"); + this.recordSourceMappingEnd(funcDecl); + } + } + }; + Emitter.prototype.emitAmbientVarDecl = function (varDecl) { + if(varDecl.init) { + this.emitParensAndCommentsInPlace(varDecl, true); + this.recordSourceMappingStart(varDecl); + this.recordSourceMappingStart(varDecl.id); + this.writeToOutput(varDecl.id.actualText); + this.recordSourceMappingEnd(varDecl.id); + this.writeToOutput(" = "); + this.emitJavascript(varDecl.init, TypeScript.TokenID.Comma, false); + this.recordSourceMappingEnd(varDecl); + this.writeToOutput(";"); + this.emitParensAndCommentsInPlace(varDecl, false); + } + }; + Emitter.prototype.varListCount = function () { + return this.varListCountStack[this.varListCountStack.length - 1]; + }; + Emitter.prototype.emitVarDeclVar = function () { + if(this.varListCount() >= 0) { + this.writeToOutput("var "); + this.setInVarBlock(-this.varListCount()); + } + return true; + }; + Emitter.prototype.onEmitVar = function () { + if(this.varListCount() > 0) { + this.setInVarBlock(this.varListCount() - 1); + } else if(this.varListCount() < 0) { + this.setInVarBlock(this.varListCount() + 1); + } + }; + Emitter.prototype.emitJavascriptVarDecl = function (varDecl, tokenId) { + if((varDecl.varFlags & TypeScript.VarFlags.Ambient) == TypeScript.VarFlags.Ambient) { + this.emitAmbientVarDecl(varDecl); + this.onEmitVar(); + } else { + var sym = varDecl.sym; + var hasInitializer = (varDecl.init != null); + this.emitParensAndCommentsInPlace(varDecl, true); + this.recordSourceMappingStart(varDecl); + if(sym && sym.isMember() && sym.container && (sym.container.kind() == TypeScript.SymbolKind.Type)) { + var type = (sym.container).type; + if(type.isClass() && (!TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.ModuleMember))) { + if(this.emitState.container != EmitContainer.Args) { + if(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Static)) { + this.writeToOutput(sym.container.name + "."); + } else { + this.writeToOutput("this."); + } + } + } else if(type.hasImplementation()) { + if(!TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Exported) && (sym.container == this.checker.gloMod || !TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Property))) { + this.emitVarDeclVar(); + } else if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.LocalStatic)) { + this.writeToOutput("."); + } else { + if(this.emitState.container == EmitContainer.DynamicModule) { + this.writeToOutput("exports."); + } else { + this.writeToOutput(this.moduleName + "."); + } + } + } else { + if(tokenId != TypeScript.TokenID.OpenParen) { + if(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Exported) && sym.container == this.checker.gloMod) { + this.writeToOutput("this."); + } else { + this.emitVarDeclVar(); + } + } + } + } else { + if(tokenId != TypeScript.TokenID.OpenParen) { + this.emitVarDeclVar(); + } + } + this.recordSourceMappingStart(varDecl.id); + this.writeToOutput(varDecl.id.actualText); + this.recordSourceMappingEnd(varDecl.id); + if(hasInitializer) { + this.writeToOutputTrimmable(" = "); + this.varListCountStack.push(0); + this.emitJavascript(varDecl.init, TypeScript.TokenID.Comma, false); + this.varListCountStack.pop(); + } + this.onEmitVar(); + if((tokenId != TypeScript.TokenID.OpenParen)) { + if(this.varListCount() < 0) { + this.writeToOutput(", "); + } else if(tokenId != TypeScript.TokenID.For) { + this.writeToOutputTrimmable(";"); + } + } + this.recordSourceMappingEnd(varDecl); + this.emitParensAndCommentsInPlace(varDecl, false); + } + }; + Emitter.prototype.declEnclosed = function (moduleDecl) { + if(moduleDecl == null) { + return true; + } + for(var i = 0, len = this.moduleDeclList.length; i < len; i++) { + if(this.moduleDeclList[i] == moduleDecl) { + return true; + } + } + return false; + }; + Emitter.prototype.emitJavascriptName = function (name, addThis) { + var sym = name.sym; + this.emitParensAndCommentsInPlace(name, true); + this.recordSourceMappingStart(name); + if(!name.isMissing()) { + if(addThis && (this.emitState.container != EmitContainer.Args) && sym) { + if(sym.container && (sym.container.name != TypeScript.globalId)) { + if(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Static) && (TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Property))) { + if(sym.declModule && TypeScript.hasFlag(sym.declModule.modFlags, TypeScript.ModuleFlags.IsDynamic)) { + this.writeToOutput("exports."); + } else { + this.writeToOutput(sym.container.name + "."); + } + } else if(sym.kind() == TypeScript.SymbolKind.Field) { + var fieldSym = sym; + if(TypeScript.hasFlag(fieldSym.flags, TypeScript.SymbolFlags.ModuleMember)) { + if((sym.container != this.checker.gloMod) && ((TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Property)) || TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Exported))) { + if(TypeScript.hasFlag(sym.declModule.modFlags, TypeScript.ModuleFlags.IsDynamic)) { + this.writeToOutput("exports."); + } else { + this.writeToOutput(sym.container.name + "."); + } + } + } else { + if(sym.isInstanceProperty()) { + this.emitThis(); + this.writeToOutput("."); + } + } + } else if(sym.kind() == TypeScript.SymbolKind.Type) { + if(sym.isInstanceProperty()) { + var typeSym = sym; + var type = typeSym.type; + if(type.call && !TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.ModuleMember)) { + this.emitThis(); + this.writeToOutput("."); + } + } else if((sym.unitIndex != this.checker.locationInfo.unitIndex) || (!this.declEnclosed(sym.declModule))) { + this.writeToOutput(sym.container.name + "."); + } + } + } else if(sym.container == this.checker.gloMod && TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Exported) && !TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Ambient) && !((sym.isType() || sym.isMember()) && sym.declModule && TypeScript.hasFlag(sym.declModule.modFlags, TypeScript.ModuleFlags.Ambient)) && this.emitState.container == EmitContainer.Prog && sym.declAST.nodeType != TypeScript.NodeType.FuncDecl) { + this.writeToOutput("this."); + } + } + if(sym && sym.declAST && sym.declAST.nodeType == TypeScript.NodeType.ModuleDeclaration && (TypeScript.hasFlag((sym.declAST).modFlags, TypeScript.ModuleFlags.IsDynamic))) { + var moduleDecl = sym.declAST; + if(TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { + this.writeLineToOutput("__" + this.modAliasId + "__;"); + } else { + var modPath = name.actualText; + var isSingleQuotedMod = TypeScript.isSingleQuoted(modPath); + var isAmbient = moduleDecl.mod.symbol.declAST && TypeScript.hasFlag((moduleDecl.mod.symbol.declAST).modFlags, TypeScript.ModuleFlags.Ambient); + modPath = isAmbient ? modPath : this.firstModAlias ? this.firstModAlias : TypeScript.quoteBaseName(modPath); + modPath = isAmbient ? modPath : (!TypeScript.isRelative(TypeScript.stripQuotes(modPath)) ? TypeScript.quoteStr("./" + TypeScript.stripQuotes(modPath)) : modPath); + if(isSingleQuotedMod) { + modPath = TypeScript.changeToSingleQuote(modPath); + } + this.writeToOutput("require(" + modPath + ")"); + } + } else { + this.writeToOutput(name.actualText); + } + } + this.recordSourceMappingEnd(name); + this.emitParensAndCommentsInPlace(name, false); + }; + Emitter.prototype.emitJavascriptStatements = function (stmts, emitEmptyBod) { + if(stmts) { + if(stmts.nodeType != TypeScript.NodeType.Block) { + var hasContents = (stmts && (stmts.nodeType != TypeScript.NodeType.List || ((stmts).members.length > 0))); + if(emitEmptyBod || hasContents) { + var hasOnlyBlockStatement = ((stmts.nodeType == TypeScript.NodeType.Block) || ((stmts.nodeType == TypeScript.NodeType.List) && ((stmts).members.length == 1) && ((stmts).members[0].nodeType == TypeScript.NodeType.Block))); + this.recordSourceMappingStart(stmts); + if(!hasOnlyBlockStatement) { + this.writeLineToOutput(" {"); + this.indenter.increaseIndent(); + } + this.emitJavascriptList(stmts, null, TypeScript.TokenID.Semicolon, true, false, false); + if(!hasOnlyBlockStatement) { + this.writeLineToOutput(""); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeToOutput("}"); + } + this.recordSourceMappingEnd(stmts); + } + } else { + this.emitJavascript(stmts, TypeScript.TokenID.Semicolon, true); + } + } else if(emitEmptyBod) { + this.writeToOutput("{ }"); + } + }; + Emitter.prototype.emitBareJavascriptStatements = function (stmts, emitClassPropertiesAfterSuperCall) { + if (typeof emitClassPropertiesAfterSuperCall === "undefined") { emitClassPropertiesAfterSuperCall = false; } + if(stmts.nodeType != TypeScript.NodeType.Block) { + if(stmts.nodeType == TypeScript.NodeType.List) { + var stmtList = stmts; + if((stmtList.members.length == 2) && (stmtList.members[0].nodeType == TypeScript.NodeType.Block) && (stmtList.members[1].nodeType == TypeScript.NodeType.EndCode)) { + this.emitJavascript(stmtList.members[0], TypeScript.TokenID.Semicolon, true); + this.writeLineToOutput(""); + } else { + this.emitJavascriptList(stmts, null, TypeScript.TokenID.Semicolon, true, false, emitClassPropertiesAfterSuperCall); + } + } else { + this.emitJavascript(stmts, TypeScript.TokenID.Semicolon, true); + } + } else { + this.emitJavascript(stmts, TypeScript.TokenID.Semicolon, true); + } + }; + Emitter.prototype.recordSourceMappingNameStart = function (name) { + if(this.sourceMapper) { + var finalName = name; + if(!name) { + finalName = ""; + } else if(this.sourceMapper.currentNameIndex.length > 0) { + finalName = this.sourceMapper.names[this.sourceMapper.currentNameIndex[this.sourceMapper.currentNameIndex.length - 1]] + "." + name; + } + this.sourceMapper.names.push(finalName); + this.sourceMapper.currentNameIndex.push(this.sourceMapper.names.length - 1); + } + }; + Emitter.prototype.recordSourceMappingNameEnd = function () { + if(this.sourceMapper) { + this.sourceMapper.currentNameIndex.pop(); + } + }; + Emitter.prototype.recordSourceMappingStart = function (ast) { + if(this.sourceMapper && TypeScript.isValidAstNode(ast)) { + var lineCol = { + line: -1, + col: -1 + }; + var sourceMapping = new TypeScript.SourceMapping(); + sourceMapping.start.emittedColumn = this.emitState.column; + sourceMapping.start.emittedLine = this.emitState.line; + TypeScript.getSourceLineColFromMap(lineCol, ast.minChar, this.checker.locationInfo.lineMap); + sourceMapping.start.sourceColumn = lineCol.col; + sourceMapping.start.sourceLine = lineCol.line; + TypeScript.getSourceLineColFromMap(lineCol, ast.limChar, this.checker.locationInfo.lineMap); + sourceMapping.end.sourceColumn = lineCol.col; + sourceMapping.end.sourceLine = lineCol.line; + if(this.sourceMapper.currentNameIndex.length > 0) { + sourceMapping.nameIndex = this.sourceMapper.currentNameIndex[this.sourceMapper.currentNameIndex.length - 1]; + } + var siblings = this.sourceMapper.currentMappings[this.sourceMapper.currentMappings.length - 1]; + siblings.push(sourceMapping); + this.sourceMapper.currentMappings.push(sourceMapping.childMappings); + } + }; + Emitter.prototype.recordSourceMappingEnd = function (ast) { + if(this.sourceMapper && TypeScript.isValidAstNode(ast)) { + this.sourceMapper.currentMappings.pop(); + var siblings = this.sourceMapper.currentMappings[this.sourceMapper.currentMappings.length - 1]; + var sourceMapping = siblings[siblings.length - 1]; + sourceMapping.end.emittedColumn = this.emitState.column; + sourceMapping.end.emittedLine = this.emitState.line; + } + }; + Emitter.prototype.Close = function () { + if(this.sourceMapper != null) { + TypeScript.SourceMapper.EmitSourceMapping(this.allSourceMappers); + } + try { + this.outfile.Close(); + } catch (ex) { + this.errorReporter.emitterError(null, ex.message); + } + }; + Emitter.prototype.emitJavascriptList = function (ast, delimiter, tokenId, startLine, onlyStatics, emitClassPropertiesAfterSuperCall, emitPrologue, requiresExtendsBlock) { + if (typeof emitClassPropertiesAfterSuperCall === "undefined") { emitClassPropertiesAfterSuperCall = false; } + if (typeof emitPrologue === "undefined") { emitPrologue = false; } + if(ast == null) { + return; + } else if(ast.nodeType != TypeScript.NodeType.List) { + this.emitPrologue(emitPrologue); + this.emitJavascript(ast, tokenId, startLine); + } else { + var list = ast; + this.emitParensAndCommentsInPlace(ast, true); + if(list.members.length == 0) { + this.emitParensAndCommentsInPlace(ast, false); + return; + } + var len = list.members.length; + for(var i = 0; i < len; i++) { + if(emitPrologue) { + if(i == 1 || !TypeScript.hasFlag(list.flags, TypeScript.ASTFlags.StrictMode)) { + this.emitPrologue(requiresExtendsBlock); + emitPrologue = false; + } + } + if(i == 1 && emitClassPropertiesAfterSuperCall) { + var constructorDecl = (this.thisClassNode).constructorDecl; + if(constructorDecl && constructorDecl.arguments) { + var argsLen = constructorDecl.arguments.members.length; + for(var iArg = 0; iArg < argsLen; iArg++) { + var arg = constructorDecl.arguments.members[iArg]; + if((arg.varFlags & TypeScript.VarFlags.Property) != TypeScript.VarFlags.None) { + this.emitIndent(); + this.recordSourceMappingStart(arg); + this.recordSourceMappingStart(arg.id); + this.writeToOutput("this." + arg.id.actualText); + this.recordSourceMappingEnd(arg.id); + this.writeToOutput(" = "); + this.recordSourceMappingStart(arg.id); + this.writeToOutput(arg.id.actualText); + this.recordSourceMappingEnd(arg.id); + this.writeLineToOutput(";"); + this.recordSourceMappingEnd(arg); + } + } + } + var nProps = (this.thisClassNode.members).members.length; + for(var iMember = 0; iMember < nProps; iMember++) { + if((this.thisClassNode.members).members[iMember].nodeType == TypeScript.NodeType.VarDecl) { + var varDecl = (this.thisClassNode.members).members[iMember]; + if(!TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static) && varDecl.init) { + this.emitIndent(); + this.emitJavascriptVarDecl(varDecl, TypeScript.TokenID.Tilde); + this.writeLineToOutput(""); + } + } + } + } + var emitNode = list.members[i]; + var isStaticDecl = (emitNode.nodeType == TypeScript.NodeType.FuncDecl && TypeScript.hasFlag((emitNode).fncFlags, TypeScript.FncFlags.Static)) || (emitNode.nodeType == TypeScript.NodeType.VarDecl && TypeScript.hasFlag((emitNode).varFlags, TypeScript.VarFlags.Static)); + if(onlyStatics ? !isStaticDecl : isStaticDecl) { + continue; + } + this.emitJavascript(emitNode, tokenId, startLine); + if(delimiter && (i < (len - 1))) { + if(startLine) { + this.writeLineToOutput(delimiter); + } else { + this.writeToOutput(delimiter); + } + } else if(startLine && (emitNode.nodeType != TypeScript.NodeType.ModuleDeclaration) && (emitNode.nodeType != TypeScript.NodeType.InterfaceDeclaration) && (!((emitNode.nodeType == TypeScript.NodeType.VarDecl) && ((((emitNode).varFlags) & TypeScript.VarFlags.Ambient) == TypeScript.VarFlags.Ambient) && (((emitNode).init) == null)) && this.varListCount() >= 0) && (emitNode.nodeType != TypeScript.NodeType.Block || (emitNode).isStatementBlock) && (emitNode.nodeType != TypeScript.NodeType.EndCode) && (emitNode.nodeType != TypeScript.NodeType.FuncDecl)) { + this.writeLineToOutput(""); + } + } + this.emitParensAndCommentsInPlace(ast, false); + } + }; + Emitter.prototype.emitJavascript = function (ast, tokenId, startLine) { + if(ast == null) { + return; + } + if(startLine && (this.indenter.indentAmt > 0) && (ast.nodeType != TypeScript.NodeType.List) && (ast.nodeType != TypeScript.NodeType.Block)) { + if((ast.nodeType != TypeScript.NodeType.InterfaceDeclaration) && (!((ast.nodeType == TypeScript.NodeType.VarDecl) && ((((ast).varFlags) & TypeScript.VarFlags.Ambient) == TypeScript.VarFlags.Ambient) && (((ast).init) == null)) && this.varListCount() >= 0) && (ast.nodeType != TypeScript.NodeType.EndCode) && ((ast.nodeType != TypeScript.NodeType.FuncDecl) || (this.emitState.container != EmitContainer.Constructor))) { + this.emitIndent(); + } + } + ast.emit(this, tokenId, startLine); + if((tokenId == TypeScript.TokenID.Semicolon) && (ast.nodeType < TypeScript.NodeType.GeneralNode)) { + this.writeToOutput(";"); + } + }; + Emitter.prototype.emitPropertyAccessor = function (funcDecl, className, isProto) { + if(!(funcDecl.accessorSymbol).hasBeenEmitted) { + var accessorSymbol = funcDecl.accessorSymbol; + this.emitIndent(); + this.recordSourceMappingStart(funcDecl); + this.writeLineToOutput("Object.defineProperty(" + className + (isProto ? ".prototype, \"" : ", \"") + funcDecl.name.actualText + "\"" + ", {"); + this.indenter.increaseIndent(); + if(accessorSymbol.getter) { + var getter = accessorSymbol.getter.declAST; + this.emitIndent(); + this.recordSourceMappingStart(getter); + this.writeToOutput("get: "); + this.emitInnerFunction(getter, false, isProto, null, Emitter.shouldCaptureThis(getter), null); + this.writeLineToOutput(","); + } + if(accessorSymbol.setter) { + var setter = accessorSymbol.setter.declAST; + this.emitIndent(); + this.recordSourceMappingStart(setter); + this.writeToOutput("set: "); + this.emitInnerFunction(setter, false, isProto, null, Emitter.shouldCaptureThis(setter), null); + this.writeLineToOutput(","); + } + this.emitIndent(); + this.writeLineToOutput("enumerable: true,"); + this.emitIndent(); + this.writeLineToOutput("configurable: true"); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeLineToOutput("});"); + this.recordSourceMappingEnd(funcDecl); + accessorSymbol.hasBeenEmitted = true; + } + }; + Emitter.prototype.emitPrototypeMember = function (member, className) { + if(member.nodeType == TypeScript.NodeType.FuncDecl) { + var funcDecl = member; + if(funcDecl.isAccessor()) { + this.emitPropertyAccessor(funcDecl, className, true); + } else { + this.emitIndent(); + this.recordSourceMappingStart(funcDecl); + this.writeToOutput(className + ".prototype." + funcDecl.getNameText() + " = "); + this.emitInnerFunction(funcDecl, false, true, null, Emitter.shouldCaptureThis(funcDecl), null); + this.writeLineToOutput(";"); + } + } else if(member.nodeType == TypeScript.NodeType.VarDecl) { + var varDecl = member; + if(varDecl.init) { + this.emitIndent(); + this.recordSourceMappingStart(varDecl); + this.recordSourceMappingStart(varDecl.id); + this.writeToOutput(className + ".prototype." + varDecl.id.actualText); + this.recordSourceMappingEnd(varDecl.id); + this.writeToOutput(" = "); + this.emitJavascript(varDecl.init, TypeScript.TokenID.Equals, false); + this.recordSourceMappingEnd(varDecl); + this.writeLineToOutput(";"); + } + } + }; + Emitter.prototype.emitAddBaseMethods = function (className, base, classDecl) { + if(base.members) { + var baseSymbol = base.symbol; + var baseName = baseSymbol.name; + if(baseSymbol.declModule != classDecl.type.symbol.declModule) { + baseName = baseSymbol.fullName(); + } + base.members.allMembers.map(function (key, s, c) { + var sym = s; + if((sym.kind() == TypeScript.SymbolKind.Type) && (sym).type.call) { + this.recordSourceMappingStart(sym.declAST); + this.writeLineToOutput(className + ".prototype." + sym.name + " = " + baseName + ".prototype." + sym.name + ";"); + this.recordSourceMappingEnd(sym.declAST); + } + }, null); + } + if(base.extendsList) { + for(var i = 0, len = base.extendsList.length; i < len; i++) { + this.emitAddBaseMethods(className, base.extendsList[i], classDecl); + } + } + }; + Emitter.prototype.emitJavascriptClass = function (classDecl) { + if(!TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Ambient)) { + var svClassNode = this.thisClassNode; + var i = 0; + this.thisClassNode = classDecl; + var className = classDecl.name.actualText; + this.emitParensAndCommentsInPlace(classDecl, true); + var temp = this.setContainer(EmitContainer.Class); + this.recordSourceMappingStart(classDecl); + if(TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Exported) && classDecl.type.symbol.container == this.checker.gloMod) { + this.writeToOutput("this." + className); + } else { + this.writeToOutput("var " + className); + } + var hasBaseClass = classDecl.extendsList && classDecl.extendsList.members.length; + var baseNameDecl = null; + var baseName = null; + if(hasBaseClass) { + this.writeLineToOutput(" = (function (_super) {"); + } else { + this.writeLineToOutput(" = (function () {"); + } + this.recordSourceMappingNameStart(className); + this.indenter.increaseIndent(); + if(hasBaseClass) { + baseNameDecl = classDecl.extendsList.members[0]; + baseName = baseNameDecl.nodeType == TypeScript.NodeType.Call ? (baseNameDecl).target : baseNameDecl; + this.emitIndent(); + this.writeLineToOutput("__extends(" + className + ", _super);"); + } + this.emitIndent(); + var constrDecl = classDecl.constructorDecl; + if(constrDecl) { + this.emitJavascript(classDecl.constructorDecl, TypeScript.TokenID.OpenParen, false); + } else { + var wroteProps = 0; + this.recordSourceMappingStart(classDecl); + this.indenter.increaseIndent(); + this.writeToOutput("function " + classDecl.name.actualText + "() {"); + this.recordSourceMappingNameStart("constructor"); + if(hasBaseClass) { + this.writeLineToOutput(""); + this.emitIndent(); + this.writeLineToOutput("_super.apply(this, arguments);"); + wroteProps++; + } + if(classDecl.varFlags & TypeScript.VarFlags.MustCaptureThis) { + this.writeCaptureThisStatement(classDecl); + } + var members = (this.thisClassNode.members).members; + for(var i = 0; i < members.length; i++) { + if(members[i].nodeType == TypeScript.NodeType.VarDecl) { + var varDecl = members[i]; + if(!TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static) && varDecl.init) { + this.writeLineToOutput(""); + this.emitIndent(); + this.emitJavascriptVarDecl(varDecl, TypeScript.TokenID.Tilde); + wroteProps++; + } + } + } + if(wroteProps) { + this.writeLineToOutput(""); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeLineToOutput("}"); + } else { + this.writeLineToOutput(" }"); + this.indenter.decreaseIndent(); + } + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(classDecl); + } + var membersLen = classDecl.members.members.length; + for(var j = 0; j < membersLen; j++) { + var memberDecl = classDecl.members.members[j]; + if(memberDecl.nodeType == TypeScript.NodeType.FuncDecl) { + var fn = memberDecl; + if(TypeScript.hasFlag(fn.fncFlags, TypeScript.FncFlags.Method) && !fn.isSignature()) { + if(!TypeScript.hasFlag(fn.fncFlags, TypeScript.FncFlags.Static)) { + this.emitPrototypeMember(fn, className); + } else { + if(fn.isAccessor()) { + this.emitPropertyAccessor(fn, this.thisClassNode.name.actualText, false); + } else { + this.emitIndent(); + this.recordSourceMappingStart(fn); + this.writeToOutput(classDecl.name.actualText + "." + fn.name.actualText + " = "); + this.emitInnerFunction(fn, (fn.name && !fn.name.isMissing()), true, null, Emitter.shouldCaptureThis(fn), null); + this.writeLineToOutput(";"); + } + } + } + } else if(memberDecl.nodeType == TypeScript.NodeType.VarDecl) { + var varDecl = memberDecl; + if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static)) { + if(varDecl.init) { + this.emitIndent(); + this.recordSourceMappingStart(varDecl); + this.writeToOutput(classDecl.name.actualText + "." + varDecl.id.actualText + " = "); + this.emitJavascript(varDecl.init, TypeScript.TokenID.Equals, false); + this.writeLineToOutput(";"); + this.recordSourceMappingEnd(varDecl); + } + } + } else { + throw Error("We want to catch this"); + } + } + this.emitIndent(); + this.recordSourceMappingStart(classDecl.endingToken); + this.writeLineToOutput("return " + className + ";"); + this.recordSourceMappingEnd(classDecl.endingToken); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.recordSourceMappingStart(classDecl.endingToken); + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(classDecl.endingToken); + this.recordSourceMappingStart(classDecl); + this.writeToOutput(")("); + if(hasBaseClass) { + this.emitJavascript(baseName, TypeScript.TokenID.Tilde, false); + } + this.writeToOutput(");"); + this.recordSourceMappingEnd(classDecl); + if((temp == EmitContainer.Module || temp == EmitContainer.DynamicModule) && TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Exported)) { + this.writeLineToOutput(""); + this.emitIndent(); + var modName = temp == EmitContainer.Module ? this.moduleName : "exports"; + this.recordSourceMappingStart(classDecl); + this.writeToOutput(modName + "." + className + " = " + className + ";"); + this.recordSourceMappingEnd(classDecl); + } + this.emitIndent(); + this.recordSourceMappingEnd(classDecl); + this.emitParensAndCommentsInPlace(classDecl, false); + this.setContainer(temp); + this.thisClassNode = svClassNode; + } + }; + Emitter.prototype.emitPrologue = function (reqInherits) { + if(!this.extendsPrologueEmitted) { + if(reqInherits) { + this.extendsPrologueEmitted = true; + this.writeLineToOutput("var __extends = this.__extends || function (d, b) {"); + this.writeLineToOutput(" function __() { this.constructor = d; }"); + this.writeLineToOutput(" __.prototype = b.prototype;"); + this.writeLineToOutput(" d.prototype = new __();"); + this.writeLineToOutput("};"); + } + } + if(!this.globalThisCapturePrologueEmitted) { + if(this.checker.mustCaptureGlobalThis) { + this.globalThisCapturePrologueEmitted = true; + this.writeLineToOutput(this.captureThisStmtString); + } + } + }; + Emitter.prototype.emitSuperReference = function () { + this.writeToOutput("_super.prototype"); + }; + Emitter.prototype.emitSuperCall = function (callEx) { + if(callEx.target.nodeType == TypeScript.NodeType.Dot) { + var dotNode = callEx.target; + if(dotNode.operand1.nodeType == TypeScript.NodeType.Super) { + this.emitJavascript(dotNode, TypeScript.TokenID.OpenParen, false); + this.writeToOutput(".call("); + this.emitThis(); + if(callEx.arguments && callEx.arguments.members.length > 0) { + this.writeToOutput(", "); + this.emitJavascriptList(callEx.arguments, ", ", TypeScript.TokenID.Comma, false, false, false); + } + this.writeToOutput(")"); + return true; + } + } + return false; + }; + Emitter.prototype.emitThis = function () { + if(this.thisFnc && !this.thisFnc.isMethod() && (!this.thisFnc.isConstructor)) { + this.writeToOutput("_this"); + } else { + this.writeToOutput("this"); + } + }; + Emitter.shouldCaptureThis = function shouldCaptureThis(func) { + return func.hasSelfReference() || func.hasSuperReferenceInFatArrowFunction(); + }; + Emitter.prototype.createFile = function (fileName, useUTF8) { + try { + return this.emitOptions.ioHost.createFile(fileName, useUTF8); + } catch (ex) { + this.errorReporter.emitterError(null, ex.message); + } + }; + return Emitter; + })(); + TypeScript.Emitter = Emitter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ErrorReporter = (function () { + function ErrorReporter(outfile) { + this.outfile = outfile; + this.parser = null; + this.checker = null; + this.lineCol = { + line: 0, + col: 0 + }; + this.emitAsComments = true; + this.hasErrors = false; + this.pushToErrorSink = false; + this.errorSink = []; + } + ErrorReporter.prototype.getCapturedErrors = function () { + return this.errorSink; + }; + ErrorReporter.prototype.freeCapturedErrors = function () { + this.errorSink = []; + }; + ErrorReporter.prototype.captureError = function (emsg) { + this.errorSink[this.errorSink.length] = emsg; + }; + ErrorReporter.prototype.setErrOut = function (outerr) { + this.outfile = outerr; + this.emitAsComments = false; + }; + ErrorReporter.prototype.emitPrefix = function () { + if(this.emitAsComments) { + this.outfile.Write("// "); + } + this.outfile.Write(this.checker.locationInfo.filename + "(" + this.lineCol.line + "," + this.lineCol.col + "): "); + }; + ErrorReporter.prototype.writePrefix = function (ast) { + if(ast) { + this.setError(ast); + } else { + this.lineCol.line = 0; + this.lineCol.col = 0; + } + this.emitPrefix(); + }; + ErrorReporter.prototype.writePrefixFromSym = function (symbol) { + if(symbol && this.checker.locationInfo.lineMap) { + TypeScript.getSourceLineColFromMap(this.lineCol, symbol.location, this.checker.locationInfo.lineMap); + } else { + this.lineCol.line = -1; + this.lineCol.col = -1; + } + this.emitPrefix(); + }; + ErrorReporter.prototype.setError = function (ast) { + if(ast) { + ast.flags |= TypeScript.ASTFlags.Error; + if(this.checker.locationInfo.lineMap) { + TypeScript.getSourceLineColFromMap(this.lineCol, ast.minChar, this.checker.locationInfo.lineMap); + } + } + }; + ErrorReporter.prototype.reportError = function (ast, message) { + if(this.pushToErrorSink) { + this.captureError(message); + return; + } + this.hasErrors = true; + if(ast && this.parser.errorRecovery && this.parser.errorCallback) { + var len = (ast.limChar - ast.minChar); + this.parser.errorCallback(ast.minChar, len, message, this.checker.locationInfo.unitIndex); + } else { + this.writePrefix(ast); + this.outfile.WriteLine(message); + } + }; + ErrorReporter.prototype.reportErrorFromSym = function (symbol, message) { + if(this.pushToErrorSink) { + this.captureError(message); + return; + } + this.hasErrors = true; + if(this.parser.errorRecovery && this.parser.errorCallback) { + this.parser.errorCallback(symbol.location, symbol.length, message, this.checker.locationInfo.unitIndex); + } else { + this.writePrefixFromSym(symbol); + this.outfile.WriteLine(message); + } + }; + ErrorReporter.prototype.emitterError = function (ast, message) { + this.reportError(ast, message); + throw Error("EmitError"); + }; + ErrorReporter.prototype.duplicateIdentifier = function (ast, name) { + this.reportError(ast, "Duplicate identifier '" + name + "'"); + }; + ErrorReporter.prototype.showRef = function (ast, text, symbol) { + var defLineCol = { + line: -1, + col: -1 + }; + this.parser.getSourceLineCol(defLineCol, symbol.location); + this.reportError(ast, "symbol " + text + " defined at (" + defLineCol.line + "," + defLineCol.col + ")"); + }; + ErrorReporter.prototype.unresolvedSymbol = function (ast, name) { + this.reportError(ast, "The name '" + name + "' does not exist in the current scope"); + }; + ErrorReporter.prototype.symbolDoesNotReferToAValue = function (ast, name) { + this.reportError(ast, "The name '" + name + "' does not refer to a value"); + }; + ErrorReporter.prototype.styleError = function (ast, msg) { + var bkThrow = this.pushToErrorSink; + this.pushToErrorSink = false; + this.reportError(ast, "STYLE: " + msg); + this.pushToErrorSink = bkThrow; + }; + ErrorReporter.prototype.simpleError = function (ast, msg) { + this.reportError(ast, msg); + }; + ErrorReporter.prototype.simpleErrorFromSym = function (sym, msg) { + this.reportErrorFromSym(sym, msg); + }; + ErrorReporter.prototype.invalidSuperReference = function (ast) { + this.simpleError(ast, "Keyword 'super' can only be used inside a class instance method"); + }; + ErrorReporter.prototype.valueCannotBeModified = function (ast) { + this.simpleError(ast, "The left-hand side of an assignment expression must be a variable, property or indexer"); + }; + ErrorReporter.prototype.invalidCall = function (ast, nodeType, scope) { + var targetType = ast.target.type; + var typeName = targetType.getScopedTypeName(scope); + if(targetType.construct && (nodeType == TypeScript.NodeType.Call)) { + this.reportError(ast, "Value of type '" + typeName + "' is not callable. Did you mean to include 'new'?"); + } else { + var catString = (nodeType == TypeScript.NodeType.Call) ? "callable" : "newable"; + this.reportError(ast, "Value of type '" + typeName + "' is not " + catString); + } + }; + ErrorReporter.prototype.indexLHS = function (ast, scope) { + var targetType = ast.operand1.type.getScopedTypeName(scope); + var indexType = ast.operand2.type.getScopedTypeName(scope); + this.simpleError(ast, "Value of type '" + targetType + "' is not indexable by type '" + indexType + "'"); + }; + ErrorReporter.prototype.incompatibleTypes = function (ast, t1, t2, op, scope, comparisonInfo) { + if(!t1) { + t1 = this.checker.anyType; + } + if(!t2) { + t2 = this.checker.anyType; + } + var reason = comparisonInfo ? comparisonInfo.message : ""; + if(op) { + this.reportError(ast, "Operator '" + op + "' cannot be applied to types '" + t1.getScopedTypeName(scope) + "' and '" + t2.getScopedTypeName(scope) + "'" + (reason ? ": " + reason : "")); + } else { + this.reportError(ast, "Cannot convert '" + t1.getScopedTypeName(scope) + "' to '" + t2.getScopedTypeName(scope) + "'" + (reason ? ": " + reason : "")); + } + }; + ErrorReporter.prototype.expectedClassOrInterface = function (ast) { + this.simpleError(ast, "Expected var, class, interface, or module"); + }; + ErrorReporter.prototype.unaryOperatorTypeError = function (ast, op, type) { + this.reportError(ast, "Operator '" + op + "' cannot be applied to type '" + type.getTypeName() + "'"); + }; + return ErrorReporter; + })(); + TypeScript.ErrorReporter = ErrorReporter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (TypeContext) { + TypeContext._map = []; + TypeContext.NoTypes = 0; + TypeContext.ArraySuffix = 1; + TypeContext.Primitive = 2; + TypeContext.Named = 4; + TypeContext.AllSimpleTypes = TypeContext.Primitive | TypeContext.Named; + TypeContext.AllTypes = TypeContext.Primitive | TypeContext.Named | TypeContext.ArraySuffix; + })(TypeScript.TypeContext || (TypeScript.TypeContext = {})); + var TypeContext = TypeScript.TypeContext; + var QuickParseResult = (function () { + function QuickParseResult(Script, endLexState) { + this.Script = Script; + this.endLexState = endLexState; + } + return QuickParseResult; + })(); + TypeScript.QuickParseResult = QuickParseResult; + var Parser = (function () { + function Parser() { + this.varLists = []; + this.scopeLists = []; + this.staticsLists = []; + this.scanner = new TypeScript.Scanner(); + this.currentToken = null; + this.needTerminator = false; + this.inFunction = false; + this.inInterfaceDecl = false; + this.currentClassDecl = null; + this.inFncDecl = false; + this.anonId = new TypeScript.Identifier("_anonymous"); + this.style_requireSemi = false; + this.style_funcInLoop = true; + this.incremental = false; + this.errorRecovery = false; + this.outfile = undefined; + this.errorCallback = null; + this.ambientModule = false; + this.ambientClass = false; + this.topLevel = true; + this.allowImportDeclaration = true; + this.currentUnitIndex = (-1); + this.prevIDTok = null; + this.statementInfoStack = new Array(); + this.hasTopLevelImportOrExport = false; + this.strictMode = false; + this.nestingLevel = 0; + this.prevExpr = null; + this.currentClassDefinition = null; + this.parsingClassConstructorDefinition = false; + this.parsingDeclareFile = false; + this.amdDependencies = []; + this.inferPropertiesFromThisAssignment = false; + this.requiresExtendsBlock = false; + this.fname = ""; + } + Parser.prototype.resetStmtStack = function () { + this.statementInfoStack = new Array(); + }; + Parser.prototype.inLoop = function () { + for(var j = this.statementInfoStack.length - 1; j >= 0; j--) { + if(this.statementInfoStack[j].stmt.isLoop()) { + return true; + } + } + return false; + }; + Parser.prototype.pushStmt = function (stmt, labels) { + var info = { + stmt: stmt, + labels: labels + }; + this.statementInfoStack.push(info); + }; + Parser.prototype.popStmt = function () { + return this.statementInfoStack.pop(); + }; + Parser.prototype.resolveJumpTarget = function (jump) { + var resolvedTarget = TypeScript.AST.getResolvedIdentifierName(jump.target); + var len = this.statementInfoStack.length; + for(var i = len - 1; i >= 0; i--) { + var info = this.statementInfoStack[i]; + if(jump.target) { + if(info.labels && (info.labels.members.length > 0)) { + for(var j = 0, labLen = info.labels.members.length; j < labLen; j++) { + var label = info.labels.members[j]; + if(label.id.text == resolvedTarget) { + jump.setResolvedTarget(this, info.stmt); + return; + } + } + } + } else { + if(info.stmt.isLoop()) { + jump.setResolvedTarget(this, info.stmt); + return; + } else if((info.stmt.nodeType == TypeScript.NodeType.Switch) && (jump.nodeType == TypeScript.NodeType.Break)) { + jump.setResolvedTarget(this, info.stmt); + return; + } + } + } + if(jump.target) { + this.reportParseError("could not find enclosing statement with label " + jump.target); + } else { + if(jump.nodeType == TypeScript.NodeType.Break) { + this.reportParseError("break statement requires enclosing loop or switch"); + } else { + this.reportParseError("continue statement requires enclosing loop"); + } + } + }; + Parser.prototype.setErrorRecovery = function (outfile) { + this.outfile = outfile; + this.errorRecovery = true; + }; + Parser.prototype.getSourceLineCol = function (lineCol, minChar) { + TypeScript.getSourceLineColFromMap(lineCol, minChar, this.scanner.lineMap); + }; + Parser.prototype.createRef = function (text, hasEscapeSequence, minChar) { + var id = new TypeScript.Identifier(text, hasEscapeSequence); + id.minChar = minChar; + return id; + }; + Parser.prototype.reportParseStyleError = function (message) { + this.reportParseError("STYLE: " + message); + }; + Parser.prototype.reportParseError = function (message, startPos, pos) { + if (typeof startPos === "undefined") { startPos = this.scanner.startPos; } + if (typeof pos === "undefined") { pos = this.scanner.pos; } + var len = Math.max(1, pos - startPos); + if(this.errorCallback) { + this.errorCallback(startPos, len, message, this.currentUnitIndex); + } else if(this.errorRecovery) { + var lineCol = { + line: -1, + col: -1 + }; + this.getSourceLineCol(lineCol, startPos); + if(this.outfile) { + this.outfile.WriteLine("// " + this.fname + " (" + lineCol.line + "," + lineCol.col + "): " + message); + } + } else { + throw new SyntaxError(this.fname + " (" + this.scanner.line + "," + this.scanner.col + "): " + message); + } + }; + Parser.prototype.checkNextToken = function (tokenId, errorRecoverySet, errorText) { + if (typeof errorText === "undefined") { errorText = null; } + this.currentToken = this.scanner.scan(); + this.checkCurrentToken(tokenId, errorRecoverySet, errorText); + }; + Parser.prototype.skip = function (errorRecoverySet) { + errorRecoverySet |= TypeScript.ErrorRecoverySet.EOF; + var ersTok = TypeScript.ErrorRecoverySet.None; + var tokenInfo = TypeScript.lookupToken(this.currentToken.tokenId); + if(tokenInfo != undefined) { + ersTok = tokenInfo.ers; + } + var pendingRightCurlies = 0; + while(((ersTok & errorRecoverySet) == TypeScript.ErrorRecoverySet.None) || (this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) && (pendingRightCurlies > 0)) { + if(this.currentToken.tokenId == TypeScript.TokenID.OpenBrace) { + pendingRightCurlies++; + } else if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { + pendingRightCurlies--; + } + this.currentToken = this.scanner.scan(); + ersTok = TypeScript.ErrorRecoverySet.None; + tokenInfo = TypeScript.lookupToken(this.currentToken.tokenId); + if(tokenInfo != undefined) { + ersTok = tokenInfo.ers; + } + } + }; + Parser.prototype.checkCurrentToken = function (tokenId, errorRecoverySet, errorText) { + if (typeof errorText === "undefined") { errorText = null; } + if(this.currentToken.tokenId != tokenId) { + errorText = errorText == null ? ("Expected '" + TypeScript.tokenTable[tokenId].text + "'") : errorText; + this.reportParseError(errorText); + if(this.errorRecovery) { + this.skip(errorRecoverySet); + } + } else { + this.currentToken = this.scanner.scan(); + } + }; + Parser.prototype.pushDeclLists = function () { + this.staticsLists.push(new TypeScript.ASTList()); + this.varLists.push(new TypeScript.ASTList()); + this.scopeLists.push(new TypeScript.ASTList()); + }; + Parser.prototype.popDeclLists = function () { + this.staticsLists.pop(); + this.varLists.pop(); + this.scopeLists.pop(); + }; + Parser.prototype.topVarList = function () { + return this.varLists[this.varLists.length - 1]; + }; + Parser.prototype.topScopeList = function () { + return this.scopeLists[this.scopeLists.length - 1]; + }; + Parser.prototype.topStaticsList = function () { + return this.staticsLists[this.staticsLists.length - 1]; + }; + Parser.prototype.parseComment = function (comment) { + if(comment) { + var c = new TypeScript.Comment(comment.value, comment.isBlock, comment.endsLine); + c.minChar = comment.startPos; + c.limChar = comment.startPos + comment.value.length; + var lineCol = { + line: -1, + col: -1 + }; + this.getSourceLineCol(lineCol, c.minChar); + c.minLine = lineCol.line; + this.getSourceLineCol(lineCol, c.limChar); + c.limLine = lineCol.line; + if(!comment.isBlock && comment.value.length > 3 && comment.value.substring(0, 3) == "///") { + var dependencyPath = TypeScript.getAdditionalDependencyPath(comment.value); + if(dependencyPath) { + this.amdDependencies.push(dependencyPath); + } + if(TypeScript.getImplicitImport(comment.value)) { + this.hasTopLevelImportOrExport = true; + } + } + return c; + } else { + return null; + } + }; + Parser.prototype.parseCommentsInner = function (comments) { + if(comments) { + var commentASTs = new Array(); + for(var i = 0; i < comments.length; i++) { + commentASTs.push(this.parseComment(comments[i])); + } + return commentASTs; + } else { + return null; + } + }; + Parser.prototype.parseComments = function () { + var comments = this.scanner.getComments(); + return this.parseCommentsInner(comments); + }; + Parser.prototype.parseCommentsForLine = function (line) { + var comments = this.scanner.getCommentsForLine(line); + return this.parseCommentsInner(comments); + }; + Parser.prototype.combineComments = function (comment1, comment2) { + if(comment1 == null) { + return comment2; + } else if(comment2 == null) { + return comment1; + } else { + return comment1.concat(comment2); + } + }; + Parser.prototype.parseEnumDecl = function (errorRecoverySet, modifiers) { + var leftCurlyCount = this.scanner.leftCurlyCount; + var rightCurlyCount = this.scanner.rightCurlyCount; + var name = null; + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + name = TypeScript.Identifier.fromToken(this.currentToken); + name.minChar = this.scanner.startPos; + name.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + } else { + this.reportParseError("Enum declaration requires identifier"); + if(this.errorRecovery) { + name = new TypeScript.MissingIdentifier(); + name.minChar = this.scanner.startPos; + name.limChar = this.scanner.startPos; + name.flags |= TypeScript.ASTFlags.Error; + } + } + var membersMinChar = this.scanner.startPos; + this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.ID); + this.pushDeclLists(); + var members = new TypeScript.ASTList(); + members.minChar = membersMinChar; + var mapDecl = new TypeScript.VarDecl(new TypeScript.Identifier("_map"), 0); + mapDecl.varFlags |= TypeScript.VarFlags.Exported; + mapDecl.varFlags |= TypeScript.VarFlags.Private; + mapDecl.varFlags |= (TypeScript.VarFlags.Property | TypeScript.VarFlags.Public); + mapDecl.init = new TypeScript.UnaryExpression(TypeScript.NodeType.ArrayLit, null); + members.append(mapDecl); + var lastValue = null; + var memberNames = []; + for(; ; ) { + var minChar = this.scanner.startPos; + var limChar; + var memberName = null; + var memberValue = null; + var preComments = null; + var postComments = null; + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToIDName(this.currentToken)) { + memberName = TypeScript.Identifier.fromToken(this.currentToken); + memberName.minChar = this.scanner.startPos; + memberName.limChar = this.scanner.pos; + memberNames.push(memberName); + } else if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { + break; + } else { + this.reportParseError("Expected identifer of enum member"); + if(this.errorRecovery) { + memberName = new TypeScript.MissingIdentifier(); + memberName.minChar = this.scanner.startPos; + memberName.limChar = this.scanner.startPos; + memberName.flags |= TypeScript.ASTFlags.Error; + } + } + limChar = this.scanner.pos; + preComments = this.parseComments(); + this.currentToken = this.scanner.scan(); + postComments = this.parseComments(); + if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { + this.currentToken = this.scanner.scan(); + memberValue = this.parseExpr(errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); + lastValue = memberValue; + limChar = memberValue.limChar; + } else { + if(lastValue == null) { + memberValue = new TypeScript.NumberLiteral(0, "0"); + lastValue = memberValue; + } else { + var nextValue = lastValue.value + 1; + memberValue = new TypeScript.NumberLiteral(nextValue, nextValue.toString()); + lastValue = memberValue; + } + var map = new TypeScript.BinaryExpression(TypeScript.NodeType.Asg, new TypeScript.BinaryExpression(TypeScript.NodeType.Index, new TypeScript.Identifier("_map"), memberValue), new TypeScript.StringLiteral('"' + memberName.actualText + '"')); + members.append(map); + } + var member = new TypeScript.VarDecl(memberName, this.nestingLevel); + member.minChar = minChar; + member.limChar = limChar; + member.init = memberValue; + member.typeExpr = new TypeScript.TypeReference(this.createRef(name.actualText, name.hasEscapeSequence, -1), 0); + member.varFlags |= (TypeScript.VarFlags.Readonly | TypeScript.VarFlags.Property); + if(memberValue.nodeType == TypeScript.NodeType.NumberLit) { + member.varFlags |= TypeScript.VarFlags.Constant; + } else if(memberValue.nodeType === TypeScript.NodeType.Lsh) { + var binop = memberValue; + if(binop.operand1.nodeType === TypeScript.NodeType.NumberLit && binop.operand2.nodeType === TypeScript.NodeType.NumberLit) { + member.varFlags |= TypeScript.VarFlags.Constant; + } + } else if(memberValue.nodeType === TypeScript.NodeType.Name) { + var nameNode = memberValue; + for(var i = 0; i < memberNames.length; i++) { + var memberName = memberNames[i]; + if(memberName.text === nameNode.text) { + member.varFlags |= TypeScript.VarFlags.Constant; + break; + } + } + } + member.preComments = preComments; + members.append(member); + member.postComments = postComments; + member.varFlags |= TypeScript.VarFlags.Exported; + if(this.currentToken.tokenId == TypeScript.TokenID.Comma) { + this.currentToken = this.scanner.scan(); + member.postComments = this.combineComments(member.postComments, this.parseCommentsForLine(this.scanner.prevLine)); + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || (TypeScript.convertTokToIDName(this.currentToken))) { + continue; + } + } + break; + } + var endingToken = new TypeScript.ASTSpan(); + endingToken.minChar = this.scanner.startPos; + endingToken.limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); + members.limChar = this.scanner.lastTokenLimChar(); + var modDecl = new TypeScript.ModuleDeclaration(name, members, this.topVarList(), endingToken); + modDecl.modFlags |= TypeScript.ModuleFlags.IsEnum; + this.popDeclLists(); + modDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; + modDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; + return modDecl; + }; + Parser.prototype.parseDottedName = function (enclosedList) { + this.currentToken = this.scanner.scan(); + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + var id = TypeScript.Identifier.fromToken(this.currentToken); + id.preComments = this.parseComments(); + enclosedList[enclosedList.length] = id; + id.minChar = this.scanner.startPos; + id.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.Dot) { + this.parseDottedName(enclosedList); + } + } else { + this.reportParseError("need identifier after '.'"); + } + }; + Parser.prototype.isValidImportPath = function (importPath) { + importPath = TypeScript.stripQuotes(importPath); + if(!importPath || importPath.indexOf(':') != -1 || importPath.indexOf('\\') != -1 || importPath.charAt(0) == '/') { + return false; + } + return true; + }; + Parser.prototype.parseImportDeclaration = function (errorRecoverySet, modifiers) { + var name = null; + var alias = null; + var importDecl = null; + var minChar = this.scanner.startPos; + var isDynamicImport = false; + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + name = TypeScript.Identifier.fromToken(this.currentToken); + } else { + this.reportParseError("Expected identifer after 'import'"); + name = new TypeScript.MissingIdentifier(); + } + name.minChar = this.scanner.startPos; + name.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + this.checkCurrentToken(TypeScript.TokenID.Equals, errorRecoverySet | TypeScript.ErrorRecoverySet.ID); + var aliasPreComments = this.parseComments(); + var limChar; + if(this.currentToken.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + if(this.currentToken.tokenId == TypeScript.TokenID.Module) { + limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.StringLiteral || this.currentToken.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + if(this.currentToken.tokenId == TypeScript.TokenID.StringLiteral) { + if(this.topLevel) { + this.hasTopLevelImportOrExport = true; + } else if(!this.allowImportDeclaration) { + this.reportParseError("Import declaration of external module is permitted only in global or top level dynamic modules"); + } + var aliasText = this.currentToken.getText(); + alias = TypeScript.Identifier.fromToken(this.currentToken); + alias.minChar = this.scanner.startPos; + alias.limChar = this.scanner.pos; + if(!this.isValidImportPath((alias).text)) { + this.reportParseError("Invalid import path"); + } + isDynamicImport = true; + this.currentToken = this.scanner.scan(); + alias.preComments = aliasPreComments; + } else { + alias = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.Assignment, true, TypeContext.NoTypes); + alias.preComments = aliasPreComments; + } + } + limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ID); + if(alias) { + alias.postComments = this.parseComments(); + } + } + } else { + alias = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.Assignment, true, TypeContext.NoTypes); + limChar = this.scanner.pos; + } + } else { + this.reportParseError("Expected module name"); + alias = new TypeScript.MissingIdentifier(); + alias.minChar = this.scanner.startPos; + if(this.currentToken.tokenId == TypeScript.TokenID.Semicolon) { + alias.limChar = this.scanner.startPos; + } else { + alias.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + } + alias.flags |= TypeScript.ASTFlags.Error; + limChar = alias.limChar; + } + importDecl = new TypeScript.ImportDeclaration(name, alias); + importDecl.isDynamicImport = isDynamicImport; + importDecl.minChar = minChar; + importDecl.limChar = limChar; + return importDecl; + }; + Parser.prototype.parseModuleDecl = function (errorRecoverySet, modifiers, preComments) { + var leftCurlyCount = this.scanner.leftCurlyCount; + var rightCurlyCount = this.scanner.rightCurlyCount; + var svAmbient = this.ambientModule; + var svTopLevel = this.topLevel; + this.topLevel = false; + if(this.parsingDeclareFile || svAmbient || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + this.ambientModule = true; + } + this.currentToken = this.scanner.scan(); + var name = null; + var enclosedList = null; + this.pushDeclLists(); + var minChar = this.scanner.startPos; + var isDynamicMod = false; + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || (this.currentToken.tokenId == TypeScript.TokenID.StringLiteral) || (!TypeScript.isPrimitiveTypeToken(this.currentToken) && TypeScript.convertTokToID(this.currentToken, this.strictMode))) { + var nameText = this.currentToken.getText(); + if(this.currentToken.tokenId == TypeScript.TokenID.StringLiteral) { + isDynamicMod = true; + if(!this.ambientModule) { + this.reportParseError("Only ambient dynamic modules may have string literal names"); + } + if(!svTopLevel) { + this.reportParseError("Dynamic modules may not be nested within other modules"); + } + } + name = TypeScript.Identifier.fromToken(this.currentToken); + name.minChar = this.scanner.startPos; + name.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + } else if(this.currentToken.tokenId == TypeScript.TokenID.OpenBrace) { + this.reportParseError("Module name missing"); + name = new TypeScript.Identifier(""); + name.minChar = minChar; + name.limChar = minChar; + } + if(this.currentToken.tokenId == TypeScript.TokenID.Dot) { + enclosedList = new Array(); + this.parseDottedName(enclosedList); + } + if(name == null) { + name = new TypeScript.MissingIdentifier(); + } + var moduleBody = new TypeScript.ASTList(); + var bodyMinChar = this.scanner.startPos; + this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.ID); + if(svTopLevel && isDynamicMod) { + this.allowImportDeclaration = true; + } else { + this.allowImportDeclaration = false; + } + this.parseStatementList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, moduleBody, true, true, TypeScript.AllowedElements.Global, modifiers); + moduleBody.minChar = bodyMinChar; + moduleBody.limChar = this.scanner.pos; + var endingToken = new TypeScript.ASTSpan(); + endingToken.minChar = this.scanner.startPos; + endingToken.limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); + var limChar = this.scanner.lastTokenLimChar(); + var moduleDecl; + this.allowImportDeclaration = svTopLevel; + if(enclosedList && (enclosedList.length > 0)) { + var len = enclosedList.length; + var innerName = enclosedList[len - 1]; + var innerDecl = new TypeScript.ModuleDeclaration(innerName, moduleBody, this.topVarList(), endingToken); + innerDecl.preComments = preComments; + if(this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + innerDecl.modFlags |= TypeScript.ModuleFlags.Ambient; + } + innerDecl.modFlags |= TypeScript.ModuleFlags.Exported; + innerDecl.minChar = minChar; + innerDecl.limChar = limChar; + this.popDeclLists(); + var outerModBod; + for(var i = len - 2; i >= 0; i--) { + outerModBod = new TypeScript.ASTList(); + outerModBod.append(innerDecl); + innerName = enclosedList[i]; + innerDecl = new TypeScript.ModuleDeclaration(innerName, outerModBod, new TypeScript.ASTList(), endingToken); + outerModBod.minChar = innerDecl.minChar = minChar; + outerModBod.limChar = innerDecl.limChar = limChar; + if(this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + innerDecl.modFlags |= TypeScript.ModuleFlags.Ambient; + } + innerDecl.modFlags |= TypeScript.ModuleFlags.Exported; + } + outerModBod = new TypeScript.ASTList(); + outerModBod.append(innerDecl); + outerModBod.minChar = minChar; + outerModBod.limChar = limChar; + moduleDecl = new TypeScript.ModuleDeclaration(name, outerModBod, new TypeScript.ASTList(), endingToken); + } else { + moduleDecl = new TypeScript.ModuleDeclaration(name, moduleBody, this.topVarList(), endingToken); + moduleDecl.preComments = preComments; + this.popDeclLists(); + } + if(this.parsingDeclareFile || svAmbient || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + moduleDecl.modFlags |= TypeScript.ModuleFlags.Ambient; + } + if(svAmbient || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { + moduleDecl.modFlags |= TypeScript.ModuleFlags.Exported; + } + if(isDynamicMod) { + moduleDecl.modFlags |= TypeScript.ModuleFlags.IsDynamic; + } + this.ambientModule = svAmbient; + this.topLevel = svTopLevel; + moduleDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; + moduleDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; + moduleDecl.limChar = moduleBody.limChar; + return moduleDecl; + }; + Parser.prototype.parseTypeReferenceTail = function (errorRecoverySet, minChar, term) { + var result = new TypeScript.TypeReference(term, 0); + result.minChar = minChar; + while(this.currentToken.tokenId == TypeScript.TokenID.OpenBracket) { + this.currentToken = this.scanner.scan(); + result.arrayCount++; + this.checkCurrentToken(TypeScript.TokenID.CloseBracket, errorRecoverySet | TypeScript.ErrorRecoverySet.LBrack); + } + result.limChar = this.scanner.lastTokenLimChar(); + return result; + }; + Parser.prototype.parseNamedType = function (errorRecoverySet, minChar, term, tail) { + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.Dot) { + var curpos = this.scanner.pos; + this.currentToken = this.scanner.scan(); + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || ((!this.errorRecovery || !this.scanner.lastTokenHadNewline()) && TypeScript.convertTokToID(this.currentToken, this.strictMode))) { + var op2 = TypeScript.Identifier.fromToken(this.currentToken); + op2.minChar = this.scanner.startPos; + op2.limChar = this.scanner.pos; + var dotNode = new TypeScript.BinaryExpression(TypeScript.NodeType.Dot, term, op2); + dotNode.minChar = term.minChar; + dotNode.limChar = op2.limChar; + return this.parseNamedType(errorRecoverySet, minChar, dotNode, tail); + } else { + this.reportParseError("need identifier after '.'"); + if(this.errorRecovery) { + term.flags |= TypeScript.ASTFlags.DotLHS; + term.limChar = this.scanner.lastTokenLimChar(); + return term; + } else { + var eop2 = new TypeScript.MissingIdentifier(); + eop2.minChar = this.scanner.pos; + eop2.limChar = this.scanner.pos; + var edotNode = new TypeScript.BinaryExpression(TypeScript.NodeType.Dot, term, eop2); + edotNode.flags |= TypeScript.ASTFlags.Error; + edotNode.minChar = term.minChar; + edotNode.limChar = eop2.limChar; + return this.parseNamedType(errorRecoverySet, minChar, edotNode, tail); + } + } + } else { + if(tail) { + return this.parseTypeReferenceTail(errorRecoverySet, minChar, term); + } else { + return term; + } + } + }; + Parser.prototype.parseTypeReference = function (errorRecoverySet, allowVoid) { + var minChar = this.scanner.startPos; + var isConstructorMember = false; + switch(this.currentToken.tokenId) { + case TypeScript.TokenID.Void: + if(!allowVoid) { + this.reportParseError("void not a valid type in this context"); + } + case TypeScript.TokenID.Any: + case TypeScript.TokenID.Number: + case TypeScript.TokenID.Bool: + case TypeScript.TokenID.String: { + var text = TypeScript.tokenTable[this.currentToken.tokenId].text; + var predefinedIdentifier = new TypeScript.Identifier(text); + predefinedIdentifier.minChar = minChar; + predefinedIdentifier.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + return this.parseTypeReferenceTail(errorRecoverySet, minChar, predefinedIdentifier); + } + case TypeScript.TokenID.Identifier: + var ident = this.createRef(this.currentToken.getText(), (this.currentToken).hasEscapeSequence, minChar); + ident.limChar = this.scanner.pos; + return this.parseNamedType(errorRecoverySet, minChar, ident, true); + case TypeScript.TokenID.OpenBrace: + return this.parseObjectType(minChar, errorRecoverySet); + case TypeScript.TokenID.New: + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId != TypeScript.TokenID.OpenParen) { + this.reportParseError("Expected '('"); + } else { + isConstructorMember = true; + } + case TypeScript.TokenID.OpenParen: { + var formals = new TypeScript.ASTList(); + var variableArgList = this.parseFormalParameterList(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, formals, false, true, false, false, false, false, null, true); + this.checkCurrentToken(TypeScript.TokenID.EqualsGreaterThan, errorRecoverySet); + var returnType = this.parseTypeReference(errorRecoverySet, true); + var funcDecl = new TypeScript.FuncDecl(null, null, false, formals, null, null, null, TypeScript.NodeType.FuncDecl); + funcDecl.returnTypeAnnotation = returnType; + funcDecl.variableArgList = variableArgList; + funcDecl.fncFlags |= TypeScript.FncFlags.Signature; + if(isConstructorMember) { + funcDecl.fncFlags |= TypeScript.FncFlags.ConstructMember; + funcDecl.hint = "_construct"; + funcDecl.classDecl = null; + } + funcDecl.minChar = minChar; + return this.parseTypeReferenceTail(errorRecoverySet, minChar, funcDecl); + } + default: + this.reportParseError("Expected type name"); + var etr = new TypeScript.TypeReference(null, 0); + etr.flags |= TypeScript.ASTFlags.Error; + etr.minChar = this.scanner.pos; + etr.limChar = this.scanner.pos; + return etr; + } + }; + Parser.prototype.parseObjectType = function (minChar, errorRecoverySet) { + this.currentToken = this.scanner.scan(); + var members = new TypeScript.ASTList(); + members.minChar = minChar; + var prevInInterfaceDecl = this.inInterfaceDecl; + this.inInterfaceDecl = true; + this.parseTypeMemberList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, members); + this.inInterfaceDecl = prevInInterfaceDecl; + this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); + var interfaceDecl = new TypeScript.InterfaceDeclaration(this.anonId, members, null, null); + interfaceDecl.minChar = minChar; + interfaceDecl.limChar = members.limChar; + return this.parseTypeReferenceTail(errorRecoverySet, minChar, interfaceDecl); + }; + Parser.prototype.parseFunctionBlock = function (errorRecoverySet, allowedElements, parentModifiers, bod, bodMinChar) { + this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); + var savedInFunction = this.inFunction; + this.inFunction = true; + this.parseStatementList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly | TypeScript.ErrorRecoverySet.StmtStart, bod, true, false, allowedElements, parentModifiers); + bod.minChar = bodMinChar; + bod.limChar = this.scanner.pos; + this.inFunction = savedInFunction; + if(bod.limChar > bod.minChar) { + var ec = new TypeScript.EndCode(); + ec.minChar = bod.limChar; + ec.limChar = ec.minChar; + bod.append(ec); + } + }; + Parser.prototype.parseFunctionStatements = function (errorRecoverySet, name, isConstructor, isMethod, args, allowedElements, minChar, requiresSignature, parentModifiers) { + this.pushDeclLists(); + var svStmtStack = this.statementInfoStack; + this.resetStmtStack(); + var bod = null; + var wasShorthand = false; + var isAnonLambda = false; + var limChar; + if(requiresSignature) { + limChar = this.scanner.pos; + if(this.currentToken.tokenId === TypeScript.TokenID.OpenBrace) { + this.reportParseError("Function declarations are not permitted within interfaces, ambient modules or classes"); + bod = new TypeScript.ASTList(); + var bodMinChar = this.scanner.startPos; + this.parseFunctionBlock(errorRecoverySet, allowedElements, parentModifiers, bod, bodMinChar); + this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); + if(this.currentToken.tokenId === TypeScript.TokenID.Semicolon) { + this.currentToken = this.scanner.scan(); + } + } else { + this.checkCurrentToken(TypeScript.TokenID.Semicolon, errorRecoverySet, "Expected ';'"); + } + } else { + bod = new TypeScript.ASTList(); + var bodMinChar = this.scanner.startPos; + if(this.currentToken.tokenId == TypeScript.TokenID.EqualsGreaterThan) { + if(isMethod) { + this.reportParseError("'=>' may not be used for class methods"); + } + wasShorthand = true; + this.currentToken = this.scanner.scan(); + } + if(wasShorthand && this.currentToken.tokenId != TypeScript.TokenID.OpenBrace) { + var retExpr = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.Assignment, true, TypeContext.NoTypes); + var retStmt = new TypeScript.ReturnStatement(); + retStmt.returnExpression = retExpr; + retStmt.minChar = retExpr.minChar; + retStmt.limChar = retExpr.limChar; + bod.minChar = bodMinChar; + bod.limChar = retExpr.limChar; + bod.append(retStmt); + } else if(this.currentToken.tokenId != TypeScript.TokenID.EndOfFile) { + isAnonLambda = wasShorthand; + this.parseFunctionBlock(errorRecoverySet, allowedElements, parentModifiers, bod, bodMinChar); + } + limChar = this.scanner.pos; + } + var funcDecl = new TypeScript.FuncDecl(name, bod, isConstructor, args, this.topVarList(), this.topScopeList(), this.topStaticsList(), TypeScript.NodeType.FuncDecl); + this.popDeclLists(); + var scopeList = this.topScopeList(); + scopeList.append(funcDecl); + var staticFuncDecl = false; + if(!requiresSignature) { + if(!wasShorthand || isAnonLambda) { + funcDecl.endingToken = new TypeScript.ASTSpan(); + funcDecl.endingToken.minChar = this.scanner.startPos; + funcDecl.endingToken.limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); + if(isAnonLambda) { + funcDecl.fncFlags |= TypeScript.FncFlags.IsFatArrowFunction; + } + } else { + funcDecl.fncFlags |= TypeScript.FncFlags.IsFatArrowFunction; + funcDecl.endingToken = new TypeScript.ASTSpan(); + funcDecl.endingToken.minChar = bod.members[0].minChar; + funcDecl.endingToken.limChar = bod.members[0].limChar; + } + } + funcDecl.minChar = minChar; + funcDecl.limChar = limChar; + if(requiresSignature) { + funcDecl.fncFlags |= TypeScript.FncFlags.Signature; + } + this.statementInfoStack = svStmtStack; + return funcDecl; + }; + Parser.prototype.transformAnonymousArgsIntoFormals = function (formals, argList) { + var _this = this; + var translateBinExOperand = function (operand) { + if(operand.nodeType == TypeScript.NodeType.Comma) { + return _this.transformAnonymousArgsIntoFormals(formals, operand); + } else if(operand.nodeType == TypeScript.NodeType.Name || operand.nodeType == TypeScript.NodeType.Asg) { + var opArg = operand.nodeType == TypeScript.NodeType.Asg ? (operand).operand1 : operand; + opArg.isParenthesized = false; + var arg = new TypeScript.ArgDecl(opArg); + arg.preComments = opArg.preComments; + arg.postComments = opArg.postComments; + arg.minChar = operand.minChar; + arg.limChar = operand.limChar; + if(TypeScript.hasFlag(opArg.flags, TypeScript.ASTFlags.PossibleOptionalParameter)) { + arg.isOptional = true; + } + if(operand.nodeType == TypeScript.NodeType.Asg) { + arg.init = (operand).operand2; + } + formals.append(arg); + return arg.isOptional || arg.init; + } else { + _this.reportParseError("Invalid lambda argument"); + } + return false; + }; + if(argList) { + if(argList.nodeType == TypeScript.NodeType.Comma) { + var commaList = argList; + if(commaList.operand1.isParenthesized) { + this.reportParseError("Invalid lambda argument", commaList.operand1.minChar, commaList.operand1.limChar); + } + if(commaList.operand2.isParenthesized) { + this.reportParseError("Invalid lambda argument", commaList.operand2.minChar, commaList.operand2.limChar); + } + var isOptional = translateBinExOperand(commaList.operand1); + isOptional = translateBinExOperand(commaList.operand2) || isOptional; + return isOptional; + } else { + return translateBinExOperand(argList); + } + } + }; + Parser.prototype.parseFormalParameterList = function (errorRecoverySet, formals, isClassConstr, isSig, isIndexer, isGetter, isSetter, isLambda, preProcessedLambdaArgs, expectClosingRParen) { + formals.minChar = this.scanner.startPos; + if(isIndexer) { + this.currentToken = this.scanner.scan(); + } else if(!isLambda) { + this.checkCurrentToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.RParen); + } + var sawEllipsis = false; + var firstArg = true; + var hasOptional = false; + var haveFirstArgID = false; + if(isLambda && preProcessedLambdaArgs && preProcessedLambdaArgs.nodeType != TypeScript.NodeType.EmptyExpr) { + hasOptional = this.transformAnonymousArgsIntoFormals(formals, preProcessedLambdaArgs); + formals.minChar = preProcessedLambdaArgs.minChar; + haveFirstArgID = true; + } + while(true) { + var munchedArg = false; + var argFlags = TypeScript.VarFlags.None; + var argMinChar = this.scanner.startPos; + if(this.inferPropertiesFromThisAssignment && this.currentToken.tokenId == TypeScript.TokenID.This) { + if(!isClassConstr) { + this.reportParseError("Instance property declarations using 'this' may only be used in class constructors"); + } + this.currentToken = this.scanner.scan(); + argFlags |= (TypeScript.VarFlags.Public | TypeScript.VarFlags.Property); + if(this.currentClassDefinition) { + this.currentClassDefinition.varFlags |= TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor; + } + } + if(this.currentToken.tokenId == TypeScript.TokenID.Public) { + argFlags |= (TypeScript.VarFlags.Public | TypeScript.VarFlags.Property); + if(this.currentClassDefinition) { + this.currentClassDefinition.varFlags |= TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor; + } + } else if(this.currentToken.tokenId == TypeScript.TokenID.Private) { + argFlags |= (TypeScript.VarFlags.Private | TypeScript.VarFlags.Property); + if(this.currentClassDefinition) { + this.currentClassDefinition.varFlags |= TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor; + } + } else if(this.currentToken.tokenId == TypeScript.TokenID.Static && isClassConstr) { + this.reportParseError("Static properties can not be declared as parameter properties"); + this.currentToken = this.scanner.scan(); + } + if(argFlags != TypeScript.VarFlags.None) { + if(!isClassConstr) { + this.reportParseError("only constructor parameters can be properties"); + } + this.currentToken = this.scanner.scan(); + if(TypeScript.isModifier(this.currentToken)) { + this.reportParseError("Multiple modifiers may not be applied to parameters"); + this.currentToken = this.scanner.scan(); + } + if(this.inferPropertiesFromThisAssignment && this.currentToken.tokenId == TypeScript.TokenID.This) { + if(!isClassConstr) { + this.reportParseError("Instance property declarations using 'this' may only be used in class constructors"); + } + this.currentToken = this.scanner.scan(); + this.currentToken = this.scanner.scan(); + } + } else if(this.currentToken.tokenId == TypeScript.TokenID.DotDotDot) { + sawEllipsis = true; + this.currentToken = this.scanner.scan(); + if(!(this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + this.reportParseError("'...' parameters require both a parameter name and an array type annotation to be specified"); + sawEllipsis = false; + } + } + var argId = null; + if(!haveFirstArgID && (this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + argId = TypeScript.Identifier.fromToken(this.currentToken); + argId.minChar = this.scanner.startPos; + argId.limChar = this.scanner.pos; + } + if(haveFirstArgID || argId) { + munchedArg = true; + var type = null; + var arg = null; + if(haveFirstArgID && formals.members.length) { + arg = formals.members[formals.members.length - 1]; + if(arg.isOptional) { + hasOptional = true; + } + } else { + arg = new TypeScript.ArgDecl(argId); + if(isGetter) { + this.reportParseError("Property getters may not take any arguments"); + } + if(isSetter && !firstArg) { + this.reportParseError("Property setters may only take one argument"); + } + arg.minChar = argMinChar; + arg.preComments = this.parseComments(); + this.currentToken = this.scanner.scan(); + } + if(this.currentToken.tokenId == TypeScript.TokenID.Question) { + arg.isOptional = true; + hasOptional = true; + this.currentToken = this.scanner.scan(); + } + if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { + this.currentToken = this.scanner.scan(); + type = this.parseTypeReference(errorRecoverySet, false); + } + if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { + if(isSig) { + this.reportParseError("Arguments in signatures may not have default values"); + } + hasOptional = true; + this.currentToken = this.scanner.scan(); + arg.init = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, false, TypeContext.NoTypes); + } + if(hasOptional && !arg.isOptionalArg() && !sawEllipsis) { + this.reportParseError("Optional parameters may only be followed by other optional parameters"); + } + if(sawEllipsis && arg.isOptionalArg()) { + this.reportParseError("Varargs may not be optional or have default parameters"); + } + if(sawEllipsis && !type) { + this.reportParseError("'...' parameters require both a parameter name and an array type annotation to be specified"); + } + arg.postComments = this.parseComments(); + arg.typeExpr = type; + arg.limChar = this.scanner.lastTokenLimChar(); + arg.varFlags |= argFlags; + if(!haveFirstArgID) { + formals.append(arg); + } else { + haveFirstArgID = false; + } + } + firstArg = false; + if(this.currentToken.tokenId == TypeScript.TokenID.Comma) { + if((munchedArg) && (!sawEllipsis)) { + this.currentToken = this.scanner.scan(); + continue; + } else { + this.reportParseError("Unexpected ',' in argument list"); + if(this.errorRecovery) { + this.currentToken = this.scanner.scan(); + continue; + } + } + } else { + break; + } + } + if(isIndexer) { + this.checkCurrentToken(TypeScript.TokenID.CloseBracket, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly | TypeScript.ErrorRecoverySet.SColon); + } else if(expectClosingRParen) { + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly | TypeScript.ErrorRecoverySet.SColon); + } + formals.limChar = this.currentToken.tokenId == TypeScript.TokenID.EndOfFile ? this.scanner.pos : this.scanner.lastTokenLimChar(); + return sawEllipsis; + }; + Parser.prototype.parseFncDecl = function (errorRecoverySet, isDecl, requiresSignature, isMethod, methodName, indexer, isStatic, markedAsAmbient, modifiers, lambdaArgContext, expectClosingRParen) { + var leftCurlyCount = this.scanner.leftCurlyCount; + var rightCurlyCount = this.scanner.rightCurlyCount; + var prevInConstr = this.parsingClassConstructorDefinition; + this.parsingClassConstructorDefinition = false; + var name = null; + var fnMin = this.scanner.startPos; + var minChar = this.scanner.pos; + var prevNestingLevel = this.nestingLevel; + var preComments = this.parseComments(); + var isLambda = !!lambdaArgContext; + this.nestingLevel = 0; + if((!this.style_funcInLoop) && this.inLoop()) { + this.reportParseStyleError("function declaration in loop"); + } + if(!isMethod && !isStatic && !indexer && !lambdaArgContext && !methodName) { + this.currentToken = this.scanner.scan(); + if((this.currentToken.tokenId != TypeScript.TokenID.Identifier) && (!TypeScript.convertTokToID(this.currentToken, this.strictMode))) { + if(isDecl) { + this.reportParseError("Function declaration must include identifier"); + this.nestingLevel = prevNestingLevel; + return new TypeScript.IncompleteAST(fnMin, this.scanner.pos); + } + } else { + name = TypeScript.Identifier.fromToken(this.currentToken); + name.minChar = this.scanner.startPos; + name.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + } + } else { + if(methodName) { + name = methodName; + } + } + var args = new TypeScript.ASTList(); + var variableArgList = false; + var isOverload = false; + var isGetter = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter); + var isSetter = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Setter); + if((this.currentToken.tokenId == TypeScript.TokenID.OpenParen) || (indexer && (this.currentToken.tokenId == TypeScript.TokenID.OpenBracket)) || (lambdaArgContext && (lambdaArgContext.preProcessedLambdaArgs || this.currentToken.tokenId == TypeScript.TokenID.DotDotDot))) { + variableArgList = this.parseFormalParameterList(errorRecoverySet, args, false, requiresSignature, indexer, isGetter, isSetter, isLambda, lambdaArgContext ? lambdaArgContext.preProcessedLambdaArgs : null, expectClosingRParen); + } + var returnType = null; + if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { + this.currentToken = this.scanner.scan(); + if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Setter)) { + this.reportParseError("Property setters may not declare a return type"); + } + returnType = this.parseTypeReference(errorRecoverySet, true); + } + if(indexer && args.members.length == 0) { + this.reportParseError("Index signatures require a parameter type to be specified"); + } + if(isLambda && this.currentToken.tokenId != TypeScript.TokenID.EqualsGreaterThan) { + this.reportParseError("Expected '=>'"); + } + if(isDecl && !(this.parsingDeclareFile || markedAsAmbient) && !this.ambientModule && !this.ambientClass && !this.inInterfaceDecl && this.currentToken.tokenId == TypeScript.TokenID.Semicolon) { + isOverload = true; + isDecl = false; + requiresSignature = true; + } + var svInFncDecl = this.inFncDecl; + this.inFncDecl = true; + var funcDecl = this.parseFunctionStatements(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, name, false, isMethod, args, TypeScript.AllowedElements.None, minChar, requiresSignature, TypeScript.Modifiers.None); + this.inFncDecl = svInFncDecl; + funcDecl.variableArgList = variableArgList; + funcDecl.isOverload = isOverload; + if(isStatic) { + funcDecl.fncFlags |= TypeScript.FncFlags.Static; + } + if(requiresSignature) { + funcDecl.fncFlags |= TypeScript.FncFlags.Signature; + } + if(indexer) { + funcDecl.fncFlags |= TypeScript.FncFlags.IndexerMember; + } + funcDecl.returnTypeAnnotation = returnType; + if(isMethod) { + funcDecl.fncFlags |= TypeScript.FncFlags.Method; + funcDecl.fncFlags |= TypeScript.FncFlags.ClassPropertyMethodExported; + } + funcDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; + funcDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; + this.nestingLevel = prevNestingLevel; + this.parsingClassConstructorDefinition = prevInConstr; + funcDecl.preComments = preComments; + return funcDecl; + }; + Parser.prototype.convertToTypeReference = function (ast) { + var result; + switch(ast.nodeType) { + case TypeScript.NodeType.TypeRef: + return ast; + case TypeScript.NodeType.Name: + result = new TypeScript.TypeReference(ast, 0); + result.minChar = ast.minChar; + result.limChar = ast.limChar; + return result; + case TypeScript.NodeType.Index: { + var expr = ast; + result = this.convertToTypeReference(expr.operand1); + if(result) { + result.arrayCount++; + result.minChar = expr.minChar; + result.limChar = expr.limChar; + return result; + } else { + var etr = new TypeScript.AST(TypeScript.NodeType.Error); + return etr; + } + } + } + return null; + }; + Parser.prototype.parseArgList = function (errorRecoverySet) { + var args = new TypeScript.ASTList(); + args.minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId !== TypeScript.TokenID.CloseParen) { + while(true) { + if(args.members.length > 0xffff) { + this.reportParseError("max number of args exceeded"); + break; + } + var arg = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); + args.append(arg); + if(this.currentToken.tokenId != TypeScript.TokenID.Comma) { + break; + } + this.currentToken = this.scanner.scan(); + } + } + args.limChar = this.scanner.pos; + return args; + }; + Parser.prototype.parseBaseList = function (extendsList, implementsList, errorRecoverySet, isClass) { + var keyword = true; + var currentList = extendsList; + for(; ; ) { + if(keyword) { + if(this.currentToken.tokenId === TypeScript.TokenID.Implements) { + currentList = implementsList; + } else if(this.currentToken.tokenId == TypeScript.TokenID.Extends && !this.requiresExtendsBlock) { + this.requiresExtendsBlock = isClass; + } + this.currentToken = this.scanner.scan(); + keyword = false; + } + var baseName = null; + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + var minChar = this.scanner.startPos; + baseName = TypeScript.Identifier.fromToken(this.currentToken); + baseName.minChar = minChar; + baseName.limChar = this.scanner.pos; + baseName = this.parseNamedType(errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly, minChar, baseName, false); + } else { + this.reportParseError("Expected base name"); + if(this.errorRecovery) { + baseName = new TypeScript.MissingIdentifier(); + baseName.minChar = this.scanner.pos; + baseName.limChar = this.scanner.pos; + baseName.flags |= TypeScript.ASTFlags.Error; + } + } + if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { + if(isClass) { + this.reportParseError("Base classes may only be initialized via a 'super' call within the constructor body"); + } else { + this.reportParseError("Interfaces may not be extended with a call expression"); + } + } else { + currentList.append(baseName); + } + if(isClass && currentList == extendsList && extendsList.members.length > 1) { + this.reportParseError("A class may only extend one other class"); + } + if(this.currentToken.tokenId == TypeScript.TokenID.Comma) { + this.currentToken = this.scanner.scan(); + continue; + } else if((this.currentToken.tokenId == TypeScript.TokenID.Extends) || (this.currentToken.tokenId == TypeScript.TokenID.Implements)) { + if(this.currentToken.tokenId == TypeScript.TokenID.Extends && !this.requiresExtendsBlock) { + this.requiresExtendsBlock = isClass; + } + currentList = extendsList; + keyword = true; + continue; + } + break; + } + }; + Parser.prototype.parseClassDecl = function (errorRecoverySet, minChar, modifiers) { + var leftCurlyCount = this.scanner.leftCurlyCount; + var rightCurlyCount = this.scanner.rightCurlyCount; + if((modifiers & TypeScript.Modifiers.Readonly) != TypeScript.Modifiers.None) { + this.reportParseError("const modifier is implicit for class"); + } + if(this.parsingDeclareFile || this.ambientModule) { + modifiers |= TypeScript.Modifiers.Ambient; + modifiers |= TypeScript.Modifiers.Exported; + } + var classIsMarkedAsAmbient = this.parsingDeclareFile || (modifiers & TypeScript.Modifiers.Ambient) != TypeScript.Modifiers.None; + var svAmbientClass = this.ambientClass; + this.ambientClass = classIsMarkedAsAmbient; + this.currentToken = this.scanner.scan(); + var name = null; + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || (!TypeScript.isPrimitiveTypeToken(this.currentToken) && TypeScript.convertTokToID(this.currentToken, this.strictMode))) { + name = TypeScript.Identifier.fromToken(this.currentToken); + name.minChar = this.scanner.startPos; + name.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + } else { + this.reportParseError("class missing name"); + if(this.errorRecovery) { + name = new TypeScript.MissingIdentifier(); + name.minChar = this.scanner.pos; + name.limChar = this.scanner.pos; + name.flags |= TypeScript.ASTFlags.Error; + } + } + var extendsList = null; + var implementsList = null; + var requiresSignature = false; + if((this.currentToken.tokenId == TypeScript.TokenID.Extends) || (this.currentToken.tokenId == TypeScript.TokenID.Implements)) { + extendsList = new TypeScript.ASTList(); + implementsList = new TypeScript.ASTList(); + this.parseBaseList(extendsList, implementsList, errorRecoverySet, true); + } + var classDecl = new TypeScript.ClassDeclaration(name, new TypeScript.ASTList(), extendsList, implementsList); + this.currentClassDefinition = classDecl; + this.parseClassElements(classDecl, errorRecoverySet, modifiers); + if(this.ambientModule || this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { + classDecl.varFlags |= TypeScript.VarFlags.Exported; + } + if(this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + classDecl.varFlags |= TypeScript.VarFlags.Ambient; + } + classDecl.varFlags |= TypeScript.VarFlags.Class; + this.ambientClass = svAmbientClass; + classDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; + classDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; + return classDecl; + }; + Parser.prototype.parseClassElements = function (classDecl, errorRecoverySet, parentModifiers) { + var modifiers = parentModifiers; + var resetModifiers = false; + var membersMinChar = this.scanner.startPos; + this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet); + this.nestingLevel++; + var currentMemberMinChar = this.scanner.startPos; + var wasGetOrSetId = false; + while(!(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace || this.currentToken.tokenId == TypeScript.TokenID.EndOfFile)) { + var scanNext = true; + var publicOrPrivateFlags = TypeScript.Modifiers.Public | TypeScript.Modifiers.Private; + if(this.currentToken.tokenId == TypeScript.TokenID.Get) { + if(modifiers & TypeScript.Modifiers.Getter) { + this.reportParseError("Duplicate 'get' declaration in class body"); + } + if(modifiers & TypeScript.Modifiers.Setter) { + this.reportParseError("Getter already marked as a setter"); + } + modifiers |= TypeScript.Modifiers.Getter; + } else if(this.currentToken.tokenId == TypeScript.TokenID.Set) { + if(modifiers & TypeScript.Modifiers.Setter) { + this.reportParseError("Duplicate 'set' declaration in class body"); + } + if(modifiers & TypeScript.Modifiers.Getter) { + this.reportParseError("Setter already marked as a getter"); + } + modifiers |= TypeScript.Modifiers.Setter; + } else if(this.currentToken.tokenId == TypeScript.TokenID.Private) { + if(modifiers & publicOrPrivateFlags) { + this.reportParseError("Multiple modifiers may not be applied to class members"); + } + modifiers |= TypeScript.Modifiers.Private; + } else if(this.currentToken.tokenId == TypeScript.TokenID.Public) { + if(modifiers & publicOrPrivateFlags) { + this.reportParseError("Multiple modifiers may not be applied to class members"); + } + modifiers |= TypeScript.Modifiers.Public; + } else if(this.currentToken.tokenId == TypeScript.TokenID.Static) { + if(modifiers & TypeScript.Modifiers.Static) { + this.reportParseError("Multiple modifiers may not be applied to class members"); + } + modifiers |= TypeScript.Modifiers.Static; + } else if(this.currentToken.tokenId == TypeScript.TokenID.Constructor) { + if(modifiers != parentModifiers) { + this.reportParseError("Constructors may not have modifiers"); + } + this.parseClassConstructorDeclaration(currentMemberMinChar, errorRecoverySet, modifiers); + scanNext = false; + resetModifiers = true; + } else if(wasGetOrSetId || this.currentToken.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToIDName(this.currentToken)) { + var idText = wasGetOrSetId ? ((modifiers & TypeScript.Modifiers.Getter) ? "get" : "set") : this.currentToken.getText(); + var id = wasGetOrSetId ? new TypeScript.Identifier(idText) : TypeScript.Identifier.fromToken(this.currentToken); + id.minChar = this.scanner.startPos; + id.limChar = this.scanner.pos; + if(wasGetOrSetId) { + modifiers = modifiers ^ ((modifiers & TypeScript.Modifiers.Getter) ? TypeScript.Modifiers.Getter : TypeScript.Modifiers.Setter); + wasGetOrSetId = false; + } else { + this.currentToken = this.scanner.scan(); + } + if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { + this.parseClassMemberFunctionDeclaration(id, currentMemberMinChar, errorRecoverySet, modifiers); + scanNext = false; + } else { + if(modifiers & TypeScript.Modifiers.Getter || modifiers & TypeScript.Modifiers.Setter) { + this.reportParseError("Property accessors must be functions"); + } + var varDecl = this.parseClassMemberVariableDeclaration(id, currentMemberMinChar, false, errorRecoverySet, modifiers); + if(varDecl.init && varDecl.init.nodeType == TypeScript.NodeType.FuncDecl) { + if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { + scanNext = false; + } + } else if(varDecl.init && varDecl.init.nodeType == TypeScript.NodeType.ObjectLit && this.currentToken.tokenId != TypeScript.TokenID.Semicolon) { + scanNext = false; + varDecl.init.flags |= TypeScript.ASTFlags.AutomaticSemicolon; + } else if(this.currentToken.tokenId != TypeScript.TokenID.Semicolon) { + this.reportParseError("Expected ';'"); + scanNext = false; + } + } + resetModifiers = true; + } else if(this.currentToken.tokenId == TypeScript.TokenID.Super) { + this.reportParseError("Base class initializers must be the first statement in a class definition"); + } else if(!wasGetOrSetId && ((modifiers & TypeScript.Modifiers.Getter) || (modifiers & TypeScript.Modifiers.Setter)) && ((this.currentToken.tokenId == TypeScript.TokenID.OpenParen) || (this.currentToken.tokenId == TypeScript.TokenID.Equals) || (this.currentToken.tokenId == TypeScript.TokenID.Colon) || (this.currentToken.tokenId == TypeScript.TokenID.Semicolon))) { + wasGetOrSetId = true; + scanNext = false; + } else if(this.currentToken.tokenId != TypeScript.TokenID.Semicolon) { + this.reportParseError("Unexpected '" + this.currentToken.getText() + "' in class definition"); + resetModifiers = true; + } + if(scanNext) { + this.currentToken = this.scanner.scan(); + } + if(resetModifiers) { + modifiers = parentModifiers; + currentMemberMinChar = this.scanner.startPos; + resetModifiers = false; + } + } + var membersLimChar = this.scanner.pos; + if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { + classDecl.endingToken = new TypeScript.ASTSpan(); + classDecl.endingToken.minChar = this.scanner.startPos; + classDecl.endingToken.limChar = this.scanner.pos; + if(!this.currentClassDefinition.members.members.length) { + this.currentClassDefinition.preComments = this.parseComments(); + } + this.currentToken = this.scanner.scan(); + } + this.nestingLevel--; + this.currentClassDefinition.members.minChar = membersMinChar; + this.currentClassDefinition.members.limChar = membersLimChar; + this.currentClassDefinition.limChar = membersLimChar; + this.currentClassDefinition = null; + }; + Parser.prototype.parseClassConstructorDeclaration = function (minChar, errorRecoverySet, modifiers) { + this.parsingClassConstructorDefinition = true; + var isAmbient = this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient); + var args = new TypeScript.ASTList(); + var variableArgList = false; + var preComments = this.parseComments(); + var constructorSpan = new TypeScript.ASTSpan(); + constructorSpan.minChar = this.scanner.startPos; + constructorSpan.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { + variableArgList = this.parseFormalParameterList(errorRecoverySet, args, true, isAmbient, false, false, false, false, null, true); + if(args.members.length > 0) { + var lastArg = args.members[args.members.length - 1]; + } + } + var requiresSignature = isAmbient || this.currentToken.tokenId == TypeScript.TokenID.Semicolon; + if(requiresSignature) { + for(var i = 0; i < args.members.length; i++) { + var arg = args.members[i]; + if(TypeScript.hasFlag(arg.varFlags, TypeScript.VarFlags.Property)) { + this.reportParseError("Overload or ambient signatures may not specify parameter properties", arg.minChar, arg.limChar); + } + } + } + if(!requiresSignature) { + this.currentClassDefinition.constructorNestingLevel = this.nestingLevel + 1; + } + var constructorFuncDecl = this.parseFunctionStatements(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, this.currentClassDefinition.name, true, false, args, TypeScript.AllowedElements.Properties, minChar, requiresSignature, modifiers); + constructorFuncDecl.constructorSpan = constructorSpan; + constructorFuncDecl.preComments = preComments; + if(requiresSignature && !isAmbient) { + constructorFuncDecl.isOverload = true; + } + constructorFuncDecl.variableArgList = variableArgList; + this.currentClassDecl = null; + constructorFuncDecl.returnTypeAnnotation = this.convertToTypeReference(this.currentClassDefinition.name); + constructorFuncDecl.classDecl = this.currentClassDefinition; + if(isAmbient) { + constructorFuncDecl.fncFlags |= TypeScript.FncFlags.Ambient; + } + if(requiresSignature) { + constructorFuncDecl.fncFlags |= TypeScript.FncFlags.Signature; + } + if(this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { + constructorFuncDecl.fncFlags |= TypeScript.FncFlags.Exported; + } + if(this.currentClassDefinition.constructorDecl) { + if(!isAmbient && !this.currentClassDefinition.constructorDecl.isSignature() && !constructorFuncDecl.isSignature()) { + this.reportParseError("Duplicate constructor definition"); + } + } + if(isAmbient || !constructorFuncDecl.isSignature()) { + this.currentClassDefinition.constructorDecl = constructorFuncDecl; + } + constructorFuncDecl.fncFlags |= TypeScript.FncFlags.ClassMethod; + this.currentClassDefinition.members.members[this.currentClassDefinition.members.members.length] = constructorFuncDecl; + this.parsingClassConstructorDefinition = false; + return constructorFuncDecl; + }; + Parser.prototype.parseClassMemberVariableDeclaration = function (text, minChar, isDeclaredInConstructor, errorRecoverySet, modifiers) { + var varDecl = new TypeScript.VarDecl(text, this.nestingLevel); + varDecl.minChar = minChar; + var isStatic = false; + varDecl.preComments = this.parseComments(); + if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { + this.currentToken = this.scanner.scan(); + varDecl.typeExpr = this.parseTypeReference(errorRecoverySet | TypeScript.ErrorRecoverySet.Asg | TypeScript.ErrorRecoverySet.Comma, false); + if(varDecl.typeExpr && varDecl.typeExpr.nodeType == TypeScript.NodeType.TypeRef) { + var typeExpr = (varDecl.typeExpr); + if(typeExpr.term && typeExpr.term.nodeType == TypeScript.NodeType.FuncDecl) { + typeExpr.term.preComments = varDecl.preComments; + } + } + } + if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { + if(this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + this.reportParseError("context does not permit variable initializer"); + if(this.errorRecovery) { + this.skip(errorRecoverySet); + varDecl.flags |= TypeScript.ASTFlags.Error; + varDecl.limChar = this.scanner.lastTokenLimChar(); + return varDecl; + } + } + this.currentToken = this.scanner.scan(); + varDecl.init = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); + varDecl.limChar = varDecl.init.limChar; + if(!(modifiers & TypeScript.Modifiers.Static)) { + this.currentClassDefinition.varFlags |= TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor; + } + } else { + varDecl.limChar = this.scanner.pos; + } + if(modifiers & TypeScript.Modifiers.Static) { + varDecl.varFlags |= TypeScript.VarFlags.Static; + isStatic = true; + } + if((modifiers & TypeScript.Modifiers.Private) != TypeScript.Modifiers.None) { + varDecl.varFlags |= TypeScript.VarFlags.Private; + } else { + varDecl.varFlags |= TypeScript.VarFlags.Public; + } + varDecl.varFlags |= TypeScript.VarFlags.Property; + if(isDeclaredInConstructor) { + varDecl.varFlags |= TypeScript.VarFlags.ClassConstructorProperty; + } + if(!isDeclaredInConstructor && !isStatic) { + varDecl.varFlags |= TypeScript.VarFlags.ClassBodyProperty; + } + this.currentClassDefinition.knownMemberNames[text.actualText] = true; + if(!isDeclaredInConstructor) { + this.currentClassDefinition.members.members[this.currentClassDefinition.members.members.length] = varDecl; + } + varDecl.postComments = this.parseComments(); + return varDecl; + }; + Parser.prototype.parseClassMemberFunctionDeclaration = function (methodName, minChar, errorRecoverySet, modifiers) { + var wasAccessorID = this.prevIDTok != null; + var isAccessor = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter) || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Setter); + var isStatic = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Static); + var isAmbient = this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient); + errorRecoverySet |= TypeScript.ErrorRecoverySet.RParen; + if(isAccessor && (modifiers & TypeScript.Modifiers.Ambient)) { + this.reportParseError("Property accessors may not be declared in ambient classes"); + } + var ast = this.parseFncDecl(errorRecoverySet, true, isAmbient, true, methodName, false, isStatic, isAmbient, modifiers, null, true); + if(ast.nodeType == TypeScript.NodeType.Error) { + return ast; + } + var funcDecl = ast; + funcDecl.minChar = minChar; + if(funcDecl.bod !== null) { + funcDecl.limChar = funcDecl.bod.limChar; + } + if(modifiers & TypeScript.Modifiers.Private) { + funcDecl.fncFlags |= TypeScript.FncFlags.Private; + } else { + funcDecl.fncFlags |= TypeScript.FncFlags.Public; + } + if(isStatic) { + funcDecl.fncFlags |= TypeScript.FncFlags.Static; + } + if(isAccessor) { + if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter)) { + funcDecl.fncFlags |= TypeScript.FncFlags.GetAccessor; + funcDecl.hint = "get" + funcDecl.name.actualText; + } else { + funcDecl.fncFlags |= TypeScript.FncFlags.SetAccessor; + funcDecl.hint = "set" + funcDecl.name.actualText; + } + funcDecl.fncFlags |= TypeScript.FncFlags.IsFunctionExpression; + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("Property accessors are only available when targeting ES5 or greater", funcDecl.minChar, funcDecl.limChar); + } + } + funcDecl.fncFlags |= TypeScript.FncFlags.ClassMethod; + this.currentClassDefinition.knownMemberNames[methodName.actualText] = true; + this.currentClassDefinition.members.members[this.currentClassDefinition.members.members.length] = funcDecl; + return funcDecl; + }; + Parser.prototype.parseTypeMember = function (errorRecoverySet) { + var minChar = this.scanner.startPos; + var propertyDecl = this.parsePropertyDeclaration(errorRecoverySet, TypeScript.Modifiers.Public, true, false); + if(propertyDecl) { + propertyDecl.minChar = minChar; + if(propertyDecl.nodeType == TypeScript.NodeType.VarDecl) { + this.checkCurrentToken(TypeScript.TokenID.Semicolon, errorRecoverySet); + } + } + return propertyDecl; + }; + Parser.prototype.parseTypeMemberList = function (errorRecoverySet, members) { + errorRecoverySet |= TypeScript.ErrorRecoverySet.TypeScriptS; + while(true) { + switch(this.currentToken.tokenId) { + case TypeScript.TokenID.CloseBrace: + case TypeScript.TokenID.EndOfFile: + members.limChar = this.scanner.pos; + return; + } + var element = this.parseTypeMember(errorRecoverySet); + if(element) { + members.append(element); + } + } + }; + Parser.prototype.parseInterfaceDecl = function (errorRecoverySet, modifiers) { + var leftCurlyCount = this.scanner.leftCurlyCount; + var rightCurlyCount = this.scanner.rightCurlyCount; + this.currentToken = this.scanner.scan(); + var minChar = this.scanner.pos; + var name = null; + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || (!TypeScript.isPrimitiveTypeToken(this.currentToken) && TypeScript.convertTokToID(this.currentToken, this.strictMode))) { + name = TypeScript.Identifier.fromToken(this.currentToken); + name.minChar = this.scanner.startPos; + name.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + } else { + this.reportParseError("interface missing name"); + if(this.errorRecovery) { + name = new TypeScript.MissingIdentifier(); + name.minChar = this.scanner.pos; + name.limChar = this.scanner.pos; + name.flags |= TypeScript.ASTFlags.Error; + } + } + var extendsList = null; + var implementsList = null; + if(this.currentToken.tokenId === TypeScript.TokenID.Extends || this.currentToken.tokenId === TypeScript.TokenID.Implements) { + if(this.currentToken.tokenId === TypeScript.TokenID.Implements) { + this.reportParseError("Expected 'extends'"); + } + extendsList = new TypeScript.ASTList(); + implementsList = new TypeScript.ASTList(); + extendsList.minChar = this.scanner.startPos; + this.parseBaseList(extendsList, implementsList, errorRecoverySet, false); + } + var membersMinChar = this.scanner.startPos; + this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.TypeScriptS); + var members = new TypeScript.ASTList(); + members.minChar = membersMinChar; + var prevInInterfaceDecl = this.inInterfaceDecl; + this.inInterfaceDecl = true; + this.parseTypeMemberList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, members); + this.inInterfaceDecl = prevInInterfaceDecl; + this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); + var interfaceDecl = new TypeScript.InterfaceDeclaration(name, members, extendsList, null); + if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Private)) { + interfaceDecl.varFlags |= TypeScript.VarFlags.Private; + } + if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Public)) { + interfaceDecl.varFlags |= TypeScript.VarFlags.Public; + } + if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { + interfaceDecl.varFlags |= TypeScript.VarFlags.Exported; + } + interfaceDecl.limChar = members.limChar; + interfaceDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; + interfaceDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; + return interfaceDecl; + }; + Parser.prototype.makeVarDecl = function (id, nest) { + var varDecl = new TypeScript.VarDecl(id, nest); + var currentVarList = this.topVarList(); + if(currentVarList) { + currentVarList.append(varDecl); + } + return varDecl; + }; + Parser.prototype.parsePropertyDeclaration = function (errorRecoverySet, modifiers, requireSignature, isStatic, unnamedAmbientFunctionOk) { + var text = null; + var minChar = this.scanner.startPos; + var nameLimChar = minChar; + var isNew = false; + var isIndexer = false; + var wasAccessorID = this.prevIDTok != null; + var isAccessor = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter) || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Setter); + if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + requireSignature = true; + } + if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen && !wasAccessorID) { + if(!requireSignature && !isStatic) { + this.reportParseError("Expected identifier in property declaration"); + if(this.errorRecovery) { + this.skip(errorRecoverySet); + text = new TypeScript.MissingIdentifier(); + } + } + } else if(this.currentToken.tokenId == TypeScript.TokenID.New) { + if(requireSignature) { + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { + isNew = true; + } + } + if(!isNew) { + if(!requireSignature) { + this.currentToken = this.scanner.scan(); + } + text = new TypeScript.Identifier("new"); + text.minChar = this.scanner.pos - 3; + text.limChar = this.scanner.pos; + nameLimChar = this.scanner.pos; + } + } else if((this.currentToken.tokenId == TypeScript.TokenID.OpenBracket) && requireSignature) { + isIndexer = true; + text = new TypeScript.Identifier("__item"); + } else if((this.currentToken.tokenId != TypeScript.TokenID.Identifier) && (!TypeScript.convertTokToIDName(this.currentToken)) && !wasAccessorID) { + this.reportParseError("Expected identifier in property declaration"); + if(this.errorRecovery) { + var eminChar = this.scanner.startPos; + var curpos = this.scanner.pos; + this.skip(errorRecoverySet & (~TypeScript.ErrorRecoverySet.Comma)); + if(this.scanner.pos == curpos) { + this.currentToken = this.scanner.scan(); + } + var epd = new TypeScript.VarDecl(new TypeScript.MissingIdentifier(), this.nestingLevel); + epd.flags |= TypeScript.ASTFlags.Error; + epd.minChar = eminChar; + epd.limChar = this.scanner.lastTokenLimChar(); + return epd; + } + } else { + if(wasAccessorID) { + text = TypeScript.Identifier.fromToken(this.prevIDTok); + text.minChar = this.scanner.lastTokenLimChar() - 3; + text.limChar = this.scanner.lastTokenLimChar(); + nameLimChar = text.limChar; + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("Property accessors are only available when targeting ES5 or greater"); + } + if(this.currentToken.getText() == text.actualText && this.currentToken != this.prevIDTok) { + this.currentToken = this.scanner.scan(); + } + this.prevIDTok = null; + } else { + text = TypeScript.Identifier.fromToken(this.currentToken); + text.minChar = this.scanner.startPos; + text.limChar = this.scanner.pos; + nameLimChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + } + } + if(this.currentToken.tokenId == TypeScript.TokenID.Question) { + if(this.inInterfaceDecl && text) { + text.flags |= TypeScript.ASTFlags.OptionalName; + } else { + this.reportParseError("Optional properties may only be declared on interface or object types"); + } + this.currentToken = this.scanner.scan(); + } + if((this.currentToken.tokenId == TypeScript.TokenID.OpenParen) || (isIndexer && (this.currentToken.tokenId == TypeScript.TokenID.OpenBracket))) { + var ers = errorRecoverySet | TypeScript.ErrorRecoverySet.RParen; + if(isIndexer) { + ers = errorRecoverySet | TypeScript.ErrorRecoverySet.RBrack; + } + if(!text && unnamedAmbientFunctionOk && !isIndexer) { + text = new TypeScript.MissingIdentifier(); + } + var ast = this.parseFncDecl(ers, true, requireSignature, this.currentClassDefinition || this.inInterfaceDecl, text, isIndexer, isStatic, (this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)), modifiers, null, true); + var funcDecl; + if(ast.nodeType == TypeScript.NodeType.Error) { + return ast; + } else { + funcDecl = ast; + } + if(funcDecl.name) { + funcDecl.name.minChar = minChar; + funcDecl.name.limChar = nameLimChar; + } + if((modifiers & TypeScript.Modifiers.Public) != TypeScript.Modifiers.None) { + funcDecl.fncFlags |= TypeScript.FncFlags.Public; + } + if((modifiers & TypeScript.Modifiers.Private) != TypeScript.Modifiers.None) { + funcDecl.fncFlags |= TypeScript.FncFlags.Private; + } + if(isStatic) { + funcDecl.fncFlags |= TypeScript.FncFlags.Static; + } + if(this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + funcDecl.fncFlags |= TypeScript.FncFlags.Ambient; + } + if(isAccessor) { + if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter)) { + funcDecl.fncFlags |= TypeScript.FncFlags.GetAccessor; + funcDecl.hint = "get" + funcDecl.name.actualText; + } else { + funcDecl.fncFlags |= TypeScript.FncFlags.SetAccessor; + funcDecl.hint = "set" + funcDecl.name.actualText; + } + funcDecl.fncFlags |= TypeScript.FncFlags.IsFunctionExpression; + if(modifiers & TypeScript.Modifiers.Ambient) { + this.reportParseError("Property accessors may not be declared in ambient types"); + } + } + if(text == null || (text.isMissing() && unnamedAmbientFunctionOk && !isIndexer)) { + if(isNew) { + funcDecl.fncFlags |= TypeScript.FncFlags.ConstructMember; + funcDecl.hint = "_construct"; + funcDecl.classDecl = this.currentClassDecl; + } else { + funcDecl.hint = "_call"; + funcDecl.fncFlags |= TypeScript.FncFlags.CallMember; + } + } + return funcDecl; + } else { + var varDecl = new TypeScript.VarDecl(text, this.nestingLevel); + varDecl.preComments = this.parseComments(); + varDecl.minChar = minChar; + if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { + this.currentToken = this.scanner.scan(); + varDecl.typeExpr = this.parseTypeReference(errorRecoverySet | TypeScript.ErrorRecoverySet.Asg | TypeScript.ErrorRecoverySet.Comma, false); + if(varDecl.typeExpr && varDecl.typeExpr.nodeType == TypeScript.NodeType.TypeRef) { + var typeExpr = (varDecl.typeExpr); + if(typeExpr.term && typeExpr.term.nodeType == TypeScript.NodeType.FuncDecl) { + typeExpr.term.preComments = varDecl.preComments; + } + } + } + if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { + if(requireSignature) { + this.reportParseError("context does not permit variable initializer"); + if(this.errorRecovery) { + this.skip(errorRecoverySet); + varDecl.flags |= TypeScript.ASTFlags.Error; + varDecl.limChar = this.scanner.lastTokenLimChar(); + return varDecl; + } + } + this.currentToken = this.scanner.scan(); + varDecl.init = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); + varDecl.limChar = varDecl.init.limChar; + if(varDecl.init.nodeType == TypeScript.NodeType.FuncDecl) { + var funcDecl = varDecl.init; + funcDecl.hint = varDecl.id.text; + funcDecl.boundToProperty = varDecl; + } else if(isAccessor) { + this.reportParseError("Accessors may only be functions"); + } + } else { + varDecl.limChar = this.scanner.pos; + } + if((modifiers & TypeScript.Modifiers.Readonly) != TypeScript.Modifiers.None) { + varDecl.varFlags |= TypeScript.VarFlags.Readonly; + } + if(isStatic) { + varDecl.varFlags |= TypeScript.VarFlags.Static; + } + if((modifiers & TypeScript.Modifiers.Public) != TypeScript.Modifiers.None) { + varDecl.varFlags |= TypeScript.VarFlags.Public; + } + if((modifiers & TypeScript.Modifiers.Private) != TypeScript.Modifiers.None) { + varDecl.varFlags |= TypeScript.VarFlags.Private; + } + varDecl.varFlags |= TypeScript.VarFlags.Property; + return varDecl; + } + }; + Parser.prototype.parseVariableDeclaration = function (errorRecoverySet, modifiers, allowIn, isStatic) { + var isConst = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Readonly); + var minChar = this.scanner.startPos; + var varDecl = null; + var declList = null; + var multivar = false; + this.currentToken = this.scanner.scan(); + var varDeclPreComments = this.parseComments(); + while(true) { + if((this.currentToken.tokenId != TypeScript.TokenID.Identifier) && (!TypeScript.convertTokToID(this.currentToken, this.strictMode))) { + this.reportParseError("Expected identifier in variable declaration"); + if(this.errorRecovery) { + varDecl = new TypeScript.VarDecl(new TypeScript.MissingIdentifier(), this.nestingLevel); + varDecl.minChar = minChar; + this.skip(errorRecoverySet); + varDecl.flags |= TypeScript.ASTFlags.Error; + varDecl.limChar = this.scanner.lastTokenLimChar(); + return varDecl; + } + } + var varDeclName = TypeScript.Identifier.fromToken(this.currentToken); + if(this.strictMode && (varDeclName.text == "eval")) { + this.reportParseError("'eval' may not name a variable in strict mode"); + } + varDecl = this.makeVarDecl(varDeclName, this.nestingLevel); + varDecl.id.minChar = this.scanner.startPos; + varDecl.id.limChar = this.scanner.pos; + varDecl.preComments = varDeclPreComments; + if(isStatic) { + varDecl.varFlags |= TypeScript.VarFlags.Static; + } + if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Readonly)) { + varDecl.varFlags |= TypeScript.VarFlags.Readonly; + } + if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + varDecl.varFlags |= TypeScript.VarFlags.Ambient; + } + if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { + varDecl.varFlags |= TypeScript.VarFlags.Exported; + } + varDecl.minChar = minChar; + if(declList) { + declList.append(varDecl); + } + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { + this.currentToken = this.scanner.scan(); + var prevInFncDecl = this.inFncDecl; + this.inFncDecl = false; + varDecl.typeExpr = this.parseTypeReference(errorRecoverySet | TypeScript.ErrorRecoverySet.Asg | TypeScript.ErrorRecoverySet.Comma, false); + this.inFncDecl = prevInFncDecl; + } + if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { + if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Ambient)) { + this.reportParseError("Ambient variable can not have an initializer"); + } + this.currentToken = this.scanner.scan(); + varDecl.init = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, allowIn, TypeContext.NoTypes); + varDecl.limChar = varDecl.init.limChar; + if(varDecl.init.nodeType == TypeScript.NodeType.FuncDecl) { + var funcDecl = varDecl.init; + funcDecl.hint = varDecl.id.actualText; + } + } else { + if(isConst) { + this.reportParseError("const declaration requires initializer"); + } + varDecl.limChar = this.scanner.pos; + } + varDecl.postComments = this.parseCommentsForLine(this.scanner.line); + if(this.currentToken.tokenId != TypeScript.TokenID.Comma) { + if(declList) { + declList.limChar = varDecl.limChar; + return declList; + } else { + return varDecl; + } + } + if(!multivar) { + declList = new TypeScript.ASTList(); + declList.minChar = varDecl.minChar; + declList.append(varDecl); + multivar = true; + } + this.currentToken = this.scanner.scan(); + minChar = this.scanner.startPos; + } + }; + Parser.prototype.parseMemberList = function (errorRecoverySet) { + var elements = new TypeScript.ASTList(); + if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { + return elements; + } + var idHint = null; + var memberName = null; + var memberExpr = null; + var member = null; + var minChar = this.scanner.startPos; + var isSet = false; + var skippedTokenForGetSetId = false; + var getSetTok = null; + var getSetStartPos = 0; + var getSetPos = 0; + for(; ; ) { + var accessorPattern = false; + if(this.currentToken.tokenId == TypeScript.TokenID.Get || this.currentToken.tokenId == TypeScript.TokenID.Set) { + isSet = this.currentToken.tokenId == TypeScript.TokenID.Set; + getSetTok = this.currentToken; + getSetStartPos = this.scanner.startPos; + getSetPos = this.scanner.pos; + this.currentToken = this.scanner.scan(); + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToIDName(this.currentToken)) { + idHint = isSet ? "set" : "get"; + idHint = idHint + this.currentToken.getText(); + memberName = TypeScript.Identifier.fromToken(this.currentToken); + memberName.minChar = this.scanner.startPos; + accessorPattern = true; + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("Property accessors are only available when targeting ES5 or greater"); + } + } else if(this.currentToken.tokenId != TypeScript.TokenID.Colon) { + this.reportParseError("Expected identifier, string or number as accessor name"); + } else { + skippedTokenForGetSetId = true; + memberName = TypeScript.Identifier.fromToken(getSetTok); + memberName.minChar = getSetStartPos; + memberName.limChar = getSetPos; + } + } else if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToIDName(this.currentToken)) { + idHint = this.currentToken.getText(); + memberName = TypeScript.Identifier.fromToken(this.currentToken); + memberName.minChar = this.scanner.startPos; + memberName.limChar = this.scanner.pos; + } else if(this.currentToken.tokenId == TypeScript.TokenID.StringLiteral) { + idHint = this.currentToken.getText(); + memberName = new TypeScript.StringLiteral(idHint); + memberName.minChar = this.scanner.startPos; + memberName.limChar = this.scanner.pos; + } else if(this.currentToken.tokenId == TypeScript.TokenID.NumberLiteral) { + var ntok = this.currentToken; + idHint = ntok.value.toString(); + memberName = new TypeScript.StringLiteral(idHint); + memberName.minChar = this.scanner.startPos; + memberName.limChar = this.scanner.pos; + } else { + this.reportParseError("Expected identifier, string or number as member name"); + if(this.errorRecovery) { + memberName = new TypeScript.MissingIdentifier(); + memberName.minChar = this.scanner.startPos; + memberName.flags |= TypeScript.ASTFlags.Error; + this.skip(errorRecoverySet | TypeScript.ErrorRecoverySet.Comma); + memberName.limChar = this.scanner.lastTokenLimChar(); + } + } + if(!skippedTokenForGetSetId) { + this.currentToken = this.scanner.scan(); + } else { + skippedTokenForGetSetId = false; + } + if(this.currentToken.tokenId == TypeScript.TokenID.Question) { + memberName.flags |= TypeScript.ASTFlags.OptionalName; + this.currentToken = this.scanner.scan(); + } + if(accessorPattern) { + var args = new TypeScript.ASTList(); + this.parseFormalParameterList(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, args, false, true, false, !isSet, isSet, false, null, true); + var funcDecl = this.parseFunctionStatements(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, memberName, false, true, args, TypeScript.AllowedElements.None, this.scanner.startPos, false, TypeScript.Modifiers.None); + if(isSet && funcDecl.returnTypeAnnotation) { + this.reportParseError("Property setters may not declare a return type"); + } + funcDecl.fncFlags |= isSet ? TypeScript.FncFlags.SetAccessor : TypeScript.FncFlags.GetAccessor; + funcDecl.fncFlags |= TypeScript.FncFlags.IsFunctionExpression; + funcDecl.hint = idHint; + memberExpr = funcDecl; + member = new TypeScript.BinaryExpression(TypeScript.NodeType.Member, memberName, memberExpr); + member.minChar = memberName.minChar; + if(memberExpr.nodeType == TypeScript.NodeType.FuncDecl) { + var funcDecl = memberExpr; + funcDecl.hint = idHint; + } + } else if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { + this.currentToken = this.scanner.scan(); + memberExpr = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); + if(memberExpr.nodeType == TypeScript.NodeType.TypeRef) { + this.reportParseError("Expected 'new' on array declaration in member definition"); + } + member = new TypeScript.BinaryExpression(TypeScript.NodeType.Member, memberName, memberExpr); + member.minChar = memberName.minChar; + if(memberExpr.nodeType == TypeScript.NodeType.FuncDecl) { + var funcDecl = memberExpr; + funcDecl.hint = idHint; + } + } else { + this.reportParseError("Expected ':' in member definition"); + if(this.errorRecovery) { + this.skip(errorRecoverySet); + elements.flags |= TypeScript.ASTFlags.Error; + elements.minChar = minChar; + elements.limChar = this.scanner.lastTokenLimChar(); + return elements; + } + } + idHint = null; + elements.append(member); + member.limChar = this.scanner.lastTokenLimChar(); + if(this.currentToken.tokenId != TypeScript.TokenID.Comma) { + break; + } else { + this.currentToken = this.scanner.scan(); + } + if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { + break; + } + } + if(member) { + elements.limChar = member.limChar; + } + elements.minChar = minChar; + return elements; + }; + Parser.prototype.parseArrayList = function (errorRecoverySet) { + var elements = null; + if(this.currentToken.tokenId == TypeScript.TokenID.CloseBracket) { + return elements; + } else { + elements = new TypeScript.ASTList(); + elements.minChar = this.scanner.startPos; + } + var arg; + for(; ; ) { + if((this.currentToken.tokenId == TypeScript.TokenID.Comma) || (this.currentToken.tokenId == TypeScript.TokenID.CloseBracket)) { + arg = new TypeScript.AST(TypeScript.NodeType.EmptyExpr); + } else { + arg = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); + } + elements.append(arg); + if(this.currentToken.tokenId != TypeScript.TokenID.Comma) { + break; + } + this.currentToken = this.scanner.scan(); + } + elements.limChar = this.scanner.lastTokenLimChar(); + return elements; + }; + Parser.prototype.parseArrayLiteral = function (errorRecoverySet) { + var arrayLiteral = null; + arrayLiteral = new TypeScript.UnaryExpression(TypeScript.NodeType.ArrayLit, this.parseArrayList(errorRecoverySet)); + return arrayLiteral; + }; + Parser.prototype.parseTerm = function (errorRecoverySet, allowCall, typeContext, inCast) { + var ast = null; + var sawId = false; + var inNew = false; + var minChar = this.scanner.startPos; + var limChar = this.scanner.pos; + var parseAsLambda = false; + var expectlambdaRParen = false; + switch(this.currentToken.tokenId) { + case TypeScript.TokenID.Number: + case TypeScript.TokenID.Bool: + case TypeScript.TokenID.Any: + case TypeScript.TokenID.String: + var tid = new TypeScript.Identifier(TypeScript.tokenTable[this.currentToken.tokenId].text); + if(TypeScript.hasFlag(typeContext, TypeContext.Primitive)) { + ast = new TypeScript.TypeReference(tid, 0); + sawId = true; + } else { + ast = tid; + sawId = true; + } + ast.minChar = minChar; + this.currentToken = this.scanner.scan(); + limChar = this.scanner.lastTokenLimChar(); + break; + case TypeScript.TokenID.This: + ast = new TypeScript.AST(TypeScript.NodeType.This); + ast.minChar = minChar; + this.currentToken = this.scanner.scan(); + limChar = this.scanner.lastTokenLimChar(); + break; + case TypeScript.TokenID.Super: + ast = new TypeScript.AST(TypeScript.NodeType.Super); + ast.minChar = minChar; + this.currentToken = this.scanner.scan(); + limChar = this.scanner.lastTokenLimChar(); + break; + case TypeScript.TokenID.True: + ast = new TypeScript.AST(TypeScript.NodeType.True); + this.currentToken = this.scanner.scan(); + ast.minChar = minChar; + break; + case TypeScript.TokenID.False: + ast = new TypeScript.AST(TypeScript.NodeType.False); + this.currentToken = this.scanner.scan(); + ast.minChar = minChar; + break; + case TypeScript.TokenID.Null: + ast = new TypeScript.AST(TypeScript.NodeType.Null); + this.currentToken = this.scanner.scan(); + ast.minChar = minChar; + break; + case TypeScript.TokenID.New: + this.currentToken = this.scanner.scan(); + var target = this.parseTerm(errorRecoverySet, false, TypeContext.AllSimpleTypes, inCast); + if(target.nodeType == TypeScript.NodeType.Error || (target.nodeType == TypeScript.NodeType.Index && (target).operand1.nodeType == TypeScript.NodeType.TypeRef)) { + this.reportParseError("Cannot invoke 'new' on this expression"); + } else { + ast = new TypeScript.CallExpression(TypeScript.NodeType.New, target, null); + ast.minChar = minChar; + limChar = this.currentToken.tokenId == TypeScript.TokenID.EndOfFile ? this.scanner.pos : this.scanner.lastTokenLimChar(); + inNew = true; + } + break; + case TypeScript.TokenID.Function: + minChar = this.scanner.pos; + ast = this.parseFncDecl(errorRecoverySet, false, false, false, null, false, false, false, TypeScript.Modifiers.None, null, true); + (ast).fncFlags |= TypeScript.FncFlags.IsFunctionExpression; + ast.minChar = minChar; + limChar = this.currentToken.tokenId == TypeScript.TokenID.EndOfFile ? this.scanner.pos : this.scanner.lastTokenLimChar(); + ast.limChar = limChar; + break; + } + if(ast == null) { + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + var idText = this.currentToken.getText(); + ast = this.createRef(idText, (this.currentToken).hasEscapeSequence, minChar); + sawId = true; + ast.minChar = minChar; + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.Question) { + ast.flags |= TypeScript.ASTFlags.PossibleOptionalParameter; + } + limChar = this.scanner.lastTokenLimChar(); + } + } + if(inCast) { + this.checkCurrentToken(TypeScript.TokenID.GreaterThan, errorRecoverySet); + } + if(ast == null) { + switch(this.currentToken.tokenId) { + case TypeScript.TokenID.OpenParen: + minChar = this.scanner.pos; + var prevTokId = this.scanner.previousToken().tokenId; + this.currentToken = this.scanner.scan(); + var couldBeLambda = prevTokId == TypeScript.TokenID.OpenParen || prevTokId == TypeScript.TokenID.Comma || prevTokId == TypeScript.TokenID.EqualsEquals || prevTokId == TypeScript.TokenID.Colon; + if(couldBeLambda && this.currentToken.tokenId == TypeScript.TokenID.CloseParen) { + parseAsLambda = true; + expectlambdaRParen = false; + this.currentToken = this.scanner.scan(); + } else if(couldBeLambda && this.currentToken.tokenId == TypeScript.TokenID.DotDotDot) { + parseAsLambda = true; + expectlambdaRParen = true; + } else { + ast = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes, couldBeLambda); + limChar = this.scanner.lastTokenLimChar(); + parseAsLambda = couldBeLambda && (ast.nodeType == TypeScript.NodeType.Name || ast.nodeType == TypeScript.NodeType.Comma) && (this.currentToken.tokenId == TypeScript.TokenID.Colon || this.currentToken.tokenId == TypeScript.TokenID.Question); + expectlambdaRParen = true; + } + if((ast && !parseAsLambda)) { + if(TypeScript.hasFlag(ast.flags, TypeScript.ASTFlags.SkipNextRParen)) { + ast.flags = ast.flags & (~(TypeScript.ASTFlags.SkipNextRParen)); + break; + } + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet); + ast.isParenthesized = true; + } + break; + case TypeScript.TokenID.NumberLiteral: { + var numTok = this.currentToken; + this.currentToken = this.scanner.scan(); + ast = new TypeScript.NumberLiteral(numTok.value, numTok.text); + ast.minChar = minChar; + limChar = this.scanner.lastTokenLimChar(); + break; + } + case TypeScript.TokenID.StringLiteral: + ast = new TypeScript.StringLiteral(this.currentToken.getText()); + this.currentToken = this.scanner.scan(); + ast.minChar = minChar; + limChar = this.scanner.lastTokenLimChar(); + break; + case TypeScript.TokenID.RegularExpressionLiteral: { + var rtok = this.currentToken; + ast = new TypeScript.RegexLiteral(rtok.text); + this.currentToken = this.scanner.scan(); + ast.minChar = minChar; + limChar = this.scanner.lastTokenLimChar(); + break; + } + case TypeScript.TokenID.OpenBracket: + minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + ast = this.parseArrayLiteral(TypeScript.ErrorRecoverySet.RBrack | errorRecoverySet); + ast.minChar = minChar; + limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseBracket, errorRecoverySet); + break; + case TypeScript.TokenID.OpenBrace: + minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + var members = this.parseMemberList(TypeScript.ErrorRecoverySet.RCurly | errorRecoverySet); + this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); + ast = new TypeScript.UnaryExpression(TypeScript.NodeType.ObjectLit, members); + ast.minChar = minChar; + limChar = this.scanner.lastTokenLimChar(); + members.minChar = minChar; + members.limChar = limChar; + break; + case TypeScript.TokenID.LessThan: + minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + var term = this.parseTypeReference(TypeScript.ErrorRecoverySet.BinOp, false); + this.checkCurrentToken(TypeScript.TokenID.GreaterThan, errorRecoverySet); + ast = new TypeScript.UnaryExpression(TypeScript.NodeType.TypeAssertion, this.parseExpr(errorRecoverySet, TypeScript.OperatorPrecedence.Unary, false, TypeContext.NoTypes)); + (ast).castTerm = term; + break; + default: + if(this.prevExpr && TypeScript.hasFlag(this.prevExpr.flags, TypeScript.ASTFlags.PossibleOptionalParameter)) { + parseAsLambda = true; + ast = this.prevExpr; + } else { + this.reportParseError("Check format of expression term"); + if(this.errorRecovery) { + var ident = new TypeScript.MissingIdentifier(); + ident.minChar = minChar; + ident.flags |= TypeScript.ASTFlags.Error; + this.skip(errorRecoverySet | TypeScript.ErrorRecoverySet.Postfix); + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + ident.setText(this.currentToken.getText(), (this.currentToken).hasEscapeSequence); + this.currentToken = this.scanner.scan(); + limChar = this.scanner.lastTokenLimChar(); + } else { + limChar = this.scanner.lastTokenLimChar(); + } + ast = ident; + } + } + } + } + if(parseAsLambda) { + if(this.currentToken.tokenId == TypeScript.TokenID.Colon || this.currentToken.tokenId == TypeScript.TokenID.Comma || this.currentToken.tokenId == TypeScript.TokenID.CloseParen || this.currentToken.tokenId == TypeScript.TokenID.DotDotDot) { + ast = this.parseLambdaExpr(errorRecoverySet, ast, true, expectlambdaRParen); + ast.minChar = minChar; + limChar = this.scanner.lastTokenLimChar(); + ast.limChar = limChar; + } else if(ast) { + ast.isParenthesized = true; + } + } + if(sawId && (typeContext != TypeContext.NoTypes)) { + typeContext |= TypeContext.ArraySuffix; + } + var postFix = this.parsePostfixOperators(errorRecoverySet, ast, allowCall, inNew, typeContext, minChar, limChar); + if(postFix) { + if(sawId && (postFix.nodeType == TypeScript.NodeType.Index)) { + var binExpr = postFix; + if(binExpr.operand2 == null) { + postFix = this.convertToTypeReference(postFix); + } + } + postFix.minChar = minChar; + postFix.limChar = TypeScript.max(postFix.limChar, this.scanner.lastTokenLimChar()); + return postFix; + } else { + return new TypeScript.AST(TypeScript.NodeType.Error); + } + }; + Parser.prototype.parseLambdaExpr = function (errorRecoverySet, lambdaArgs, skipNextRParen, expectClosingRParen) { + var ast = this.parseFncDecl(errorRecoverySet, false, false, false, null, false, false, false, TypeScript.Modifiers.None, { + preProcessedLambdaArgs: lambdaArgs + }, expectClosingRParen); + (ast).fncFlags |= TypeScript.FncFlags.IsFunctionExpression; + (ast).fncFlags |= TypeScript.FncFlags.IsFatArrowFunction; + if(!skipNextRParen) { + ast.flags |= TypeScript.ASTFlags.SkipNextRParen; + } + ast.limChar = this.scanner.lastTokenLimChar(); + ; + return ast; + }; + Parser.prototype.parseExpr = function (errorRecoverySet, minPrecedence, allowIn, typeContext, possiblyInLambda) { + if (typeof possiblyInLambda === "undefined") { possiblyInLambda = false; } + var ast = null; + var tokenInfo = TypeScript.lookupToken(this.currentToken.tokenId); + var canAssign = true; + var idHint = null; + var minChar = this.scanner.startPos; + var preComments = this.parseComments(); + var exprIsAnonLambda = false; + if((tokenInfo != undefined) && (tokenInfo.unopNodeType != TypeScript.NodeType.None)) { + canAssign = false; + this.currentToken = this.scanner.scan(); + var tempExpr = this.parseExpr(TypeScript.ErrorRecoverySet.BinOp | errorRecoverySet, tokenInfo.unopPrecedence, allowIn, TypeContext.NoTypes); + ast = new TypeScript.UnaryExpression(tokenInfo.unopNodeType, tempExpr); + ast.limChar = tempExpr.limChar; + ast.minChar = minChar; + } else { + ast = this.parseTerm(TypeScript.ErrorRecoverySet.BinOp | TypeScript.ErrorRecoverySet.AddOp | errorRecoverySet, true, typeContext, false); + var id; + var temp; + if(ast.nodeType == TypeScript.NodeType.Name) { + id = ast; + idHint = id.actualText; + } else if(ast.nodeType == TypeScript.NodeType.Dot) { + var subsumedExpr = false; + if(this.inferPropertiesFromThisAssignment && (this.currentToken.tokenId == TypeScript.TokenID.Colon || this.currentToken.tokenId == TypeScript.TokenID.Equals) && this.parsingClassConstructorDefinition && this.nestingLevel == this.currentClassDefinition.constructorNestingLevel && (ast).operand1.nodeType == TypeScript.NodeType.This) { + if((ast).operand2.nodeType == TypeScript.NodeType.Name) { + var op2ID = ((ast).operand2); + if(!this.currentClassDefinition.knownMemberNames[op2ID.actualText]) { + ast = this.parseClassMemberVariableDeclaration(op2ID, ast.minChar, true, errorRecoverySet, TypeScript.Modifiers.Public); + subsumedExpr = true; + } + } + } + if(!subsumedExpr) { + temp = ast; + while(temp.nodeType == TypeScript.NodeType.Dot) { + var binExpr = temp; + temp = binExpr.operand2; + } + if(temp.nodeType == TypeScript.NodeType.Name) { + id = temp; + idHint = id.actualText; + } + } + } + if((!this.scanner.lastTokenHadNewline()) && ((this.currentToken.tokenId == TypeScript.TokenID.PlusPlus) || (this.currentToken.tokenId == TypeScript.TokenID.MinusMinus))) { + canAssign = false; + var operand = ast; + ast = new TypeScript.UnaryExpression((this.currentToken.tokenId == TypeScript.TokenID.PlusPlus) ? TypeScript.NodeType.IncPost : TypeScript.NodeType.DecPost, operand); + ast.limChar = this.scanner.pos; + ast.minChar = operand.minChar; + this.currentToken = this.scanner.scan(); + } + } + for(; ; ) { + tokenInfo = TypeScript.lookupToken(this.currentToken.tokenId); + if((tokenInfo == undefined) || (tokenInfo.binopNodeType == TypeScript.NodeType.None)) { + break; + } + if((!allowIn) && (tokenInfo.binopNodeType == TypeScript.NodeType.In)) { + break; + } + if(tokenInfo.binopPrecedence == TypeScript.OperatorPrecedence.Assignment) { + if(tokenInfo.binopPrecedence < minPrecedence) { + break; + } + if(!canAssign) { + this.reportParseError("illegal assignment"); + } + } else if(tokenInfo.binopPrecedence <= minPrecedence) { + break; + } + if(possiblyInLambda && this.currentToken.tokenId == TypeScript.TokenID.Comma && this.scanner.getLookAheadToken().tokenId == TypeScript.TokenID.DotDotDot) { + exprIsAnonLambda = true; + canAssign = false; + ast = this.parseLambdaExpr(errorRecoverySet, ast, false, true); + break; + } + this.currentToken = this.scanner.scan(); + canAssign = false; + if(tokenInfo.binopNodeType == TypeScript.NodeType.ConditionalExpression) { + if(possiblyInLambda && (this.currentToken.tokenId == TypeScript.TokenID.Equals || this.currentToken.tokenId == TypeScript.TokenID.Colon || this.currentToken.tokenId == TypeScript.TokenID.CloseParen || this.currentToken.tokenId == TypeScript.TokenID.Comma)) { + exprIsAnonLambda = true; + canAssign = true; + } else { + this.prevExpr = ast; + var whenTrue = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.Colon, TypeScript.OperatorPrecedence.Assignment, allowIn, TypeContext.NoTypes); + this.prevExpr = null; + this.checkCurrentToken(TypeScript.TokenID.Colon, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); + var whenFalse = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.BinOp, TypeScript.OperatorPrecedence.Assignment, allowIn, TypeContext.NoTypes); + ast = new TypeScript.ConditionalExpression(ast, whenTrue, whenFalse); + } + } else { + var tc = TypeContext.NoTypes; + var binExpr2; + binExpr2 = new TypeScript.BinaryExpression(tokenInfo.binopNodeType, ast, this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.BinOp, tokenInfo.binopPrecedence, allowIn, TypeContext.NoTypes, possiblyInLambda)); + if(binExpr2.operand2.nodeType == TypeScript.NodeType.FuncDecl) { + var funcDecl = binExpr2.operand2; + funcDecl.hint = idHint; + } + binExpr2.minChar = ast.minChar; + binExpr2.limChar = this.scanner.lastTokenLimChar(); + idHint = null; + ast = binExpr2; + } + } + if(canAssign) { + ast.flags |= TypeScript.ASTFlags.Writeable; + } + if(!exprIsAnonLambda) { + ast.minChar = minChar; + ast.limChar = TypeScript.max(ast.limChar, this.scanner.lastTokenLimChar()); + if(preComments) { + ast.preComments = ast.preComments ? preComments.concat(ast.preComments) : preComments; + } + ast.postComments = this.parseCommentsForLine(this.scanner.line); + } + return ast; + }; + Parser.prototype.parsePostfixOperators = function (errorRecoverySet, ast, allowCall, inNew, typeContext, lhsMinChar, lhsLimChar) { + var count = 0; + if(!ast) { + ast = new TypeScript.AST(TypeScript.NodeType.EmptyExpr); + ast.isParenthesized = true; + } + ast.minChar = lhsMinChar; + ast.limChar = lhsLimChar; + for(; ; ) { + switch(this.currentToken.tokenId) { + case TypeScript.TokenID.OpenParen: + if(inNew) { + var callExpr = ast; + callExpr.arguments = this.parseArgList(errorRecoverySet); + inNew = false; + } else { + if(!allowCall) { + return ast; + } + ast = new TypeScript.CallExpression(TypeScript.NodeType.Call, ast, this.parseArgList(errorRecoverySet)); + ast.minChar = lhsMinChar; + } + ast.limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet); + break; + case TypeScript.TokenID.OpenBracket: + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.CloseBracket) { + if(TypeScript.hasFlag(typeContext, TypeContext.ArraySuffix)) { + this.currentToken = this.scanner.scan(); + if(ast.nodeType == TypeScript.NodeType.TypeRef) { + var typeRef = ast; + typeRef.arrayCount++; + } else { + ast = new TypeScript.BinaryExpression(TypeScript.NodeType.Index, ast, null); + } + ast.limChar = this.scanner.pos; + break; + } + } + ast = new TypeScript.BinaryExpression(TypeScript.NodeType.Index, ast, this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RBrack, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes)); + ast.minChar = lhsMinChar; + ast.limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseBracket, errorRecoverySet); + break; + case TypeScript.TokenID.Dot: { + var name = null; + var curpos = this.scanner.pos; + this.currentToken = this.scanner.scan(); + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || ((!this.errorRecovery || !this.scanner.lastTokenHadNewline()) && TypeScript.convertTokToIDName(this.currentToken))) { + ast.flags |= TypeScript.ASTFlags.DotLHS; + name = this.createRef(this.currentToken.getText(), (this.currentToken).hasEscapeSequence, this.scanner.startPos); + name.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + } else { + this.reportParseError("Expected identifier following dot"); + if(this.errorRecovery) { + this.skip(errorRecoverySet); + ast.flags |= (TypeScript.ASTFlags.Error | TypeScript.ASTFlags.DotLHS); + return ast; + } else { + name = new TypeScript.MissingIdentifier(); + } + } + ast = new TypeScript.BinaryExpression(TypeScript.NodeType.Dot, ast, name); + ast.minChar = lhsMinChar; + ast.limChar = this.scanner.lastTokenLimChar(); + break; + } + case TypeScript.TokenID.EqualsGreaterThan: + ast = this.parseFncDecl(errorRecoverySet, false, false, false, null, false, false, false, TypeScript.Modifiers.None, { + preProcessedLambdaArgs: ast + }, false); + (ast).fncFlags |= TypeScript.FncFlags.IsFunctionExpression; + ast.minChar = lhsMinChar; + ast.limChar = this.scanner.lastTokenLimChar(); + break; + default: + return ast; + } + } + }; + Parser.prototype.parseTry = function (tryNode, errorRecoverySet, parentModifiers) { + var minChar = this.scanner.startPos; + var preComments = this.parseComments(); + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId != TypeScript.TokenID.OpenBrace) { + this.reportParseError("Expected '{'"); + if(this.errorRecovery) { + var etryNode = tryNode; + etryNode.minChar = minChar; + etryNode.limChar = this.scanner.lastTokenLimChar(); + etryNode.flags |= TypeScript.ASTFlags.Error; + return etryNode; + } + } + tryNode.body = this.parseStatement(errorRecoverySet, TypeScript.AllowedElements.None, parentModifiers); + tryNode.minChar = minChar; + tryNode.limChar = tryNode.body.limChar; + tryNode.preComments = preComments; + tryNode.postComments = this.parseComments(); + return tryNode; + }; + Parser.prototype.parseCatch = function (errorRecoverySet, parentModifiers) { + var catchMinChar = this.scanner.startPos; + var preComments = this.parseComments(); + this.currentToken = this.scanner.scan(); + this.checkCurrentToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); + if((this.currentToken.tokenId != TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + this.reportParseError("Expected identifier in catch header"); + if(this.errorRecovery) { + this.skip(errorRecoverySet); + var ecatch = new TypeScript.Catch(new TypeScript.VarDecl(new TypeScript.MissingIdentifier(), this.nestingLevel), new TypeScript.Statement(TypeScript.NodeType.Empty)); + ecatch.statement.minChar = catchMinChar; + ecatch.statement.limChar = this.scanner.pos; + ecatch.minChar = this.scanner.startPos; + ecatch.limChar = this.scanner.pos; + ecatch.flags |= TypeScript.ASTFlags.Error; + return ecatch; + } + } + var param = new TypeScript.VarDecl(TypeScript.Identifier.fromToken(this.currentToken), this.nestingLevel); + param.id.minChar = this.scanner.startPos; + param.id.limChar = this.scanner.pos; + param.minChar = param.id.minChar; + param.limChar = param.id.limChar; + this.currentToken = this.scanner.scan(); + var statementPos = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); + if(this.currentToken.tokenId != TypeScript.TokenID.OpenBrace) { + this.reportParseError("Expected '{' to start catch body"); + if(this.errorRecovery) { + this.skip(errorRecoverySet); + var ecatch = new TypeScript.Catch(new TypeScript.VarDecl(new TypeScript.MissingIdentifier(), this.nestingLevel), new TypeScript.Statement(TypeScript.NodeType.Empty)); + ecatch.statement.minChar = catchMinChar; + ecatch.statement.limChar = statementPos; + ecatch.minChar = this.scanner.startPos; + ecatch.limChar = this.scanner.pos; + ecatch.flags |= TypeScript.ASTFlags.Error; + return ecatch; + } + } + var catchStmt = this.parseStatement(errorRecoverySet, TypeScript.AllowedElements.None, parentModifiers); + var catchNode = new TypeScript.Catch(param, catchStmt); + catchNode.statement.minChar = catchMinChar; + catchNode.statement.limChar = statementPos; + catchNode.minChar = catchMinChar; + catchNode.limChar = catchStmt.limChar; + catchNode.preComments = preComments; + catchNode.postComments = this.parseComments(); + return catchNode; + }; + Parser.prototype.parseFinally = function (errorRecoverySet, parentModifiers) { + var finMinChar = this.scanner.startPos; + var preComments = this.parseComments(); + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId != TypeScript.TokenID.OpenBrace) { + this.reportParseError("Expected '{' to start body of finally statement"); + if(this.errorRecovery) { + this.skip(errorRecoverySet); + var efin = new TypeScript.Finally(new TypeScript.Statement(TypeScript.NodeType.Empty)); + efin.flags |= TypeScript.ASTFlags.Error; + efin.minChar = this.scanner.startPos; + efin.limChar = this.scanner.pos; + return efin; + } + } + var finBody = this.parseStatement(errorRecoverySet, TypeScript.AllowedElements.None, parentModifiers); + var fin = new TypeScript.Finally(finBody); + fin.minChar = finMinChar; + fin.limChar = fin.body.limChar; + fin.preComments = preComments; + fin.postComments = this.parseComments(); + return fin; + }; + Parser.prototype.parseTryCatchFinally = function (errorRecoverySet, parentModifiers, labelList) { + var tryPart = new TypeScript.Try(null); + var tryMinChar = this.scanner.startPos; + this.pushStmt(tryPart, labelList); + this.parseTry(tryPart, errorRecoverySet | TypeScript.ErrorRecoverySet.Catch, parentModifiers); + this.popStmt(); + var tc = null; + var tf = null; + if(this.currentToken.tokenId == TypeScript.TokenID.Catch) { + var catchPart = this.parseCatch(errorRecoverySet | TypeScript.ErrorRecoverySet.Catch, parentModifiers); + tc = new TypeScript.TryCatch(tryPart, catchPart); + tc.minChar = tryPart.minChar; + tc.limChar = catchPart.limChar; + } + if(this.currentToken.tokenId != TypeScript.TokenID.Finally) { + if(tc == null) { + this.reportParseError("try with neither catch nor finally"); + if(this.errorRecovery) { + var etf = new TypeScript.TryFinally(tryPart, new TypeScript.Finally(new TypeScript.AST(TypeScript.NodeType.Empty))); + etf.flags |= TypeScript.ASTFlags.Error; + etf.minChar = this.scanner.startPos; + etf.limChar = this.scanner.pos; + return etf; + } + return new TypeScript.TryFinally(tryPart, new TypeScript.Finally(new TypeScript.AST(TypeScript.NodeType.Empty))); + } else { + return tc; + } + } else { + if(tc) { + tryPart = tc; + } + var finallyPart = this.parseFinally(errorRecoverySet, parentModifiers); + tf = new TypeScript.TryFinally(tryPart, finallyPart); + tf.minChar = tryMinChar; + tf.limChar = finallyPart.limChar; + return tf; + } + }; + Parser.prototype.parseStatement = function (errorRecoverySet, allowedElements, parentModifiers) { + var ast = null; + var labelList = null; + var astList = null; + var temp; + var modifiers = TypeScript.Modifiers.None; + var minChar = this.scanner.startPos; + var forInOk = false; + var needTerminator = false; + var fnOrVar = null; + var preComments = this.parseComments(); + function isAmbient() { + return TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient) || TypeScript.hasFlag(parentModifiers, TypeScript.Modifiers.Ambient); + } + function mayNotBeExported() { + if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { + this.reportError("Statement may not be exported"); + } + } + for(; ; ) { + switch(this.currentToken.tokenId) { + case TypeScript.TokenID.EndOfFile: + ast = new TypeScript.AST(TypeScript.NodeType.Error); + ast.minChar = minChar; + ast.limChar = this.scanner.pos; + break; + case TypeScript.TokenID.Function: + if(this.parsingDeclareFile || isAmbient() || this.ambientModule) { + this.currentToken = this.scanner.scan(); + fnOrVar = this.parsePropertyDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, modifiers, true, false, true); + if(fnOrVar.nodeType == TypeScript.NodeType.VarDecl) { + this.reportParseError("function keyword can only introduce function declaration"); + } else if((fnOrVar.nodeType == TypeScript.NodeType.FuncDecl) && ((fnOrVar).fncFlags , TypeScript.FncFlags.IsFatArrowFunction)) { + needTerminator = true; + } + ast = fnOrVar; + if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported) || this.parsingDeclareFile || this.ambientModule && ast.nodeType == TypeScript.NodeType.FuncDecl) { + (ast).fncFlags |= TypeScript.FncFlags.Exported; + } + } else { + ast = this.parseFncDecl(errorRecoverySet, true, false, false, null, false, false, false, modifiers, null, true); + if(TypeScript.hasFlag((ast).fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { + needTerminator = true; + } + if(this.ambientModule) { + this.reportParseError("function declaration not permitted within ambient module"); + } + if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { + (ast).fncFlags |= TypeScript.FncFlags.Exported; + } + } + break; + case TypeScript.TokenID.Module: + if((allowedElements & TypeScript.AllowedElements.ModuleDeclarations) == TypeScript.AllowedElements.None) { + this.reportParseError("module not allowed in this context"); + this.currentToken = this.scanner.scan(); + ast = new TypeScript.AST(TypeScript.NodeType.Error); + ast.minChar = minChar; + ast.limChar = this.scanner.lastTokenLimChar(); + } else { + ast = this.parseModuleDecl(errorRecoverySet, modifiers, preComments); + preComments = null; + } + break; + case TypeScript.TokenID.Import: + if((allowedElements & TypeScript.AllowedElements.ModuleDeclarations) == TypeScript.AllowedElements.None) { + this.reportParseError("module not allowed in this context"); + this.currentToken = this.scanner.scan(); + ast = new TypeScript.AST(TypeScript.NodeType.Error); + ast.minChar = minChar; + ast.limChar = this.scanner.lastTokenLimChar(); + } else { + if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { + this.reportParseError("export keyword not permitted on import declaration"); + } + ast = this.parseImportDeclaration(errorRecoverySet, modifiers); + needTerminator = true; + } + break; + case TypeScript.TokenID.Export: + if((allowedElements & TypeScript.AllowedElements.ModuleDeclarations) == TypeScript.AllowedElements.None) { + this.reportParseError("'export' statements are only allowed at the global and module levels"); + this.currentToken = this.scanner.scan(); + ast = new TypeScript.AST(TypeScript.NodeType.Error); + ast.minChar = minChar; + ast.limChar = this.scanner.lastTokenLimChar(); + } + if(this.topLevel) { + this.hasTopLevelImportOrExport = true; + } + modifiers |= TypeScript.Modifiers.Exported; + this.currentToken = this.scanner.scan(); + break; + case TypeScript.TokenID.Private: + modifiers |= TypeScript.Modifiers.Private; + this.currentToken = this.scanner.scan(); + if(this.parsingClassConstructorDefinition) { + if(!this.inferPropertiesFromThisAssignment) { + this.reportParseError("Property declarations are not permitted within constructor bodies"); + } + minChar = this.scanner.pos; + if(this.inferPropertiesFromThisAssignment && (this.currentToken.tokenId != TypeScript.TokenID.This || (this.currentToken = this.scanner.scan()).tokenId != TypeScript.TokenID.Dot)) { + this.reportParseError("Expected 'this.' for property declaration"); + this.currentToken = this.scanner.scan(); + ast = new TypeScript.AST(TypeScript.NodeType.Error); + ast.minChar = minChar; + ast.limChar = this.scanner.lastTokenLimChar(); + } else { + this.currentToken = this.scanner.scan(); + var id = TypeScript.Identifier.fromToken(this.currentToken); + id.minChar = this.scanner.startPos; + id.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + ast = this.parseClassMemberVariableDeclaration(id, minChar, this.parsingClassConstructorDefinition, errorRecoverySet, modifiers); + } + } else { + if(this.currentToken.tokenId != TypeScript.TokenID.Interface) { + if(this.currentToken.tokenId == TypeScript.TokenID.Get) { + this.prevIDTok = this.currentToken; + this.currentToken = this.scanner.scan(); + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("Property accessors are only available when targeting ES5 or greater"); + } + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + modifiers |= TypeScript.Modifiers.Getter; + this.prevIDTok = null; + } + } else if(this.currentToken.tokenId == TypeScript.TokenID.Set) { + this.prevIDTok = this.currentToken; + this.currentToken = this.scanner.scan(); + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("Property accessors are only available when targeting ES5 or greater"); + } + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + modifiers |= TypeScript.Modifiers.Setter; + this.prevIDTok = null; + } + } + fnOrVar = this.parsePropertyDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, modifiers, isAmbient(), false); + if((fnOrVar.nodeType == TypeScript.NodeType.VarDecl) || ((fnOrVar.nodeType == TypeScript.NodeType.FuncDecl) && (TypeScript.hasFlag((fnOrVar).fncFlags, TypeScript.FncFlags.IsFatArrowFunction)))) { + needTerminator = true; + } + ast = fnOrVar; + } + } + break; + case TypeScript.TokenID.Public: + if(this.parsingClassConstructorDefinition) { + if(!this.inferPropertiesFromThisAssignment) { + this.reportParseError("Property declarations are not permitted within constructor bodies"); + } + this.currentToken = this.scanner.scan(); + minChar = this.scanner.pos; + modifiers |= TypeScript.Modifiers.Public; + if(this.inferPropertiesFromThisAssignment && (this.currentToken.tokenId != TypeScript.TokenID.This || (this.currentToken = this.scanner.scan()).tokenId != TypeScript.TokenID.Dot)) { + this.reportParseError("Expected 'this.' for property declaration"); + this.currentToken = this.scanner.scan(); + ast = new TypeScript.AST(TypeScript.NodeType.Error); + ast.minChar = minChar; + ast.limChar = this.scanner.lastTokenLimChar(); + } else { + this.currentToken = this.scanner.scan(); + var id = TypeScript.Identifier.fromToken(this.currentToken); + id.minChar = this.scanner.startPos; + id.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + ast = this.parseClassMemberVariableDeclaration(id, minChar, this.parsingClassConstructorDefinition, errorRecoverySet, modifiers); + } + } else { + if((allowedElements & TypeScript.AllowedElements.Properties) == TypeScript.AllowedElements.None) { + this.reportParseError("'property' statements are only allowed within classes"); + this.currentToken = this.scanner.scan(); + ast = new TypeScript.AST(TypeScript.NodeType.Error); + ast.minChar = minChar; + ast.limChar = this.scanner.lastTokenLimChar(); + } else { + modifiers |= TypeScript.Modifiers.Public; + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.Get) { + this.prevIDTok = this.currentToken; + this.currentToken = this.scanner.scan(); + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("Property accessors are only available when targeting ES5 or greater"); + } + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + modifiers |= TypeScript.Modifiers.Getter; + this.prevIDTok = null; + } + } else if(this.currentToken.tokenId == TypeScript.TokenID.Set) { + this.prevIDTok = this.currentToken; + this.currentToken = this.scanner.scan(); + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("Property accessors are only available when targeting ES5 or greater"); + } + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + modifiers |= TypeScript.Modifiers.Setter; + this.prevIDTok = null; + } + } + fnOrVar = this.parsePropertyDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, modifiers, isAmbient(), false); + if((fnOrVar.nodeType == TypeScript.NodeType.VarDecl) || ((fnOrVar.nodeType == TypeScript.NodeType.FuncDecl) && TypeScript.hasFlag((fnOrVar).fncFlags, TypeScript.FncFlags.IsFatArrowFunction))) { + needTerminator = true; + } + ast = fnOrVar; + } + } + break; + case TypeScript.TokenID.Declare: + if(!(allowedElements & TypeScript.AllowedElements.AmbientDeclarations)) { + this.reportParseError("Ambient declarations are only allowed at the top-level or module scopes"); + } + if(!this.parsingDeclareFile && TypeScript.hasFlag(parentModifiers, TypeScript.Modifiers.Ambient)) { + this.reportParseError("Duplicate ambient declaration in this context. (Is the enclosing module or class already ambient?)"); + } + modifiers |= TypeScript.Modifiers.Ambient; + this.currentToken = this.scanner.scan(); + break; + case TypeScript.TokenID.Class: + if((allowedElements & TypeScript.AllowedElements.ClassDeclarations) == TypeScript.AllowedElements.None) { + this.reportParseError("class not allowed in this context"); + this.currentToken = this.scanner.scan(); + ast = new TypeScript.AST(TypeScript.NodeType.Error); + ast.minChar = minChar; + ast.limChar = this.scanner.lastTokenLimChar(); + } else { + ast = this.parseClassDecl(errorRecoverySet, minChar, modifiers); + } + break; + case TypeScript.TokenID.Interface: + if((allowedElements & TypeScript.AllowedElements.InterfaceDeclarations) == TypeScript.AllowedElements.None) { + this.reportParseError("interface not allowed in this context"); + this.currentToken = this.scanner.scan(); + ast = new TypeScript.AST(TypeScript.NodeType.Error); + ast.minChar = minChar; + ast.limChar = this.scanner.lastTokenLimChar(); + } else { + ast = this.parseInterfaceDecl(errorRecoverySet, modifiers); + } + break; + case TypeScript.TokenID.Var: + var declAst = this.parseVariableDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart, modifiers, true, false); + if(declAst.nodeType == TypeScript.NodeType.VarDecl) { + ast = declAst; + } else { + ast = new TypeScript.Block(declAst, false); + } + needTerminator = true; + break; + case TypeScript.TokenID.Static: + if(this.currentClassDecl == null) { + this.reportParseError("Statics may only be class members"); + } + mayNotBeExported(); + modifiers |= TypeScript.Modifiers.Public; + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.Get) { + this.prevIDTok = this.currentToken; + this.currentToken = this.scanner.scan(); + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("Property accessors are only available when targeting ES5 or greater"); + } + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + modifiers |= TypeScript.Modifiers.Getter; + this.prevIDTok = null; + } + } else if(this.currentToken.tokenId == TypeScript.TokenID.Set) { + this.currentToken = this.scanner.scan(); + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("Property accessors are only available when targeting ES5 or greater"); + } + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + modifiers |= TypeScript.Modifiers.Setter; + } + } + if(isAmbient()) { + modifiers |= TypeScript.Modifiers.Ambient; + } + fnOrVar = this.parsePropertyDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, modifiers, this.parsingDeclareFile || (modifiers & TypeScript.Modifiers.Ambient) != TypeScript.Modifiers.None, true); + var staticsList = this.topStaticsList(); + if(staticsList && fnOrVar.nodeType == TypeScript.NodeType.VarDecl) { + staticsList.append(fnOrVar); + } + if(fnOrVar.nodeType == TypeScript.NodeType.VarDecl || ((fnOrVar.nodeType == TypeScript.NodeType.FuncDecl) && TypeScript.hasFlag((fnOrVar).fncFlags, TypeScript.FncFlags.IsFatArrowFunction))) { + needTerminator = true; + } + ast = fnOrVar; + break; + case TypeScript.TokenID.For: + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("syntax error: for statement does not take modifiers"); + } + minChar = this.scanner.startPos; + this.checkNextToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart | TypeScript.ErrorRecoverySet.Var); + forInOk = true; + switch(this.currentToken.tokenId) { + case TypeScript.TokenID.Var: + temp = this.parseVariableDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon | TypeScript.ErrorRecoverySet.In, TypeScript.Modifiers.None, false, false); + break; + case TypeScript.TokenID.Semicolon: + temp = null; + break; + default: + temp = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon | TypeScript.ErrorRecoverySet.In, TypeScript.OperatorPrecedence.None, false, TypeContext.NoTypes); + break; + } + if(this.currentToken.tokenId == TypeScript.TokenID.In) { + if((temp == null) || (!forInOk)) { + this.reportParseError("malformed for statement"); + if(this.errorRecovery) { + this.skip(errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); + ast = new TypeScript.AST(TypeScript.NodeType.Empty); + ast.flags |= TypeScript.ASTFlags.Error; + } + } else { + this.currentToken = this.scanner.scan(); + var forInStmt = new TypeScript.ForInStatement(temp, this.parseExpr(TypeScript.ErrorRecoverySet.RParen | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, false, TypeContext.NoTypes)); + forInStmt.limChar = this.scanner.pos; + forInStmt.statement.minChar = minChar; + forInStmt.statement.limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseParen, TypeScript.ErrorRecoverySet.StmtStart | errorRecoverySet); + this.pushStmt(forInStmt, labelList); + forInStmt.body = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); + this.popStmt(); + forInStmt.minChar = minChar; + ast = forInStmt; + } + } else { + var forStmt = new TypeScript.ForStatement(temp); + forStmt.minChar = minChar; + this.checkCurrentToken(TypeScript.TokenID.Semicolon, errorRecoverySet); + if(this.currentToken.tokenId == TypeScript.TokenID.Semicolon) { + forStmt.cond = null; + } else { + forStmt.cond = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); + if(this.currentToken.tokenId != TypeScript.TokenID.Semicolon) { + this.skip(errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); + ast = forStmt; + ast.flags |= TypeScript.ASTFlags.Error; + } + } + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.CloseParen) { + forStmt.incr = null; + } else { + forStmt.incr = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); + } + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly); + this.pushStmt(forStmt, labelList); + forStmt.body = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); + this.popStmt(); + forStmt.limChar = forStmt.body.limChar; + ast = forStmt; + } + break; + case TypeScript.TokenID.With: + { + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("'with' statements are only available in ES5 codegen mode or better"); + } + if(this.strictMode) { + this.reportParseError("'with' statements are not available in strict mode"); + } + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("'with' statement does not take modifiers"); + } + minChar = this.scanner.startPos; + this.checkNextToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart | TypeScript.ErrorRecoverySet.Var); + var expr = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.Colon, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly); + var withStmt = new TypeScript.WithStatement(expr); + withStmt.body = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); + withStmt.minChar = minChar; + withStmt.limChar = withStmt.body.limChar; + ast = withStmt; + } + break; + case TypeScript.TokenID.Switch: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("'switch' statement does not take modifiers"); + } + this.checkNextToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); + var switchStmt = new TypeScript.SwitchStatement(this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes)); + switchStmt.statement.minChar = minChar; + switchStmt.statement.limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly); + var caseListMinChar = this.scanner.startPos; + this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.SCase); + switchStmt.defaultCase = null; + switchStmt.caseList = new TypeScript.ASTList(); + var caseStmt = null; + this.pushStmt(switchStmt, labelList); + for(; ; ) { + if((this.currentToken.tokenId == TypeScript.TokenID.Case) || (this.currentToken.tokenId == TypeScript.TokenID.Default)) { + var isDefault = (this.currentToken.tokenId == TypeScript.TokenID.Default); + caseStmt = new TypeScript.CaseStatement(); + caseStmt.minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + if(isDefault) { + switchStmt.defaultCase = caseStmt; + } else { + caseStmt.expr = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.Colon, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); + } + caseStmt.colonSpan.minChar = this.scanner.startPos; + caseStmt.colonSpan.limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.Colon, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); + caseStmt.body = new TypeScript.ASTList(); + this.parseStatementList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, caseStmt.body, false, true, allowedElements, modifiers); + caseStmt.limChar = caseStmt.body.limChar; + switchStmt.caseList.append(caseStmt); + } else { + break; + } + } + switchStmt.caseList.minChar = caseListMinChar; + switchStmt.caseList.limChar = this.scanner.pos; + switchStmt.limChar = switchStmt.caseList.limChar; + this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); + this.popStmt(); + ast = switchStmt; + break; + } + case TypeScript.TokenID.While: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("'while' statement does not take modifiers"); + } + minChar = this.scanner.startPos; + this.checkNextToken(TypeScript.TokenID.OpenParen, TypeScript.ErrorRecoverySet.ExprStart | errorRecoverySet); + var whileStmt = new TypeScript.WhileStatement(this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes)); + whileStmt.minChar = minChar; + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); + this.pushStmt(whileStmt, labelList); + whileStmt.body = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); + whileStmt.limChar = whileStmt.body.limChar; + this.popStmt(); + ast = whileStmt; + break; + } + case TypeScript.TokenID.Do: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("'do' statement does not take modifiers"); + } + minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + var doStmt = new TypeScript.DoWhileStatement(); + doStmt.minChar = minChar; + this.pushStmt(doStmt, labelList); + doStmt.body = this.parseStatement(errorRecoverySet | TypeScript.ErrorRecoverySet.While, allowedElements, parentModifiers); + this.popStmt(); + doStmt.whileAST = new TypeScript.Identifier("while"); + doStmt.whileAST.minChar = this.scanner.startPos; + this.checkCurrentToken(TypeScript.TokenID.While, errorRecoverySet | TypeScript.ErrorRecoverySet.LParen); + doStmt.whileAST.limChar = doStmt.whileAST.minChar + 5; + this.checkCurrentToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); + doStmt.cond = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); + doStmt.limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet); + ast = doStmt; + if(this.currentToken.tokenId == TypeScript.TokenID.Semicolon) { + this.currentToken = this.scanner.scan(); + } + break; + } + case TypeScript.TokenID.If: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("if statement does not take modifiers"); + } + minChar = this.scanner.startPos; + this.checkNextToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); + var ifStmt = new TypeScript.IfStatement(this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.LParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes)); + ifStmt.minChar = minChar; + ifStmt.statement.minChar = minChar; + ifStmt.statement.limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); + this.pushStmt(ifStmt, labelList); + ifStmt.thenBod = this.parseStatement(TypeScript.ErrorRecoverySet.Else | errorRecoverySet, allowedElements, parentModifiers); + ifStmt.limChar = ifStmt.thenBod.limChar; + if(this.currentToken.tokenId == TypeScript.TokenID.Else) { + this.currentToken = this.scanner.scan(); + ifStmt.elseBod = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); + ifStmt.limChar = ifStmt.elseBod.limChar; + } + this.popStmt(); + ast = ifStmt; + break; + } + case TypeScript.TokenID.Try: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("try statement does not take modifiers"); + } + minChar = this.scanner.startPos; + ast = this.parseTryCatchFinally(errorRecoverySet, parentModifiers, labelList); + break; + } + case TypeScript.TokenID.OpenBrace: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("block does not take modifiers"); + } + minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + var block = new TypeScript.Block(new TypeScript.ASTList(), true); + this.pushStmt(block, labelList); + this.parseStatementList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, block.statements, false, false, TypeScript.AllowedElements.None, modifiers); + this.popStmt(); + block.statements.minChar = minChar; + block.statements.limChar = this.scanner.pos; + block.minChar = block.statements.minChar; + block.limChar = block.statements.limChar; + this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); + ast = block; + break; + } + case TypeScript.TokenID.Semicolon: + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("modifier can not appear here"); + } + ast = new TypeScript.AST(TypeScript.NodeType.Empty); + this.currentToken = this.scanner.scan(); + break; + case TypeScript.TokenID.Break: + case TypeScript.TokenID.Continue: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("modifiers can not appear before jump statement"); + } + var jump = new TypeScript.Jump((this.currentToken.tokenId == TypeScript.TokenID.Break) ? TypeScript.NodeType.Break : TypeScript.NodeType.Continue); + this.currentToken = this.scanner.scan(); + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) && (!this.scanner.lastTokenHadNewline())) { + jump.target = this.currentToken.getText(); + this.currentToken = this.scanner.scan(); + } + this.resolveJumpTarget(jump); + ast = jump; + needTerminator = true; + break; + } + case TypeScript.TokenID.Return: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("modifiers can not appear before return statement"); + } + if(!this.inFunction) { + this.reportParseError("return statement outside of function body"); + } + minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + var retStmt = new TypeScript.ReturnStatement(); + retStmt.minChar = minChar; + if((this.currentToken.tokenId != TypeScript.TokenID.Semicolon) && (this.currentToken.tokenId != TypeScript.TokenID.CloseBrace) && (!(this.scanner.lastTokenHadNewline()))) { + retStmt.returnExpression = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); + } + needTerminator = true; + retStmt.limChar = this.scanner.lastTokenLimChar(); + ast = retStmt; + break; + } + case TypeScript.TokenID.Throw: + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("modifiers can not appear before a throw statement"); + } + minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + if((this.currentToken.tokenId != TypeScript.TokenID.Semicolon) && (this.currentToken.tokenId != TypeScript.TokenID.CloseBrace) && (!(this.scanner.lastTokenHadNewline()))) { + temp = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); + } else { + this.reportParseError("throw with no target"); + temp = null; + } + ast = new TypeScript.UnaryExpression(TypeScript.NodeType.Throw, temp); + ast.limChar = this.scanner.lastTokenLimChar(); + needTerminator = true; + break; + case TypeScript.TokenID.Enum: + this.currentToken = this.scanner.scan(); + ast = this.parseEnumDecl(errorRecoverySet, modifiers); + ast.minChar = minChar; + ast.limChar = this.scanner.lastTokenLimChar(); + if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + (ast).modFlags |= TypeScript.ModuleFlags.Ambient; + } + if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { + (ast).modFlags |= TypeScript.ModuleFlags.Exported; + } + break; + case TypeScript.TokenID.Debugger: + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("modifiers can not appear before debugger statement"); + } + minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + var debuggerStmt = new TypeScript.DebuggerStatement(); + debuggerStmt.minChar = minChar; + needTerminator = true; + debuggerStmt.limChar = this.scanner.lastTokenLimChar(); + ast = debuggerStmt; + break; + default: + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("modifiers can not appear before an expression statement or label"); + } + minChar = this.scanner.startPos; + var svPos = this.scanner.pos; + temp = this.parseExpr(TypeScript.ErrorRecoverySet.Colon | TypeScript.ErrorRecoverySet.StmtStart | errorRecoverySet, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); + if(this.scanner.pos == svPos) { + this.currentToken = this.scanner.scan(); + ast = temp; + } else if((this.currentToken.tokenId == TypeScript.TokenID.Colon) && (!this.scanner.lastTokenHadNewline()) && temp && (temp.nodeType == TypeScript.NodeType.Name)) { + if(labelList == null) { + labelList = new TypeScript.ASTList(); + } + labelList.append(new TypeScript.Label(temp)); + this.currentToken = this.scanner.scan(); + } else { + ast = temp; + needTerminator = true; + } + } + if(ast) { + break; + } + } + if(needTerminator) { + switch(this.currentToken.tokenId) { + case TypeScript.TokenID.Semicolon: + this.currentToken = this.scanner.scan(); + ast.flags |= TypeScript.ASTFlags.ExplicitSemicolon; + break; + case TypeScript.TokenID.EndOfFile: + ast.limChar = this.scanner.pos; + case TypeScript.TokenID.CloseBrace: + ast.flags |= TypeScript.ASTFlags.AutomaticSemicolon; + if(this.style_requireSemi) { + this.reportParseStyleError("no automatic semicolon"); + } + break; + default: + if(!this.scanner.lastTokenHadNewline()) { + this.reportParseError("Expected ';'"); + } else { + ast.flags |= TypeScript.ASTFlags.AutomaticSemicolon; + if(this.style_requireSemi) { + this.reportParseStyleError("no automatic semicolon"); + } + } + break; + } + } + if(labelList) { + ast = new TypeScript.LabeledStatement(labelList, ast); + } + ast.minChar = minChar; + ast.limChar = TypeScript.max(ast.limChar, this.scanner.lastTokenLimChar()); + if(preComments) { + ast.preComments = ast.preComments ? preComments.concat(ast.preComments) : preComments; + } + if(this.ambientModule && (!this.okAmbientModuleMember(ast))) { + this.reportParseError("statement not permitted within ambient module"); + } + ast.flags |= TypeScript.ASTFlags.IsStatement; + return ast; + }; + Parser.prototype.okAmbientModuleMember = function (ast) { + var nt = ast.nodeType; + return (nt == TypeScript.NodeType.ClassDeclaration) || (nt == TypeScript.NodeType.ImportDeclaration) || (nt == TypeScript.NodeType.InterfaceDeclaration) || (nt == TypeScript.NodeType.ModuleDeclaration) || (nt == TypeScript.NodeType.Empty) || (nt == TypeScript.NodeType.VarDecl) || ((nt == TypeScript.NodeType.Block) && !(ast).isStatementBlock) || ((nt == TypeScript.NodeType.FuncDecl) && ((ast).bod == null)); + }; + Parser.prototype.parseStatementList = function (errorRecoverySet, statements, sourceElms, noLeadingCase, allowedElements, parentModifiers) { + var directivePrologue = sourceElms; + statements.minChar = this.scanner.startPos; + var limChar = this.scanner.pos; + var innerStmts = (allowedElements & TypeScript.AllowedElements.ModuleDeclarations) == TypeScript.AllowedElements.None; + var classNope = (allowedElements & TypeScript.AllowedElements.ClassDeclarations) == TypeScript.AllowedElements.None; + errorRecoverySet |= TypeScript.ErrorRecoverySet.TypeScriptS | TypeScript.ErrorRecoverySet.RCurly; + var oldStrictMode = this.strictMode; + this.nestingLevel++; + for(; ; ) { + if((this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) || (noLeadingCase && ((this.currentToken.tokenId == TypeScript.TokenID.Case) || (this.currentToken.tokenId == TypeScript.TokenID.Default))) || (innerStmts && (this.currentToken.tokenId == TypeScript.TokenID.Export)) || (classNope && (this.currentToken.tokenId == TypeScript.TokenID.Class)) || (this.currentToken.tokenId == TypeScript.TokenID.EndOfFile)) { + statements.limChar = limChar; + if(statements.members.length == 0) { + statements.preComments = this.parseComments(); + } else { + statements.postComments = this.parseComments(); + } + this.strictMode = oldStrictMode; + this.nestingLevel--; + return; + } + var stmt = this.parseStatement(errorRecoverySet & (~(TypeScript.ErrorRecoverySet.Else | TypeScript.ErrorRecoverySet.RParen | TypeScript.ErrorRecoverySet.Catch | TypeScript.ErrorRecoverySet.Colon)), allowedElements, parentModifiers); + if(stmt) { + stmt.postComments = this.combineComments(stmt.postComments, this.parseCommentsForLine(this.scanner.prevLine)); + statements.append(stmt); + limChar = stmt.limChar; + if(directivePrologue) { + if(stmt.nodeType == TypeScript.NodeType.QString) { + var qstring = stmt; + if(qstring.text == "\"use strict\"") { + statements.flags |= TypeScript.ASTFlags.StrictMode; + this.strictMode = true; + } else { + directivePrologue = false; + } + } else { + directivePrologue = false; + } + } + } + } + }; + Parser.prototype.quickParse = function (sourceText, filename, unitIndex) { + var svGenTarget = TypeScript.moduleGenTarget; + try { + TypeScript.moduleGenTarget = TypeScript.ModuleGenTarget.Local; + var script = this.parse(sourceText, filename, unitIndex, TypeScript.AllowedElements.QuickParse); + return new QuickParseResult(script, this.scanner.lexState); + }finally { + TypeScript.moduleGenTarget = svGenTarget; + } + }; + Parser.prototype.parse = function (sourceText, filename, unitIndex, allowedElements) { + if (typeof allowedElements === "undefined") { allowedElements = TypeScript.AllowedElements.Global; } + var _this = this; + this.fname = filename; + this.currentUnitIndex = unitIndex; + this.currentToken = null; + this.needTerminator = false; + this.inFunction = false; + this.inInterfaceDecl = false; + this.inFncDecl = false; + this.ambientModule = false; + this.ambientClass = false; + this.topLevel = true; + this.allowImportDeclaration = true; + this.prevIDTok = null; + this.statementInfoStack = new Array(); + this.hasTopLevelImportOrExport = false; + this.strictMode = false; + this.nestingLevel = 0; + this.prevExpr = null; + this.currentClassDefinition = null; + this.parsingClassConstructorDefinition = false; + this.parsingDeclareFile = false; + this.amdDependencies = []; + this.inferPropertiesFromThisAssignment = false; + this.requiresExtendsBlock = false; + this.scanner.resetComments(); + this.scanner.setErrorHandler(function (message) { + return _this.reportParseError(message); + }); + this.scanner.setSourceText(sourceText, TypeScript.LexMode.File); + var leftCurlyCount = this.scanner.leftCurlyCount; + var rightCurlyCount = this.scanner.rightCurlyCount; + var minChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + this.pushDeclLists(); + var bod = new TypeScript.ASTList(); + bod.minChar = minChar; + this.parsingDeclareFile = TypeScript.isDSTRFile(filename) || TypeScript.isDTSFile(filename); + while(true) { + this.parseStatementList(TypeScript.ErrorRecoverySet.EOF | TypeScript.ErrorRecoverySet.Func, bod, true, false, allowedElements, TypeScript.Modifiers.None); + if(this.currentToken.tokenId === TypeScript.TokenID.EndOfFile) { + break; + } + var badToken = TypeScript.tokenTable[this.currentToken.tokenId]; + this.reportParseError("Unexpected statement block terminator '" + badToken.text + "'"); + this.currentToken = this.scanner.scan(); + } + bod.limChar = this.scanner.pos; + var topLevelMod = null; + if(TypeScript.moduleGenTarget != TypeScript.ModuleGenTarget.Local && this.hasTopLevelImportOrExport) { + var correctedFileName = TypeScript.switchToForwardSlashes(filename); + var id = new TypeScript.Identifier(correctedFileName); + topLevelMod = new TypeScript.ModuleDeclaration(id, bod, this.topVarList(), null); + topLevelMod.modFlags |= TypeScript.ModuleFlags.IsDynamic; + topLevelMod.modFlags |= TypeScript.ModuleFlags.IsWholeFile; + topLevelMod.modFlags |= TypeScript.ModuleFlags.Exported; + if(this.parsingDeclareFile) { + topLevelMod.modFlags |= TypeScript.ModuleFlags.Ambient; + } + topLevelMod.minChar = minChar; + topLevelMod.limChar = this.scanner.pos; + topLevelMod.prettyName = TypeScript.getPrettyName(correctedFileName); + topLevelMod.containsUnicodeChar = this.scanner.seenUnicodeChar; + topLevelMod.containsUnicodeCharInComment = this.scanner.seenUnicodeCharInComment; + topLevelMod.amdDependencies = this.amdDependencies; + bod = new TypeScript.ASTList(); + bod.minChar = topLevelMod.minChar; + bod.limChar = topLevelMod.limChar; + bod.append(topLevelMod); + } + var script = new TypeScript.Script(this.topVarList(), this.topScopeList()); + script.bod = bod; + this.popDeclLists(); + script.minChar = minChar; + script.limChar = this.scanner.pos; + script.locationInfo = new TypeScript.LocationInfo(filename, this.scanner.lineMap, unitIndex); + script.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; + script.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; + script.isDeclareFile = this.parsingDeclareFile; + script.topLevelMod = topLevelMod; + script.containsUnicodeChar = this.scanner.seenUnicodeChar; + script.containsUnicodeCharInComment = this.scanner.seenUnicodeCharInComment; + script.requiresExtendsBlock = this.requiresExtendsBlock; + return script; + }; + return Parser; + })(); + TypeScript.Parser = Parser; + function quickParse(logger, scopeStartAST, sourceText, minChar, limChar, errorCapture) { + var fragment = sourceText.getText(minChar, limChar); + logger.log("Quick parse range (" + minChar + "," + limChar + "): \"" + TypeScript.stringToLiteral(fragment, 100) + "\""); + var quickParser = new Parser(); + quickParser.setErrorRecovery(null); + quickParser.errorCallback = errorCapture; + var quickClassDecl = new TypeScript.ClassDeclaration(null, null, null, null); + quickParser.currentClassDecl = quickClassDecl; + var result = quickParser.quickParse(new TypeScript.StringSourceText(fragment), "", 0); + return result; + } + TypeScript.quickParse = quickParse; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var PrintContext = (function () { + function PrintContext(outfile, parser) { + this.outfile = outfile; + this.parser = parser; + this.builder = ""; + this.indent1 = " "; + this.indentStrings = []; + this.indentAmt = 0; + } + PrintContext.prototype.increaseIndent = function () { + this.indentAmt++; + }; + PrintContext.prototype.decreaseIndent = function () { + this.indentAmt--; + }; + PrintContext.prototype.startLine = function () { + if(this.builder.length > 0) { + TypeScript.CompilerDiagnostics.Alert(this.builder); + } + var indentString = this.indentStrings[this.indentAmt]; + if(indentString === undefined) { + indentString = ""; + for(var i = 0; i < this.indentAmt; i++) { + indentString += this.indent1; + } + this.indentStrings[this.indentAmt] = indentString; + } + this.builder += indentString; + }; + PrintContext.prototype.write = function (s) { + this.builder += s; + }; + PrintContext.prototype.writeLine = function (s) { + this.builder += s; + this.outfile.WriteLine(this.builder); + this.builder = ""; + }; + return PrintContext; + })(); + TypeScript.PrintContext = PrintContext; + function prePrintAST(ast, parent, walker) { + var pc = walker.state; + ast.print(pc); + pc.increaseIndent(); + return ast; + } + TypeScript.prePrintAST = prePrintAST; + function postPrintAST(ast, parent, walker) { + var pc = walker.state; + pc.decreaseIndent(); + return ast; + } + TypeScript.postPrintAST = postPrintAST; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + TypeScript.LexEOF = (-1); + TypeScript.LexCodeNWL = 0x0A; + TypeScript.LexCodeRET = 0x0D; + TypeScript.LexCodeLS = 0x2028; + TypeScript.LexCodePS = 0x2029; + TypeScript.LexCodeTAB = 0x09; + TypeScript.LexCodeVTAB = 0x0B; + TypeScript.LexCode_e = 'e'.charCodeAt(0); + TypeScript.LexCode_E = 'E'.charCodeAt(0); + TypeScript.LexCode_x = 'x'.charCodeAt(0); + TypeScript.LexCode_X = 'X'.charCodeAt(0); + TypeScript.LexCode_a = 'a'.charCodeAt(0); + TypeScript.LexCode_A = 'A'.charCodeAt(0); + TypeScript.LexCode_f = 'f'.charCodeAt(0); + TypeScript.LexCode_F = 'F'.charCodeAt(0); + TypeScript.LexCode_g = 'g'.charCodeAt(0); + TypeScript.LexCode_m = 'm'.charCodeAt(0); + TypeScript.LexCode_i = 'i'.charCodeAt(0); + TypeScript.LexCode_u = 'u'.charCodeAt(0); + TypeScript.LexCode_0 = '0'.charCodeAt(0); + TypeScript.LexCode_9 = '9'.charCodeAt(0); + TypeScript.LexCode_8 = '8'.charCodeAt(0); + TypeScript.LexCode_7 = '7'.charCodeAt(0); + TypeScript.LexCodeBSL = '\\'.charCodeAt(0); + TypeScript.LexCodeSHP = '#'.charCodeAt(0); + TypeScript.LexCodeBNG = '!'.charCodeAt(0); + TypeScript.LexCodeQUO = '"'.charCodeAt(0); + TypeScript.LexCodeAPO = '\''.charCodeAt(0); + TypeScript.LexCodePCT = '%'.charCodeAt(0); + TypeScript.LexCodeAMP = '&'.charCodeAt(0); + TypeScript.LexCodeLPR = '('.charCodeAt(0); + TypeScript.LexCodeRPR = ')'.charCodeAt(0); + TypeScript.LexCodePLS = '+'.charCodeAt(0); + TypeScript.LexCodeMIN = '-'.charCodeAt(0); + TypeScript.LexCodeMUL = '*'.charCodeAt(0); + TypeScript.LexCodeSLH = '/'.charCodeAt(0); + TypeScript.LexCodeXOR = '^'.charCodeAt(0); + TypeScript.LexCodeCMA = ','.charCodeAt(0); + TypeScript.LexCodeDOT = '.'.charCodeAt(0); + TypeScript.LexCodeLT = '<'.charCodeAt(0); + TypeScript.LexCodeEQ = '='.charCodeAt(0); + TypeScript.LexCodeGT = '>'.charCodeAt(0); + TypeScript.LexCodeQUE = '?'.charCodeAt(0); + TypeScript.LexCodeLBR = '['.charCodeAt(0); + TypeScript.LexCodeRBR = ']'.charCodeAt(0); + TypeScript.LexCodeUSC = '_'.charCodeAt(0); + TypeScript.LexCodeLC = '{'.charCodeAt(0); + TypeScript.LexCodeRC = '}'.charCodeAt(0); + TypeScript.LexCodeBAR = '|'.charCodeAt(0); + TypeScript.LexCodeTIL = '~'.charCodeAt(0); + TypeScript.LexCodeCOL = ':'.charCodeAt(0); + TypeScript.LexCodeSMC = ';'.charCodeAt(0); + TypeScript.LexCodeUnderscore = '_'.charCodeAt(0); + TypeScript.LexCodeDollar = '$'.charCodeAt(0); + TypeScript.LexCodeSpace = 32; + TypeScript.LexCodeAtSign = '@'.charCodeAt(0); + TypeScript.LexCodeASCIIChars = 128; + TypeScript.LexKeywordTable = undefined; + var autoToken = new Array(TypeScript.LexCodeASCIIChars); + var lexIdStartTable = new Array(TypeScript.LexCodeASCIIChars); + var unicodeES3IdStart = [ + 170, + 170, + 181, + 181, + 186, + 186, + 192, + 214, + 216, + 246, + 248, + 543, + 546, + 563, + 592, + 685, + 688, + 696, + 699, + 705, + 720, + 721, + 736, + 740, + 750, + 750, + 890, + 890, + 902, + 902, + 904, + 906, + 908, + 908, + 910, + 929, + 931, + 974, + 976, + 983, + 986, + 1011, + 1024, + 1153, + 1164, + 1220, + 1223, + 1224, + 1227, + 1228, + 1232, + 1269, + 1272, + 1273, + 1329, + 1366, + 1369, + 1369, + 1377, + 1415, + 1488, + 1514, + 1520, + 1522, + 1569, + 1594, + 1600, + 1610, + 1649, + 1747, + 1749, + 1749, + 1765, + 1766, + 1786, + 1788, + 1808, + 1808, + 1810, + 1836, + 1920, + 1957, + 2309, + 2361, + 2365, + 2365, + 2384, + 2384, + 2392, + 2401, + 2437, + 2444, + 2447, + 2448, + 2451, + 2472, + 2474, + 2480, + 2482, + 2482, + 2486, + 2489, + 2524, + 2525, + 2527, + 2529, + 2544, + 2545, + 2565, + 2570, + 2575, + 2576, + 2579, + 2600, + 2602, + 2608, + 2610, + 2611, + 2613, + 2614, + 2616, + 2617, + 2649, + 2652, + 2654, + 2654, + 2674, + 2676, + 2693, + 2699, + 2701, + 2701, + 2703, + 2705, + 2707, + 2728, + 2730, + 2736, + 2738, + 2739, + 2741, + 2745, + 2749, + 2749, + 2768, + 2768, + 2784, + 2784, + 2821, + 2828, + 2831, + 2832, + 2835, + 2856, + 2858, + 2864, + 2866, + 2867, + 2870, + 2873, + 2877, + 2877, + 2908, + 2909, + 2911, + 2913, + 2949, + 2954, + 2958, + 2960, + 2962, + 2965, + 2969, + 2970, + 2972, + 2972, + 2974, + 2975, + 2979, + 2980, + 2984, + 2986, + 2990, + 2997, + 2999, + 3001, + 3077, + 3084, + 3086, + 3088, + 3090, + 3112, + 3114, + 3123, + 3125, + 3129, + 3168, + 3169, + 3205, + 3212, + 3214, + 3216, + 3218, + 3240, + 3242, + 3251, + 3253, + 3257, + 3294, + 3294, + 3296, + 3297, + 3333, + 3340, + 3342, + 3344, + 3346, + 3368, + 3370, + 3385, + 3424, + 3425, + 3461, + 3478, + 3482, + 3505, + 3507, + 3515, + 3517, + 3517, + 3520, + 3526, + 3585, + 3632, + 3634, + 3635, + 3648, + 3654, + 3713, + 3714, + 3716, + 3716, + 3719, + 3720, + 3722, + 3722, + 3725, + 3725, + 3732, + 3735, + 3737, + 3743, + 3745, + 3747, + 3749, + 3749, + 3751, + 3751, + 3754, + 3755, + 3757, + 3760, + 3762, + 3763, + 3773, + 3773, + 3776, + 3780, + 3782, + 3782, + 3804, + 3805, + 3840, + 3840, + 3904, + 3911, + 3913, + 3946, + 3976, + 3979, + 4096, + 4129, + 4131, + 4135, + 4137, + 4138, + 4176, + 4181, + 4256, + 4293, + 4304, + 4342, + 4352, + 4441, + 4447, + 4514, + 4520, + 4601, + 4608, + 4614, + 4616, + 4678, + 4680, + 4680, + 4682, + 4685, + 4688, + 4694, + 4696, + 4696, + 4698, + 4701, + 4704, + 4742, + 4744, + 4744, + 4746, + 4749, + 4752, + 4782, + 4784, + 4784, + 4786, + 4789, + 4792, + 4798, + 4800, + 4800, + 4802, + 4805, + 4808, + 4814, + 4816, + 4822, + 4824, + 4846, + 4848, + 4878, + 4880, + 4880, + 4882, + 4885, + 4888, + 4894, + 4896, + 4934, + 4936, + 4954, + 5024, + 5108, + 5121, + 5740, + 5743, + 5750, + 5761, + 5786, + 5792, + 5866, + 6016, + 6067, + 6176, + 6263, + 6272, + 6312, + 7680, + 7835, + 7840, + 7929, + 7936, + 7957, + 7960, + 7965, + 7968, + 8005, + 8008, + 8013, + 8016, + 8023, + 8025, + 8025, + 8027, + 8027, + 8029, + 8029, + 8031, + 8061, + 8064, + 8116, + 8118, + 8124, + 8126, + 8126, + 8130, + 8132, + 8134, + 8140, + 8144, + 8147, + 8150, + 8155, + 8160, + 8172, + 8178, + 8180, + 8182, + 8188, + 8319, + 8319, + 8450, + 8450, + 8455, + 8455, + 8458, + 8467, + 8469, + 8469, + 8473, + 8477, + 8484, + 8484, + 8486, + 8486, + 8488, + 8488, + 8490, + 8493, + 8495, + 8497, + 8499, + 8505, + 8544, + 8579, + 12293, + 12295, + 12321, + 12329, + 12337, + 12341, + 12344, + 12346, + 12353, + 12436, + 12445, + 12446, + 12449, + 12538, + 12540, + 12542, + 12549, + 12588, + 12593, + 12686, + 12704, + 12727, + 13312, + 19893, + 19968, + 40869, + 40960, + 42124, + 44032, + 55203, + 63744, + 64045, + 64256, + 64262, + 64275, + 64279, + 64285, + 64285, + 64287, + 64296, + 64298, + 64310, + 64312, + 64316, + 64318, + 64318, + 64320, + 64321, + 64323, + 64324, + 64326, + 64433, + 64467, + 64829, + 64848, + 64911, + 64914, + 64967, + 65008, + 65019, + 65136, + 65138, + 65140, + 65140, + 65142, + 65276, + 65313, + 65338, + 65345, + 65370, + 65382, + 65470, + 65474, + 65479, + 65482, + 65487, + 65490, + 65495, + 65498, + 65500, + + ]; + var unicodeES3IdCont = [ + 768, + 846, + 864, + 866, + 1155, + 1158, + 1425, + 1441, + 1443, + 1465, + 1467, + 1469, + 1471, + 1471, + 1473, + 1474, + 1476, + 1476, + 1611, + 1621, + 1632, + 1641, + 1648, + 1648, + 1750, + 1756, + 1759, + 1764, + 1767, + 1768, + 1770, + 1773, + 1776, + 1785, + 1809, + 1809, + 1840, + 1866, + 1958, + 1968, + 2305, + 2307, + 2364, + 2364, + 2366, + 2381, + 2385, + 2388, + 2402, + 2403, + 2406, + 2415, + 2433, + 2435, + 2492, + 2492, + 2494, + 2500, + 2503, + 2504, + 2507, + 2509, + 2519, + 2519, + 2530, + 2531, + 2534, + 2543, + 2562, + 2562, + 2620, + 2620, + 2622, + 2626, + 2631, + 2632, + 2635, + 2637, + 2662, + 2673, + 2689, + 2691, + 2748, + 2748, + 2750, + 2757, + 2759, + 2761, + 2763, + 2765, + 2790, + 2799, + 2817, + 2819, + 2876, + 2876, + 2878, + 2883, + 2887, + 2888, + 2891, + 2893, + 2902, + 2903, + 2918, + 2927, + 2946, + 2947, + 3006, + 3010, + 3014, + 3016, + 3018, + 3021, + 3031, + 3031, + 3047, + 3055, + 3073, + 3075, + 3134, + 3140, + 3142, + 3144, + 3146, + 3149, + 3157, + 3158, + 3174, + 3183, + 3202, + 3203, + 3262, + 3268, + 3270, + 3272, + 3274, + 3277, + 3285, + 3286, + 3302, + 3311, + 3330, + 3331, + 3390, + 3395, + 3398, + 3400, + 3402, + 3405, + 3415, + 3415, + 3430, + 3439, + 3458, + 3459, + 3530, + 3530, + 3535, + 3540, + 3542, + 3542, + 3544, + 3551, + 3570, + 3571, + 3633, + 3633, + 3636, + 3642, + 3655, + 3662, + 3664, + 3673, + 3761, + 3761, + 3764, + 3769, + 3771, + 3772, + 3784, + 3789, + 3792, + 3801, + 3864, + 3865, + 3872, + 3881, + 3893, + 3893, + 3895, + 3895, + 3897, + 3897, + 3902, + 3903, + 3953, + 3972, + 3974, + 3975, + 3984, + 3991, + 3993, + 4028, + 4038, + 4038, + 4140, + 4146, + 4150, + 4153, + 4160, + 4169, + 4182, + 4185, + 4969, + 4977, + 6068, + 6099, + 6112, + 6121, + 6160, + 6169, + 6313, + 6313, + 8255, + 8256, + 8400, + 8412, + 8417, + 8417, + 12330, + 12335, + 12441, + 12442, + 12539, + 12539, + 64286, + 64286, + 65056, + 65059, + 65075, + 65076, + 65101, + 65103, + 65296, + 65305, + 65343, + 65343, + 65381, + 65381, + + ]; + var unicodeES5IdStart = [ + 170, + 170, + 181, + 181, + 186, + 186, + 192, + 214, + 216, + 246, + 248, + 705, + 710, + 721, + 736, + 740, + 748, + 748, + 750, + 750, + 880, + 884, + 886, + 887, + 890, + 893, + 902, + 902, + 904, + 906, + 908, + 908, + 910, + 929, + 931, + 1013, + 1015, + 1153, + 1162, + 1319, + 1329, + 1366, + 1369, + 1369, + 1377, + 1415, + 1488, + 1514, + 1520, + 1522, + 1568, + 1610, + 1646, + 1647, + 1649, + 1747, + 1749, + 1749, + 1765, + 1766, + 1774, + 1775, + 1786, + 1788, + 1791, + 1791, + 1808, + 1808, + 1810, + 1839, + 1869, + 1957, + 1969, + 1969, + 1994, + 2026, + 2036, + 2037, + 2042, + 2042, + 2048, + 2069, + 2074, + 2074, + 2084, + 2084, + 2088, + 2088, + 2112, + 2136, + 2208, + 2208, + 2210, + 2220, + 2308, + 2361, + 2365, + 2365, + 2384, + 2384, + 2392, + 2401, + 2417, + 2423, + 2425, + 2431, + 2437, + 2444, + 2447, + 2448, + 2451, + 2472, + 2474, + 2480, + 2482, + 2482, + 2486, + 2489, + 2493, + 2493, + 2510, + 2510, + 2524, + 2525, + 2527, + 2529, + 2544, + 2545, + 2565, + 2570, + 2575, + 2576, + 2579, + 2600, + 2602, + 2608, + 2610, + 2611, + 2613, + 2614, + 2616, + 2617, + 2649, + 2652, + 2654, + 2654, + 2674, + 2676, + 2693, + 2701, + 2703, + 2705, + 2707, + 2728, + 2730, + 2736, + 2738, + 2739, + 2741, + 2745, + 2749, + 2749, + 2768, + 2768, + 2784, + 2785, + 2821, + 2828, + 2831, + 2832, + 2835, + 2856, + 2858, + 2864, + 2866, + 2867, + 2869, + 2873, + 2877, + 2877, + 2908, + 2909, + 2911, + 2913, + 2929, + 2929, + 2947, + 2947, + 2949, + 2954, + 2958, + 2960, + 2962, + 2965, + 2969, + 2970, + 2972, + 2972, + 2974, + 2975, + 2979, + 2980, + 2984, + 2986, + 2990, + 3001, + 3024, + 3024, + 3077, + 3084, + 3086, + 3088, + 3090, + 3112, + 3114, + 3123, + 3125, + 3129, + 3133, + 3133, + 3160, + 3161, + 3168, + 3169, + 3205, + 3212, + 3214, + 3216, + 3218, + 3240, + 3242, + 3251, + 3253, + 3257, + 3261, + 3261, + 3294, + 3294, + 3296, + 3297, + 3313, + 3314, + 3333, + 3340, + 3342, + 3344, + 3346, + 3386, + 3389, + 3389, + 3406, + 3406, + 3424, + 3425, + 3450, + 3455, + 3461, + 3478, + 3482, + 3505, + 3507, + 3515, + 3517, + 3517, + 3520, + 3526, + 3585, + 3632, + 3634, + 3635, + 3648, + 3654, + 3713, + 3714, + 3716, + 3716, + 3719, + 3720, + 3722, + 3722, + 3725, + 3725, + 3732, + 3735, + 3737, + 3743, + 3745, + 3747, + 3749, + 3749, + 3751, + 3751, + 3754, + 3755, + 3757, + 3760, + 3762, + 3763, + 3773, + 3773, + 3776, + 3780, + 3782, + 3782, + 3804, + 3807, + 3840, + 3840, + 3904, + 3911, + 3913, + 3948, + 3976, + 3980, + 4096, + 4138, + 4159, + 4159, + 4176, + 4181, + 4186, + 4189, + 4193, + 4193, + 4197, + 4198, + 4206, + 4208, + 4213, + 4225, + 4238, + 4238, + 4256, + 4293, + 4295, + 4295, + 4301, + 4301, + 4304, + 4346, + 4348, + 4680, + 4682, + 4685, + 4688, + 4694, + 4696, + 4696, + 4698, + 4701, + 4704, + 4744, + 4746, + 4749, + 4752, + 4784, + 4786, + 4789, + 4792, + 4798, + 4800, + 4800, + 4802, + 4805, + 4808, + 4822, + 4824, + 4880, + 4882, + 4885, + 4888, + 4954, + 4992, + 5007, + 5024, + 5108, + 5121, + 5740, + 5743, + 5759, + 5761, + 5786, + 5792, + 5866, + 5870, + 5872, + 5888, + 5900, + 5902, + 5905, + 5920, + 5937, + 5952, + 5969, + 5984, + 5996, + 5998, + 6000, + 6016, + 6067, + 6103, + 6103, + 6108, + 6108, + 6176, + 6263, + 6272, + 6312, + 6314, + 6314, + 6320, + 6389, + 6400, + 6428, + 6480, + 6509, + 6512, + 6516, + 6528, + 6571, + 6593, + 6599, + 6656, + 6678, + 6688, + 6740, + 6823, + 6823, + 6917, + 6963, + 6981, + 6987, + 7043, + 7072, + 7086, + 7087, + 7098, + 7141, + 7168, + 7203, + 7245, + 7247, + 7258, + 7293, + 7401, + 7404, + 7406, + 7409, + 7413, + 7414, + 7424, + 7615, + 7680, + 7957, + 7960, + 7965, + 7968, + 8005, + 8008, + 8013, + 8016, + 8023, + 8025, + 8025, + 8027, + 8027, + 8029, + 8029, + 8031, + 8061, + 8064, + 8116, + 8118, + 8124, + 8126, + 8126, + 8130, + 8132, + 8134, + 8140, + 8144, + 8147, + 8150, + 8155, + 8160, + 8172, + 8178, + 8180, + 8182, + 8188, + 8305, + 8305, + 8319, + 8319, + 8336, + 8348, + 8450, + 8450, + 8455, + 8455, + 8458, + 8467, + 8469, + 8469, + 8473, + 8477, + 8484, + 8484, + 8486, + 8486, + 8488, + 8488, + 8490, + 8493, + 8495, + 8505, + 8508, + 8511, + 8517, + 8521, + 8526, + 8526, + 8544, + 8584, + 11264, + 11310, + 11312, + 11358, + 11360, + 11492, + 11499, + 11502, + 11506, + 11507, + 11520, + 11557, + 11559, + 11559, + 11565, + 11565, + 11568, + 11623, + 11631, + 11631, + 11648, + 11670, + 11680, + 11686, + 11688, + 11694, + 11696, + 11702, + 11704, + 11710, + 11712, + 11718, + 11720, + 11726, + 11728, + 11734, + 11736, + 11742, + 11823, + 11823, + 12293, + 12295, + 12321, + 12329, + 12337, + 12341, + 12344, + 12348, + 12353, + 12438, + 12445, + 12447, + 12449, + 12538, + 12540, + 12543, + 12549, + 12589, + 12593, + 12686, + 12704, + 12730, + 12784, + 12799, + 13312, + 19893, + 19968, + 40908, + 40960, + 42124, + 42192, + 42237, + 42240, + 42508, + 42512, + 42527, + 42538, + 42539, + 42560, + 42606, + 42623, + 42647, + 42656, + 42735, + 42775, + 42783, + 42786, + 42888, + 42891, + 42894, + 42896, + 42899, + 42912, + 42922, + 43000, + 43009, + 43011, + 43013, + 43015, + 43018, + 43020, + 43042, + 43072, + 43123, + 43138, + 43187, + 43250, + 43255, + 43259, + 43259, + 43274, + 43301, + 43312, + 43334, + 43360, + 43388, + 43396, + 43442, + 43471, + 43471, + 43520, + 43560, + 43584, + 43586, + 43588, + 43595, + 43616, + 43638, + 43642, + 43642, + 43648, + 43695, + 43697, + 43697, + 43701, + 43702, + 43705, + 43709, + 43712, + 43712, + 43714, + 43714, + 43739, + 43741, + 43744, + 43754, + 43762, + 43764, + 43777, + 43782, + 43785, + 43790, + 43793, + 43798, + 43808, + 43814, + 43816, + 43822, + 43968, + 44002, + 44032, + 55203, + 55216, + 55238, + 55243, + 55291, + 63744, + 64109, + 64112, + 64217, + 64256, + 64262, + 64275, + 64279, + 64285, + 64285, + 64287, + 64296, + 64298, + 64310, + 64312, + 64316, + 64318, + 64318, + 64320, + 64321, + 64323, + 64324, + 64326, + 64433, + 64467, + 64829, + 64848, + 64911, + 64914, + 64967, + 65008, + 65019, + 65136, + 65140, + 65142, + 65276, + 65313, + 65338, + 65345, + 65370, + 65382, + 65470, + 65474, + 65479, + 65482, + 65487, + 65490, + 65495, + 65498, + 65500, + + ]; + var unicodeES5IdCont = [ + 768, + 879, + 1155, + 1159, + 1425, + 1469, + 1471, + 1471, + 1473, + 1474, + 1476, + 1477, + 1479, + 1479, + 1552, + 1562, + 1611, + 1641, + 1648, + 1648, + 1750, + 1756, + 1759, + 1764, + 1767, + 1768, + 1770, + 1773, + 1776, + 1785, + 1809, + 1809, + 1840, + 1866, + 1958, + 1968, + 1984, + 1993, + 2027, + 2035, + 2070, + 2073, + 2075, + 2083, + 2085, + 2087, + 2089, + 2093, + 2137, + 2139, + 2276, + 2302, + 2304, + 2307, + 2362, + 2364, + 2366, + 2383, + 2385, + 2391, + 2402, + 2403, + 2406, + 2415, + 2433, + 2435, + 2492, + 2492, + 2494, + 2500, + 2503, + 2504, + 2507, + 2509, + 2519, + 2519, + 2530, + 2531, + 2534, + 2543, + 2561, + 2563, + 2620, + 2620, + 2622, + 2626, + 2631, + 2632, + 2635, + 2637, + 2641, + 2641, + 2662, + 2673, + 2677, + 2677, + 2689, + 2691, + 2748, + 2748, + 2750, + 2757, + 2759, + 2761, + 2763, + 2765, + 2786, + 2787, + 2790, + 2799, + 2817, + 2819, + 2876, + 2876, + 2878, + 2884, + 2887, + 2888, + 2891, + 2893, + 2902, + 2903, + 2914, + 2915, + 2918, + 2927, + 2946, + 2946, + 3006, + 3010, + 3014, + 3016, + 3018, + 3021, + 3031, + 3031, + 3046, + 3055, + 3073, + 3075, + 3134, + 3140, + 3142, + 3144, + 3146, + 3149, + 3157, + 3158, + 3170, + 3171, + 3174, + 3183, + 3202, + 3203, + 3260, + 3260, + 3262, + 3268, + 3270, + 3272, + 3274, + 3277, + 3285, + 3286, + 3298, + 3299, + 3302, + 3311, + 3330, + 3331, + 3390, + 3396, + 3398, + 3400, + 3402, + 3405, + 3415, + 3415, + 3426, + 3427, + 3430, + 3439, + 3458, + 3459, + 3530, + 3530, + 3535, + 3540, + 3542, + 3542, + 3544, + 3551, + 3570, + 3571, + 3633, + 3633, + 3636, + 3642, + 3655, + 3662, + 3664, + 3673, + 3761, + 3761, + 3764, + 3769, + 3771, + 3772, + 3784, + 3789, + 3792, + 3801, + 3864, + 3865, + 3872, + 3881, + 3893, + 3893, + 3895, + 3895, + 3897, + 3897, + 3902, + 3903, + 3953, + 3972, + 3974, + 3975, + 3981, + 3991, + 3993, + 4028, + 4038, + 4038, + 4139, + 4158, + 4160, + 4169, + 4182, + 4185, + 4190, + 4192, + 4194, + 4196, + 4199, + 4205, + 4209, + 4212, + 4226, + 4237, + 4239, + 4253, + 4957, + 4959, + 5906, + 5908, + 5938, + 5940, + 5970, + 5971, + 6002, + 6003, + 6068, + 6099, + 6109, + 6109, + 6112, + 6121, + 6155, + 6157, + 6160, + 6169, + 6313, + 6313, + 6432, + 6443, + 6448, + 6459, + 6470, + 6479, + 6576, + 6592, + 6600, + 6601, + 6608, + 6617, + 6679, + 6683, + 6741, + 6750, + 6752, + 6780, + 6783, + 6793, + 6800, + 6809, + 6912, + 6916, + 6964, + 6980, + 6992, + 7001, + 7019, + 7027, + 7040, + 7042, + 7073, + 7085, + 7088, + 7097, + 7142, + 7155, + 7204, + 7223, + 7232, + 7241, + 7248, + 7257, + 7376, + 7378, + 7380, + 7400, + 7405, + 7405, + 7410, + 7412, + 7616, + 7654, + 7676, + 7679, + 8204, + 8205, + 8255, + 8256, + 8276, + 8276, + 8400, + 8412, + 8417, + 8417, + 8421, + 8432, + 11503, + 11505, + 11647, + 11647, + 11744, + 11775, + 12330, + 12335, + 12441, + 12442, + 42528, + 42537, + 42607, + 42607, + 42612, + 42621, + 42655, + 42655, + 42736, + 42737, + 43010, + 43010, + 43014, + 43014, + 43019, + 43019, + 43043, + 43047, + 43136, + 43137, + 43188, + 43204, + 43216, + 43225, + 43232, + 43249, + 43264, + 43273, + 43302, + 43309, + 43335, + 43347, + 43392, + 43395, + 43443, + 43456, + 43472, + 43481, + 43561, + 43574, + 43587, + 43587, + 43596, + 43597, + 43600, + 43609, + 43643, + 43643, + 43696, + 43696, + 43698, + 43700, + 43703, + 43704, + 43710, + 43711, + 43713, + 43713, + 43755, + 43759, + 43765, + 43766, + 44003, + 44010, + 44012, + 44013, + 44016, + 44025, + 64286, + 64286, + 65024, + 65039, + 65056, + 65062, + 65075, + 65076, + 65101, + 65103, + 65296, + 65305, + 65343, + 65343, + + ]; + function LexLookUpUnicodeMap(code, map) { + var lo = 0; + var hi = map.length; + var mid; + while(lo + 1 < hi) { + mid = lo + (hi - lo) / 2; + mid -= mid % 2; + if(map[mid] <= code && code <= map[mid + 1]) { + return true; + } + if(code < map[mid]) { + hi = mid; + } else { + lo = mid + 2; + } + } + return false; + } + TypeScript.LexLookUpUnicodeMap = LexLookUpUnicodeMap; + function LexIsUnicodeDigit(code) { + if(TypeScript.codeGenTarget == TypeScript.CodeGenTarget.ES3) { + return LexLookUpUnicodeMap(code, unicodeES3IdCont); + } else { + return LexLookUpUnicodeMap(code, unicodeES5IdCont); + } + } + TypeScript.LexIsUnicodeDigit = LexIsUnicodeDigit; + function LexIsUnicodeIdStart(code) { + if(TypeScript.codeGenTarget == TypeScript.CodeGenTarget.ES3) { + return LexLookUpUnicodeMap(code, unicodeES3IdStart); + } else { + return LexLookUpUnicodeMap(code, unicodeES5IdStart); + } + } + TypeScript.LexIsUnicodeIdStart = LexIsUnicodeIdStart; + function LexInitialize() { + TypeScript.initializeStaticTokens(); + autoToken[TypeScript.LexCodeLPR] = TypeScript.staticTokens[TypeScript.TokenID.OpenParen]; + autoToken[TypeScript.LexCodeRPR] = TypeScript.staticTokens[TypeScript.TokenID.CloseParen]; + autoToken[TypeScript.LexCodeCMA] = TypeScript.staticTokens[TypeScript.TokenID.Comma]; + autoToken[TypeScript.LexCodeSMC] = TypeScript.staticTokens[TypeScript.TokenID.Semicolon]; + autoToken[TypeScript.LexCodeLBR] = TypeScript.staticTokens[TypeScript.TokenID.OpenBracket]; + autoToken[TypeScript.LexCodeRBR] = TypeScript.staticTokens[TypeScript.TokenID.CloseBracket]; + autoToken[TypeScript.LexCodeTIL] = TypeScript.staticTokens[TypeScript.TokenID.Tilde]; + autoToken[TypeScript.LexCodeQUE] = TypeScript.staticTokens[TypeScript.TokenID.Question]; + autoToken[TypeScript.LexCodeLC] = TypeScript.staticTokens[TypeScript.TokenID.OpenBrace]; + autoToken[TypeScript.LexCodeRC] = TypeScript.staticTokens[TypeScript.TokenID.CloseBrace]; + autoToken[TypeScript.LexCodeCOL] = TypeScript.staticTokens[TypeScript.TokenID.Colon]; + TypeScript.LexKeywordTable = new TypeScript.StringHashTable(); + for(var i in (TypeScript.TokenID)._map) { + if((i) <= TypeScript.TokenID.LimKeyword) { + TypeScript.LexKeywordTable.add((TypeScript.TokenID)._map[i].toLowerCase(), i); + } + } + for(var j = 0; j < TypeScript.LexCodeASCIIChars; j++) { + if(LexIsIdentifierStartChar(j)) { + lexIdStartTable[j] = true; + } else { + lexIdStartTable[j] = false; + } + } + } + TypeScript.LexInitialize = LexInitialize; + function LexAdjustIndent(code, indentAmt) { + if((code == TypeScript.LexCodeLBR) || (code == TypeScript.LexCodeLC) || (code == TypeScript.LexCodeLPR)) { + return indentAmt + 1; + } else if((code == TypeScript.LexCodeRBR) || (code == TypeScript.LexCodeRC) || (code == TypeScript.LexCodeRPR)) { + return indentAmt - 1; + } else { + return indentAmt; + } + } + TypeScript.LexAdjustIndent = LexAdjustIndent; + function LexIsIdentifierStartChar(code) { + return (((code >= 97) && (code <= 122)) || ((code >= 65) && (code <= 90)) || (code == TypeScript.LexCodeDollar) || (code == TypeScript.LexCodeUnderscore)); + } + TypeScript.LexIsIdentifierStartChar = LexIsIdentifierStartChar; + function LexIsDigit(code) { + return ((code >= 48) && (code <= 57)); + } + TypeScript.LexIsDigit = LexIsDigit; + function LexIsIdentifierChar(code) { + return lexIdStartTable[code] || LexIsDigit(code); + } + TypeScript.LexIsIdentifierChar = LexIsIdentifierChar; + function LexMatchingOpen(code) { + if(code == TypeScript.LexCodeRBR) { + return TypeScript.LexCodeLBR; + } else if(code == TypeScript.LexCodeRC) { + return TypeScript.LexCodeLC; + } else if(code == TypeScript.LexCodeRPR) { + return TypeScript.LexCodeLPR; + } else { + return 0; + } + } + TypeScript.LexMatchingOpen = LexMatchingOpen; + (function (NumberScanState) { + NumberScanState._map = []; + NumberScanState._map[0] = "Start"; + NumberScanState.Start = 0; + NumberScanState._map[1] = "InFraction"; + NumberScanState.InFraction = 1; + NumberScanState._map[2] = "InEmptyFraction"; + NumberScanState.InEmptyFraction = 2; + NumberScanState._map[3] = "InExponent"; + NumberScanState.InExponent = 3; + })(TypeScript.NumberScanState || (TypeScript.NumberScanState = {})); + var NumberScanState = TypeScript.NumberScanState; + (function (LexState) { + LexState._map = []; + LexState._map[0] = "Start"; + LexState.Start = 0; + LexState._map[1] = "InMultilineComment"; + LexState.InMultilineComment = 1; + LexState._map[2] = "InMultilineSingleQuoteString"; + LexState.InMultilineSingleQuoteString = 2; + LexState._map[3] = "InMultilineDoubleQuoteString"; + LexState.InMultilineDoubleQuoteString = 3; + })(TypeScript.LexState || (TypeScript.LexState = {})); + var LexState = TypeScript.LexState; + (function (LexMode) { + LexMode._map = []; + LexMode._map[0] = "Line"; + LexMode.Line = 0; + LexMode._map[1] = "File"; + LexMode.File = 1; + })(TypeScript.LexMode || (TypeScript.LexMode = {})); + var LexMode = TypeScript.LexMode; + (function (CommentStyle) { + CommentStyle._map = []; + CommentStyle._map[0] = "Line"; + CommentStyle.Line = 0; + CommentStyle._map[1] = "Block"; + CommentStyle.Block = 1; + })(TypeScript.CommentStyle || (TypeScript.CommentStyle = {})); + var CommentStyle = TypeScript.CommentStyle; + var StringSourceText = (function () { + function StringSourceText(text) { + this.text = text; + } + StringSourceText.prototype.getText = function (start, end) { + return this.text.substring(start, end); + }; + StringSourceText.prototype.getLength = function () { + return this.text.length; + }; + return StringSourceText; + })(); + TypeScript.StringSourceText = StringSourceText; + var SourceTextSegment = (function () { + function SourceTextSegment(segmentStart, segmentEnd, segment) { + this.segmentStart = segmentStart; + this.segmentEnd = segmentEnd; + this.segment = segment; + } + SourceTextSegment.prototype.charCodeAt = function (index) { + return this.segment.charCodeAt(index - this.segmentStart); + }; + SourceTextSegment.prototype.substring = function (start, end) { + return this.segment.substring(start - this.segmentStart, end - this.segmentStart); + }; + return SourceTextSegment; + })(); + TypeScript.SourceTextSegment = SourceTextSegment; + var AggerateSourceTextSegment = (function () { + function AggerateSourceTextSegment(seg1, seg2) { + this.seg1 = seg1; + this.seg2 = seg2; + } + AggerateSourceTextSegment.prototype.charCodeAt = function (index) { + if(this.seg1.segmentStart <= index && index < this.seg1.segmentEnd) { + return this.seg1.segment.charCodeAt(index - this.seg1.segmentStart); + } + return this.seg2.segment.charCodeAt(index - this.seg2.segmentStart); + }; + AggerateSourceTextSegment.prototype.substring = function (start, end) { + if(this.seg1.segmentStart <= start && end <= this.seg1.segmentEnd) { + return this.seg1.segment.substring(start - this.seg1.segmentStart, end - this.seg1.segmentStart); + } + return this.seg2.segment.substring(start - this.seg2.segmentStart) + this.seg1.segment.substring(0, end - this.seg1.segmentStart); + }; + return AggerateSourceTextSegment; + })(); + TypeScript.AggerateSourceTextSegment = AggerateSourceTextSegment; + var ScannerTextStream = (function () { + function ScannerTextStream(sourceText) { + this.sourceText = sourceText; + this.agg = new AggerateSourceTextSegment(ScannerTextStream.emptySegment, ScannerTextStream.emptySegment); + this.len = this.sourceText.getLength(); + } + ScannerTextStream.emptySegment = new SourceTextSegment(0, 0, ""); + ScannerTextStream.prototype.max = function (a, b) { + return a >= b ? a : b; + }; + ScannerTextStream.prototype.min = function (a, b) { + return a <= b ? a : b; + }; + ScannerTextStream.prototype.fetchSegment = function (start, end) { + if(this.agg.seg1.segmentStart <= start && end <= this.agg.seg1.segmentEnd) { + return this.agg.seg1; + } + if(this.agg.seg2.segmentStart <= start && end <= this.agg.seg1.segmentEnd) { + return this.agg; + } + var prev = this.agg.seg1; + var s = prev.segmentEnd; + var e = TypeScript.max(s + 512, end); + e = TypeScript.min(e, this.len); + var src = this.sourceText.getText(s, e); + var newSeg = new SourceTextSegment(s, e, src); + this.agg.seg2 = prev; + this.agg.seg1 = newSeg; + return this.agg; + }; + ScannerTextStream.prototype.charCodeAt = function (index) { + return this.fetchSegment(index, index + 1).charCodeAt(index); + }; + ScannerTextStream.prototype.substring = function (start, end) { + return this.fetchSegment(start, end).substring(start, end); + }; + return ScannerTextStream; + })(); + TypeScript.ScannerTextStream = ScannerTextStream; + var SavedTokens = (function () { + function SavedTokens() { + this.prevToken = null; + this.curSavedToken = null; + this.prevSavedToken = null; + this.prevToken = null; + this.currentToken = 0; + this.tokens = new Array(); + this.seenUnicodeChar = false; + this.seenUnicodeCharInComment = false; + this.prevLine = 1; + this.line = 1; + this.col = 0; + this.lexState = LexState.Start; + this.commentStack = new Array(); + this.lineMap = []; + } + SavedTokens.prototype.previousToken = function () { + return this.prevToken; + }; + SavedTokens.prototype.addToken = function (tok, scanner) { + this.tokens[this.currentToken++] = new TypeScript.SavedToken(tok, scanner.startPos, scanner.pos); + }; + SavedTokens.prototype.scan = function () { + this.startLine = this.line; + this.startPos = this.col; + if(this.currentTokenIndex == this.currentTokens.length) { + if(this.line < this.lineMap.length) { + this.line++; + this.col = 0; + this.currentTokenIndex = 0; + this.currentTokens = this.tokensByLine[this.line]; + } else { + return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; + } + } + if(this.currentTokenIndex < this.currentTokens.length) { + this.prevToken = this.curSavedToken.tok; + this.prevSavedToken = this.curSavedToken; + this.curSavedToken = this.currentTokens[this.currentTokenIndex++]; + var curToken = this.curSavedToken.tok; + this.pos = this.curSavedToken.limChar; + this.col += (this.curSavedToken.limChar - this.curSavedToken.minChar); + this.startPos = this.curSavedToken.minChar; + this.prevLine = this.line; + return curToken; + } else { + return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; + } + }; + SavedTokens.prototype.lastTokenLimChar = function () { + if(this.prevSavedToken !== null) { + return this.prevSavedToken.limChar; + } else { + return 0; + } + }; + SavedTokens.prototype.lastTokenHadNewline = function () { + return this.prevLine != this.startLine; + }; + SavedTokens.prototype.getComments = function () { + var stack = this.commentStack; + this.commentStack = []; + return stack; + }; + SavedTokens.prototype.getCommentsForLine = function (line) { + var comments = null; + while((this.commentStack.length > 0) && (this.commentStack[0].line == line)) { + if(comments == null) { + comments = [ + this.commentStack.shift() + ]; + } else { + comments = comments.concat([ + this.commentStack.shift() + ]); + } + } + return comments; + }; + SavedTokens.prototype.resetComments = function () { + this.commentStack = []; + }; + SavedTokens.prototype.setSourceText = function (newSrc, textMode) { + }; + SavedTokens.prototype.setErrorHandler = function (reportError) { + }; + SavedTokens.prototype.getLookAheadToken = function () { + throw new Error("Invalid operation."); + }; + return SavedTokens; + })(); + TypeScript.SavedTokens = SavedTokens; + var Scanner = (function () { + function Scanner() { + this.prevLine = 1; + this.line = 1; + this.col = 0; + this.pos = 0; + this.startPos = 0; + this.len = 0; + this.lineMap = []; + this.ch = TypeScript.LexEOF; + this.lexState = LexState.Start; + this.mode = LexMode.File; + this.scanComments = true; + this.interveningWhitespace = false; + this.interveningWhitespacePos = 0; + this.leftCurlyCount = 0; + this.rightCurlyCount = 0; + this.commentStack = new Array(); + this.saveScan = null; + this.seenUnicodeChar = false; + this.seenUnicodeCharInComment = false; + this.prevTok = TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; + this.startCol = this.col; + this.startLine = this.line; + this.lineMap[1] = 0; + if(!TypeScript.LexKeywordTable) { + LexInitialize(); + } + } + Scanner.prototype.previousToken = function () { + return this.prevTok; + }; + Scanner.prototype.setSourceText = function (newSrc, textMode) { + this.mode = textMode; + this.scanComments = (this.mode === LexMode.Line); + this.pos = 0; + this.interveningWhitespacePos = 0; + this.startPos = 0; + this.line = 1; + this.col = 0; + this.startCol = this.col; + this.startLine = this.line; + this.len = 0; + this.src = newSrc.getText(0, newSrc.getLength()); + this.len = this.src.length; + this.lineMap = []; + this.lineMap[1] = 0; + this.commentStack = []; + this.leftCurlyCount = 0; + this.rightCurlyCount = 0; + this.seenUnicodeChar = false; + this.seenUnicodeCharInComment = false; + }; + Scanner.prototype.setErrorHandler = function (reportError) { + this.reportError = reportError; + }; + Scanner.prototype.setText = function (newSrc, textMode) { + this.setSourceText(new StringSourceText(newSrc), textMode); + }; + Scanner.prototype.setScanComments = function (value) { + this.scanComments = value; + }; + Scanner.prototype.tokenStart = function () { + this.startPos = this.pos; + this.startLine = this.line; + this.startCol = this.col; + this.interveningWhitespace = false; + }; + Scanner.prototype.peekChar = function () { + if(this.pos < this.len) { + return this.src.charCodeAt(this.pos); + } else { + return TypeScript.LexEOF; + } + }; + Scanner.prototype.peekCharAt = function (index) { + if(index < this.len) { + return this.src.charCodeAt(index); + } else { + return TypeScript.LexEOF; + } + }; + Scanner.prototype.IsHexDigit = function (c) { + return ((c >= TypeScript.LexCode_0) && (c <= TypeScript.LexCode_9)) || ((c >= TypeScript.LexCode_A) && (c <= TypeScript.LexCode_F)) || ((c >= TypeScript.LexCode_a) && (c <= TypeScript.LexCode_f)); + }; + Scanner.prototype.IsOctalDigit = function (c) { + return ((c >= TypeScript.LexCode_0) && (c <= TypeScript.LexCode_7)) || ((c >= TypeScript.LexCode_a) && (c <= TypeScript.LexCode_f)); + }; + Scanner.prototype.scanHexDigits = function () { + var atLeastOneDigit = false; + for(; ; ) { + if(this.IsHexDigit(this.ch)) { + this.nextChar(); + atLeastOneDigit = true; + } else { + if(atLeastOneDigit) { + var text = this.src.substring(this.startPos, this.pos); + return new TypeScript.NumberLiteralToken(parseInt(text), text); + } else { + return null; + } + } + } + }; + Scanner.prototype.scanOctalDigits = function () { + var atLeastOneDigit = false; + for(; ; ) { + if(this.IsOctalDigit(this.ch)) { + this.nextChar(); + atLeastOneDigit = true; + } else { + if(atLeastOneDigit) { + var text = this.src.substring(this.startPos, this.pos); + return new TypeScript.NumberLiteralToken(parseInt(text), text); + } else { + return null; + } + } + } + }; + Scanner.prototype.scanDecimalNumber = function (state) { + var atLeastOneDigit = false; + var svPos = this.pos; + var svCol = this.col; + for(; ; ) { + if(LexIsDigit(this.ch)) { + atLeastOneDigit = true; + if(this.ch != TypeScript.LexCode_0 && state == NumberScanState.InEmptyFraction) { + state = NumberScanState.InFraction; + } + this.nextChar(); + } else if(this.ch == TypeScript.LexCodeDOT) { + if(state == NumberScanState.Start) { + this.nextChar(); + state = NumberScanState.InEmptyFraction; + } else { + if(atLeastOneDigit) { + var text = this.src.substring(this.startPos, this.pos); + return new TypeScript.NumberLiteralToken(parseFloat(text), text); + } else { + this.pos = svPos; + this.col = svCol; + return null; + } + } + } else if((this.ch == TypeScript.LexCode_e) || (this.ch == TypeScript.LexCode_E)) { + if(state == NumberScanState.Start) { + if(atLeastOneDigit) { + atLeastOneDigit = false; + this.nextChar(); + state = NumberScanState.InExponent; + } else { + this.pos = svPos; + this.col = svCol; + return null; + } + } else if(state == NumberScanState.InFraction || state == NumberScanState.InEmptyFraction) { + this.nextChar(); + state = NumberScanState.InExponent; + atLeastOneDigit = false; + } else { + if(atLeastOneDigit) { + var text = this.src.substring(this.startPos, this.pos); + return new TypeScript.NumberLiteralToken(parseFloat(text), text); + } else { + this.pos = svPos; + this.col = svCol; + return null; + } + } + } else if((this.ch == TypeScript.LexCodePLS) || (this.ch == TypeScript.LexCodeMIN)) { + if(state == NumberScanState.InExponent) { + if(!atLeastOneDigit) { + this.nextChar(); + } else { + this.pos = svPos; + this.col = svCol; + return null; + } + } else if(state == NumberScanState.InEmptyFraction || state == NumberScanState.InFraction) { + var text = this.src.substring(this.startPos, this.pos); + return new TypeScript.NumberLiteralToken(parseFloat(text), text); + } else { + if(!atLeastOneDigit) { + this.pos = svPos; + this.col = svCol; + return null; + } else { + var text = this.src.substring(this.startPos, this.pos); + return new TypeScript.NumberLiteralToken(parseFloat(text), text); + } + } + } else { + if(!atLeastOneDigit) { + this.pos = svPos; + this.col = svCol; + return null; + } else { + var text = this.src.substring(this.startPos, this.pos); + return new TypeScript.NumberLiteralToken(parseFloat(text), text); + } + } + } + }; + Scanner.prototype.scanNumber = function () { + if(this.peekChar() == TypeScript.LexCode_0) { + switch(this.peekCharAt(this.pos + 1)) { + case TypeScript.LexCode_x: + case TypeScript.LexCode_X: + this.advanceChar(2); + return this.scanHexDigits(); + case TypeScript.LexCode_8: + case TypeScript.LexCode_9: + case TypeScript.LexCodeDOT: + return this.scanDecimalNumber(NumberScanState.Start); + default: + return this.scanOctalDigits(); + } + } else { + return this.scanDecimalNumber(NumberScanState.Start); + } + }; + Scanner.prototype.scanFraction = function () { + return this.scanDecimalNumber(NumberScanState.InFraction); + }; + Scanner.prototype.newLine = function () { + this.col = 0; + if(this.mode == LexMode.File) { + this.line++; + this.lineMap[this.line] = this.pos + 1; + } + }; + Scanner.prototype.finishMultilineComment = function () { + var ch2; + this.lexState = LexState.InMultilineComment; + while(this.pos < this.len) { + if(this.ch == TypeScript.LexCodeMUL) { + ch2 = this.peekCharAt(this.pos + 1); + if(ch2 == TypeScript.LexCodeSLH) { + this.advanceChar(2); + if(this.mode == LexMode.File) { + this.tokenStart(); + } + this.lexState = LexState.Start; + return true; + } + } else if(this.ch == TypeScript.LexCodeNWL) { + this.newLine(); + if(this.mode == LexMode.Line) { + this.nextChar(); + return false; + } + } else if(this.ch >= TypeScript.LexCodeASCIIChars) { + this.seenUnicodeCharInComment = true; + } + this.nextChar(); + } + return false; + }; + Scanner.prototype.pushComment = function (comment) { + this.commentStack.push(comment); + }; + Scanner.prototype.getComments = function () { + var stack = this.commentStack; + this.commentStack = []; + return stack; + }; + Scanner.prototype.getCommentsForLine = function (line) { + var comments = null; + while((this.commentStack.length > 0) && (this.commentStack[0].line == line)) { + if(comments == null) { + comments = [ + this.commentStack.shift() + ]; + } else { + comments = comments.concat([ + this.commentStack.shift() + ]); + } + } + return comments; + }; + Scanner.prototype.resetComments = function () { + this.commentStack = []; + }; + Scanner.prototype.endsLine = function (c) { + return (c == TypeScript.LexCodeNWL) || (c == TypeScript.LexCodeRET) || (c == TypeScript.LexCodeLS) || (c == TypeScript.LexCodePS); + }; + Scanner.prototype.finishSinglelineComment = function () { + while(this.pos < this.len) { + if(this.endsLine(this.ch)) { + break; + } + if(this.ch >= TypeScript.LexCodeASCIIChars) { + this.seenUnicodeCharInComment = true; + } + this.nextChar(); + } + if(this.mode == LexMode.File) { + this.tokenStart(); + } + }; + Scanner.prototype.findClosingSLH = function () { + var index = this.pos; + var ch2 = this.src.charCodeAt(index); + var prevCh = 0; + var liveEsc = false; + while(!this.endsLine(ch2) && (index < this.len)) { + if((ch2 == TypeScript.LexCodeSLH) && (!liveEsc)) { + return index; + } + prevCh = ch2; + index++; + if(liveEsc) { + liveEsc = false; + } else { + liveEsc = (prevCh == TypeScript.LexCodeBSL); + } + ch2 = this.src.charCodeAt(index); + } + return -1; + }; + Scanner.prototype.speculateRegex = function () { + if(TypeScript.noRegexTable[this.prevTok.tokenId] != undefined) { + return null; + } + var svPos = this.pos; + var svCol = this.col; + var index = this.findClosingSLH(); + if(index > 0) { + var pattern = this.src.substring(svPos, index); + var flags = ""; + this.pos = index + 1; + this.ch = this.peekChar(); + var flagsStart = this.pos; + while((this.ch == TypeScript.LexCode_i) || (this.ch == TypeScript.LexCode_g) || (this.ch == TypeScript.LexCode_m)) { + this.nextChar(); + } + if((this.pos - flagsStart) > 3) { + return null; + } else { + flags = this.src.substring(flagsStart, this.pos); + } + var regex = undefined; + try { + regex = new RegExp(pattern, flags); + } catch (regexException) { + } + if(regex) { + this.col = svCol + (this.pos - this.startPos); + return new TypeScript.RegularExpressionLiteralToken(this.src.substring(svPos - 1, this.pos)); + } + } + this.pos = svPos; + this.col = svCol; + return null; + }; + Scanner.prototype.lastTokenHadNewline = function () { + return this.prevLine != this.startLine; + }; + Scanner.prototype.lastTokenLimChar = function () { + return this.interveningWhitespace ? this.interveningWhitespacePos : this.startPos; + }; + Scanner.prototype.advanceChar = function (amt) { + this.pos += amt; + this.col += amt; + this.ch = this.peekChar(); + }; + Scanner.prototype.nextChar = function () { + this.pos++; + this.col++; + this.ch = this.peekChar(); + }; + Scanner.prototype.getLookAheadToken = function () { + var prevLine = this.prevLine; + var line = this.line; + var col = this.col; + var pos = this.pos; + var startPos = this.startPos; + var startCol = this.startCol; + var startLine = this.startLine; + var ch = this.ch; + var prevTok = this.prevTok; + var lexState = this.lexState; + var interveningWhitespace = this.interveningWhitespace; + var interveningWhitespacePos = this.interveningWhitespacePos; + var leftCurlyCount = this.leftCurlyCount; + var rightCurlyCount = this.rightCurlyCount; + var seenUnicodeChar = this.seenUnicodeChar; + var seenUnicodeCharInComment = this.seenUnicodeCharInComment; + var commentStackLength = this.commentStack.length; + var lookAheadToken = this.scan(); + this.prevLine = prevLine; + this.line = line; + this.col = col; + this.pos = pos; + this.startPos = startPos; + this.startCol = startCol; + this.startLine = startLine; + this.ch = ch; + this.prevTok = prevTok; + this.lexState = lexState; + this.interveningWhitespace = interveningWhitespace; + this.interveningWhitespacePos = interveningWhitespacePos; + this.leftCurlyCount = leftCurlyCount; + this.rightCurlyCount = rightCurlyCount; + this.seenUnicodeChar = seenUnicodeChar; + this.seenUnicodeCharInComment = seenUnicodeCharInComment; + this.commentStack.length = commentStackLength; + return lookAheadToken; + }; + Scanner.prototype.scanInLine = function () { + if((this.lexState == LexState.InMultilineComment) && (this.scanComments)) { + this.ch = this.peekChar(); + var commentLine = this.line; + this.finishMultilineComment(); + if(this.startPos < this.pos) { + var commentText = this.src.substring(this.startPos, this.pos); + this.tokenStart(); + return new TypeScript.CommentToken(TypeScript.TokenID.Comment, commentText, true, this.startPos, commentLine, true); + } else { + return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; + } + } else if(this.lexState == LexState.InMultilineSingleQuoteString && this.pos < this.len) { + this.ch = this.peekChar(); + this.lexState = LexState.Start; + return this.scanStringConstant(TypeScript.LexCodeAPO); + } else if(this.lexState == LexState.InMultilineDoubleQuoteString && this.pos < this.len) { + this.ch = this.peekChar(); + this.lexState = LexState.Start; + return this.scanStringConstant(TypeScript.LexCodeQUO); + } + this.prevLine = this.line; + var prevTok = this.innerScan(); + if(prevTok.tokenId != TypeScript.TokenID.Whitespace) { + this.prevTok = prevTok; + } + return prevTok; + }; + Scanner.prototype.scan = function () { + this.prevLine = this.line; + this.prevTok = this.innerScan(); + if(this.saveScan) { + this.saveScan.addToken(this.prevTok, this); + } + return this.prevTok; + }; + Scanner.prototype.isValidUnicodeIdentifierChar = function () { + var valid = LexIsUnicodeIdStart(this.ch) || LexIsUnicodeDigit(this.ch); + this.seenUnicodeChar = this.seenUnicodeChar || valid; + return valid; + }; + Scanner.prototype.scanStringConstant = function (endCode) { + scanStringConstantLoop: +for(; ; ) { + switch(this.ch) { + case TypeScript.LexEOF: + this.reportScannerError("Unterminated string constant"); + break scanStringConstantLoop; + case TypeScript.LexCodeLS: + case TypeScript.LexCodePS: + this.seenUnicodeChar = true; + case TypeScript.LexCodeRET: + case TypeScript.LexCodeNWL: + this.reportScannerError("Unterminated string constant"); + break scanStringConstantLoop; + case TypeScript.LexCodeAPO: + case TypeScript.LexCodeQUO: + if(this.ch == endCode) { + this.nextChar(); + break scanStringConstantLoop; + } + break; + case TypeScript.LexCodeBSL: + this.nextChar(); + switch(this.ch) { + case TypeScript.LexCodeAPO: + case TypeScript.LexCodeQUO: + case TypeScript.LexCodeBSL: + this.nextChar(); + continue scanStringConstantLoop; + case TypeScript.LexCodeLS: + case TypeScript.LexCodePS: + this.seenUnicodeChar = true; + case TypeScript.LexCodeRET: + case TypeScript.LexCodeNWL: + if(this.ch == TypeScript.LexCodeRET && this.peekCharAt(this.pos + 1) == TypeScript.LexCodeNWL) { + this.nextChar(); + } + this.newLine(); + if(this.mode == LexMode.Line) { + this.nextChar(); + this.lexState = endCode == TypeScript.LexCodeAPO ? LexState.InMultilineSingleQuoteString : LexState.InMultilineDoubleQuoteString; + break scanStringConstantLoop; + } + break; + case TypeScript.LexCode_x: + case TypeScript.LexCode_u: + var expectedHexDigits = this.ch == TypeScript.LexCode_x ? 2 : 4; + this.nextChar(); + for(var i = 0; i < expectedHexDigits; i++) { + if(this.IsHexDigit(this.ch)) { + this.nextChar(); + } else { + this.reportScannerError("Invalid Unicode escape sequence"); + break; + } + } + continue scanStringConstantLoop; + } + break; + } + if(this.ch >= TypeScript.LexCodeASCIIChars) { + this.seenUnicodeChar = true; + } + this.nextChar(); + } + return new TypeScript.StringLiteralToken(this.src.substring(this.startPos, this.pos)); + }; + Scanner.prototype.scanIdentifier = function () { + var hasEscape = false; + var isFirstChar = (this.ch == TypeScript.LexCodeBSL); + var hasUnicode = false; + for(; ; ) { + while(lexIdStartTable[this.ch] || LexIsDigit(this.ch) || (this.ch >= TypeScript.LexCodeASCIIChars && this.isValidUnicodeIdentifierChar())) { + this.nextChar(); + } + if(this.ch == TypeScript.LexCodeBSL) { + this.nextChar(); + if(this.ch == TypeScript.LexCode_u) { + this.nextChar(); + for(var h = 0; h < 4; h++) { + if(this.IsHexDigit(this.ch)) { + this.nextChar(); + } else { + this.reportScannerError("Invalid Unicode escape sequence"); + return TypeScript.staticTokens[TypeScript.TokenID.Error]; + } + } + var hexChar = parseInt(this.src.substring(this.pos - 4, this.pos), 16); + if(lexIdStartTable[hexChar] || (!isFirstChar && LexIsDigit(hexChar)) || (hexChar >= TypeScript.LexCodeASCIIChars && (LexIsUnicodeIdStart(hexChar) || (!isFirstChar && LexIsUnicodeDigit(hexChar))))) { + } else { + this.reportScannerError("Invalid identifier character"); + return TypeScript.staticTokens[TypeScript.TokenID.Error]; + } + hasEscape = true; + isFirstChar = false; + continue; + } + this.reportScannerError("Invalid Unicode escape sequence"); + return TypeScript.staticTokens[TypeScript.TokenID.Error]; + } + break; + } + var id; + var text = this.src.substring(this.startPos, this.pos); + if(!hasEscape && (id = TypeScript.LexKeywordTable.lookup(text)) != null) { + return TypeScript.staticTokens[id]; + } else { + return new TypeScript.IdentifierToken(text, hasEscape); + } + }; + Scanner.prototype.innerScan = function () { + var rtok; + this.tokenStart(); + this.ch = this.peekChar(); + start: +while(this.pos < this.len) { + if(lexIdStartTable[this.ch] || this.ch == TypeScript.LexCodeBSL || (this.ch >= TypeScript.LexCodeASCIIChars && LexIsUnicodeIdStart(this.ch))) { + return this.scanIdentifier(); + } else if(this.ch == TypeScript.LexCodeSpace) { + if(!this.interveningWhitespace) { + this.interveningWhitespacePos = this.pos; + } + do { + this.nextChar(); + }while(this.ch == TypeScript.LexCodeSpace); + if(this.mode == LexMode.Line) { + var whitespaceText = this.src.substring(this.startPos, this.pos); + return new TypeScript.WhitespaceToken(TypeScript.TokenID.Whitespace, whitespaceText); + } else { + this.tokenStart(); + this.interveningWhitespace = true; + } + } else if(this.ch == TypeScript.LexCodeSLH) { + this.nextChar(); + var commentText; + if(this.ch == TypeScript.LexCodeSLH) { + if(!this.interveningWhitespace) { + this.interveningWhitespacePos = this.pos - 1; + } + var commentStartPos = this.pos - 1; + var commentStartLine = this.line; + this.finishSinglelineComment(); + var commentText = this.src.substring(commentStartPos, this.pos); + var commentToken = new TypeScript.CommentToken(TypeScript.TokenID.Comment, commentText, false, commentStartPos, commentStartLine, false); + if(this.scanComments) { + this.startPos = commentStartPos; + return commentToken; + } else { + this.pushComment(commentToken); + } + this.interveningWhitespace = true; + } else if(this.ch == TypeScript.LexCodeMUL) { + if(!this.interveningWhitespace) { + this.interveningWhitespacePos = this.pos - 1; + } + var commentStartPos = this.pos - 1; + var commentStartLine = this.line; + this.nextChar(); + this.finishMultilineComment(); + var commentText = this.src.substring(commentStartPos, this.pos); + var endsLine = this.endsLine(this.peekChar()); + var commentToken = new TypeScript.CommentToken(TypeScript.TokenID.Comment, commentText, true, commentStartPos, commentStartLine, endsLine); + if(this.scanComments) { + this.startPos = commentStartPos; + return commentToken; + } else { + this.pushComment(commentToken); + } + this.interveningWhitespace = true; + } else { + var regexTok = this.speculateRegex(); + if(regexTok) { + return regexTok; + } else { + if(this.peekCharAt(this.pos) == TypeScript.LexCodeEQ) { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.SlashEquals]; + } else { + return TypeScript.staticTokens[TypeScript.TokenID.Slash]; + } + } + } + } else if(this.ch == TypeScript.LexCodeSMC) { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Semicolon]; + } else if((this.ch == TypeScript.LexCodeAPO) || (this.ch == TypeScript.LexCodeQUO)) { + var endCode = this.ch; + this.nextChar(); + return this.scanStringConstant(endCode); + } else if(autoToken[this.ch]) { + var atok = autoToken[this.ch]; + if(atok.tokenId == TypeScript.TokenID.OpenBrace) { + this.leftCurlyCount++; + } else if(atok.tokenId == TypeScript.TokenID.CloseBrace) { + this.rightCurlyCount++; + } + this.nextChar(); + return atok; + } else if((this.ch >= TypeScript.LexCode_0) && (this.ch <= TypeScript.LexCode_9)) { + rtok = this.scanNumber(); + if(rtok) { + return rtok; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Error]; + } + } else { + switch(this.ch) { + case TypeScript.LexCodeTAB: + case TypeScript.LexCodeVTAB: + if(!this.interveningWhitespace) { + this.interveningWhitespacePos = this.pos; + } + if(this.mode == LexMode.Line) { + do { + this.nextChar(); + }while((this.ch == TypeScript.LexCodeSpace) || (this.ch == 9)); + var wsText = this.src.substring(this.startPos, this.pos); + return new TypeScript.WhitespaceToken(TypeScript.TokenID.Whitespace, wsText); + } else { + this.interveningWhitespace = true; + } + case 0xFF: + case 0xFE: + case 0xEF: + case 0xBB: + case 0xBF: + case TypeScript.LexCodeLS: + case TypeScript.LexCodePS: + case TypeScript.LexCodeNWL: + case TypeScript.LexCodeRET: + if(this.ch == TypeScript.LexCodeNWL) { + this.newLine(); + if(this.mode == LexMode.Line) { + return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; + } + } + if(!this.interveningWhitespace) { + this.interveningWhitespacePos = this.pos; + } + this.nextChar(); + this.tokenStart(); + this.interveningWhitespace = true; + break; + case TypeScript.LexCodeDOT: { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeDOT) { + if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeDOT) { + this.advanceChar(3); + return TypeScript.staticTokens[TypeScript.TokenID.DotDotDot]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Dot]; + } + } else { + this.nextChar(); + rtok = this.scanFraction(); + if(rtok) { + return rtok; + } else { + return TypeScript.staticTokens[TypeScript.TokenID.Dot]; + } + } + } + case TypeScript.LexCodeEQ: + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeEQ) { + this.advanceChar(3); + return TypeScript.staticTokens[TypeScript.TokenID.EqualsEqualsEquals]; + } else { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.EqualsEquals]; + } + } else if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeGT) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.EqualsGreaterThan]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Equals]; + } + case TypeScript.LexCodeBNG: + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeEQ) { + this.advanceChar(3); + return TypeScript.staticTokens[TypeScript.TokenID.ExclamationEqualsEquals]; + } else { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.ExclamationEquals]; + } + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Exclamation]; + } + case TypeScript.LexCodePLS: + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.PlusEquals]; + } else if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodePLS) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.PlusPlus]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Plus]; + } + case TypeScript.LexCodeMIN: + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.MinusEquals]; + } else if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeMIN) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.MinusMinus]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Minus]; + } + case TypeScript.LexCodeMUL: + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.AsteriskEquals]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Asterisk]; + } + case TypeScript.LexCodePCT: + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.PercentEquals]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Percent]; + } + case TypeScript.LexCodeLT: + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeLT) { + if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeEQ) { + this.advanceChar(3); + return TypeScript.staticTokens[TypeScript.TokenID.LessThanLessThanEquals]; + } else { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.LessThanLessThan]; + } + } else if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.LessThanEquals]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.LessThan]; + } + case TypeScript.LexCodeGT: + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeGT) { + if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeEQ) { + this.advanceChar(3); + return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanGreaterThanEquals]; + } else if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeGT) { + if(this.peekCharAt(this.pos + 3) == TypeScript.LexCodeEQ) { + this.advanceChar(4); + return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanGreaterThanGreaterThanEquals]; + } else { + this.advanceChar(3); + return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanGreaterThanGreaterThan]; + } + } else { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanGreaterThan]; + } + } else if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanEquals]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.GreaterThan]; + } + case TypeScript.LexCodeXOR: + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.CaretEquals]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Caret]; + } + case TypeScript.LexCodeBAR: + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.BarEquals]; + } else if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeBAR) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.BarBar]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Bar]; + } + case TypeScript.LexCodeAMP: + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.AmpersandEquals]; + } else if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeAMP) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.AmpersandAmpersand]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.And]; + } + default: + this.reportScannerError("Invalid character"); + this.nextChar(); + continue start; + } + } + } + return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; + }; + Scanner.prototype.reportScannerError = function (message) { + if(this.reportError) { + this.reportError(message); + } + }; + return Scanner; + })(); + TypeScript.Scanner = Scanner; + function convertTokToIDName(tok) { + return convertTokToIDBase(tok, true, false); + } + TypeScript.convertTokToIDName = convertTokToIDName; + function convertTokToID(tok, strictMode) { + return convertTokToIDBase(tok, false, strictMode); + } + TypeScript.convertTokToID = convertTokToID; + function convertTokToIDBase(tok, identifierName, strictMode) { + if(tok.tokenId <= TypeScript.TokenID.LimKeyword) { + var tokInfo = TypeScript.lookupToken(tok.tokenId); + if(tokInfo != undefined) { + var resFlags = TypeScript.Reservation.Javascript | TypeScript.Reservation.JavascriptFuture; + if(strictMode) { + resFlags |= TypeScript.Reservation.JavascriptFutureStrict; + } + if(identifierName || !TypeScript.hasFlag(tokInfo.reservation, resFlags)) { + return true; + } + } else { + return false; + } + } else { + return false; + } + } + function getLineNumberFromPosition(lineMap, position) { + if(position === -1) { + return 0; + } + var min = 0; + var max = lineMap.length - 1; + while(min < max) { + var med = (min + max) >> 1; + if(position < lineMap[med]) { + max = med - 1; + } else if(position < lineMap[med + 1]) { + min = max = med; + } else { + min = med + 1; + } + } + return min; + } + TypeScript.getLineNumberFromPosition = getLineNumberFromPosition; + function getSourceLineColFromMap(lineCol, minChar, lineMap) { + var line = getLineNumberFromPosition(lineMap, minChar); + if(line > 0) { + lineCol.line = line; + lineCol.col = (minChar - lineMap[line]); + } + } + TypeScript.getSourceLineColFromMap = getSourceLineColFromMap; + function getLineColumnFromPosition(script, position) { + var result = { + line: -1, + col: -1 + }; + getSourceLineColFromMap(result, position, script.locationInfo.lineMap); + if(result.col >= 0) { + result.col++; + } + return result; + } + TypeScript.getLineColumnFromPosition = getLineColumnFromPosition; + function getPositionFromLineColumn(script, line, column) { + return script.locationInfo.lineMap[line] + (column - 1); + } + TypeScript.getPositionFromLineColumn = getPositionFromLineColumn; + function isPrimitiveTypeToken(token) { + switch(token.tokenId) { + case TypeScript.TokenID.Any: + case TypeScript.TokenID.Bool: + case TypeScript.TokenID.Number: + case TypeScript.TokenID.String: + return true; + } + return false; + } + TypeScript.isPrimitiveTypeToken = isPrimitiveTypeToken; + function isModifier(token) { + switch(token.tokenId) { + case TypeScript.TokenID.Public: + case TypeScript.TokenID.Private: + case TypeScript.TokenID.Static: + return true; + } + return false; + } + TypeScript.isModifier = isModifier; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var AssignScopeContext = (function () { + function AssignScopeContext(scopeChain, typeFlow, modDeclChain) { + this.scopeChain = scopeChain; + this.typeFlow = typeFlow; + this.modDeclChain = modDeclChain; + } + return AssignScopeContext; + })(); + TypeScript.AssignScopeContext = AssignScopeContext; + function pushAssignScope(scope, context, type, classType, fnc) { + var chain = new TypeScript.ScopeChain(null, context.scopeChain, scope); + chain.thisType = type; + chain.classType = classType; + chain.fnc = fnc; + context.scopeChain = chain; + } + TypeScript.pushAssignScope = pushAssignScope; + function popAssignScope(context) { + context.scopeChain = context.scopeChain.previous; + } + TypeScript.popAssignScope = popAssignScope; + function instanceCompare(a, b) { + if(((a == null) || (!a.isInstanceProperty()))) { + return b; + } else { + return a; + } + } + TypeScript.instanceCompare = instanceCompare; + function instanceFilterStop(s) { + return s.isInstanceProperty(); + } + TypeScript.instanceFilterStop = instanceFilterStop; + var ScopeSearchFilter = (function () { + function ScopeSearchFilter(select, stop) { + this.select = select; + this.stop = stop; + this.result = null; + } + ScopeSearchFilter.prototype.reset = function () { + this.result = null; + }; + ScopeSearchFilter.prototype.update = function (b) { + this.result = this.select(this.result, b); + if(this.result) { + return this.stop(this.result); + } else { + return false; + } + }; + return ScopeSearchFilter; + })(); + TypeScript.ScopeSearchFilter = ScopeSearchFilter; + TypeScript.instanceFilter = new ScopeSearchFilter(instanceCompare, instanceFilterStop); + function preAssignModuleScopes(ast, context) { + var moduleDecl = ast; + var memberScope = null; + var aggScope = null; + if(moduleDecl.name && moduleDecl.mod) { + moduleDecl.name.sym = moduleDecl.mod.symbol; + } + var mod = moduleDecl.mod; + if(!mod) { + return; + } + memberScope = new TypeScript.SymbolTableScope(mod.members, mod.ambientMembers, mod.enclosedTypes, mod.ambientEnclosedTypes, mod.symbol); + mod.memberScope = memberScope; + context.modDeclChain.push(moduleDecl); + context.typeFlow.checker.currentModDecl = moduleDecl; + aggScope = new TypeScript.SymbolAggregateScope(mod.symbol); + aggScope.addParentScope(memberScope); + aggScope.addParentScope(context.scopeChain.scope); + pushAssignScope(aggScope, context, null, null, null); + mod.containedScope = aggScope; + if(mod.symbol) { + context.typeFlow.addLocalsFromScope(mod.containedScope, mod.symbol, moduleDecl.vars, mod.members.privateMembers, true); + } + } + TypeScript.preAssignModuleScopes = preAssignModuleScopes; + function preAssignClassScopes(ast, context) { + var classDecl = ast; + var memberScope = null; + var aggScope = null; + if(classDecl.name && classDecl.type) { + classDecl.name.sym = classDecl.type.symbol; + } + var classType = ast.type; + if(classType) { + var classSym = classType.symbol; + memberScope = context.typeFlow.checker.scopeOf(classType); + aggScope = new TypeScript.SymbolAggregateScope(classType.symbol); + aggScope.addParentScope(memberScope); + aggScope.addParentScope(context.scopeChain.scope); + classType.containedScope = aggScope; + classType.memberScope = memberScope; + var instanceType = classType.instanceType; + memberScope = context.typeFlow.checker.scopeOf(instanceType); + instanceType.memberScope = memberScope; + aggScope = new TypeScript.SymbolAggregateScope(instanceType.symbol); + aggScope.addParentScope(context.scopeChain.scope); + pushAssignScope(aggScope, context, instanceType, classType, null); + instanceType.containedScope = aggScope; + } else { + ast.type = context.typeFlow.anyType; + } + } + TypeScript.preAssignClassScopes = preAssignClassScopes; + function preAssignInterfaceScopes(ast, context) { + var interfaceDecl = ast; + var memberScope = null; + var aggScope = null; + if(interfaceDecl.name && interfaceDecl.type) { + interfaceDecl.name.sym = interfaceDecl.type.symbol; + } + var interfaceType = ast.type; + memberScope = context.typeFlow.checker.scopeOf(interfaceType); + interfaceType.memberScope = memberScope; + aggScope = new TypeScript.SymbolAggregateScope(interfaceType.symbol); + aggScope.addParentScope(memberScope); + aggScope.addParentScope(context.scopeChain.scope); + pushAssignScope(aggScope, context, null, null, null); + interfaceType.containedScope = aggScope; + } + TypeScript.preAssignInterfaceScopes = preAssignInterfaceScopes; + function preAssignWithScopes(ast, context) { + var withStmt = ast; + var withType = withStmt.type; + var members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + var ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + var withType = new TypeScript.Type(); + var withSymbol = new TypeScript.WithSymbol(withStmt.minChar, context.typeFlow.checker.locationInfo.unitIndex, withType); + withType.members = members; + withType.ambientMembers = ambientMembers; + withType.symbol = withSymbol; + withType.setHasImplementation(); + withStmt.type = withType; + var withScope = new TypeScript.SymbolScopeBuilder(withType.members, withType.ambientMembers, null, null, context.scopeChain.scope, withType.symbol); + pushAssignScope(withScope, context, null, null, null); + withType.containedScope = withScope; + } + TypeScript.preAssignWithScopes = preAssignWithScopes; + function preAssignFuncDeclScopes(ast, context) { + var funcDecl = ast; + var container = null; + var localContainer = null; + if(funcDecl.type) { + localContainer = ast.type.symbol; + } + var isStatic = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static); + var isInnerStatic = isStatic && context.scopeChain.fnc != null; + var parentScope = isInnerStatic ? context.scopeChain.fnc.type.memberScope : context.scopeChain.scope; + if(context.scopeChain.thisType && (!funcDecl.isConstructor || TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod))) { + var instType = context.scopeChain.thisType; + if(!(instType.typeFlags & TypeScript.TypeFlags.IsClass) && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { + if(!funcDecl.isMethod() || isStatic) { + parentScope = instType.constructorScope; + } else { + parentScope = instType.containedScope; + } + } else { + if(context.scopeChain.previous.scope.container && context.scopeChain.previous.scope.container.declAST && context.scopeChain.previous.scope.container.declAST.nodeType == TypeScript.NodeType.FuncDecl && (context.scopeChain.previous.scope.container.declAST).isConstructor) { + parentScope = instType.constructorScope; + } else if(isStatic && context.scopeChain.classType) { + parentScope = context.scopeChain.classType.containedScope; + } else { + parentScope = instType.containedScope; + } + } + container = instType.symbol; + } else if(funcDecl.isConstructor && context.scopeChain.thisType) { + container = context.scopeChain.thisType.symbol; + } + if(funcDecl.type == null || TypeScript.hasFlag(funcDecl.type.symbol.flags, TypeScript.SymbolFlags.TypeSetDuringScopeAssignment)) { + if(context.scopeChain.fnc && context.scopeChain.fnc.type) { + container = context.scopeChain.fnc.type.symbol; + } + var funcScope = null; + var outerFnc = context.scopeChain.fnc; + var nameText = funcDecl.name ? funcDecl.name.actualText : null; + var fgSym = null; + if(isStatic) { + if(outerFnc.type.members == null && container.getType().memberScope) { + outerFnc.type.members = ((container).type.memberScope).valueMembers; + } + funcScope = context.scopeChain.fnc.type.memberScope; + outerFnc.innerStaticFuncs[outerFnc.innerStaticFuncs.length] = funcDecl; + } else { + funcScope = context.scopeChain.scope; + } + if(nameText && nameText != "__missing" && !funcDecl.isAccessor()) { + if(isStatic) { + fgSym = funcScope.findLocal(nameText, false, false); + } else { + fgSym = funcScope.findLocal(nameText, false, false); + } + } + context.typeFlow.checker.createFunctionSignature(funcDecl, container, funcScope, fgSym, fgSym == null); + if(!funcDecl.accessorSymbol && (funcDecl.fncFlags & TypeScript.FncFlags.ClassMethod) && container && ((!fgSym || fgSym.declAST.nodeType != TypeScript.NodeType.FuncDecl) && funcDecl.isAccessor()) || (fgSym && fgSym.isAccessor())) { + funcDecl.accessorSymbol = context.typeFlow.checker.createAccessorSymbol(funcDecl, fgSym, container.getType(), (funcDecl.isMethod() && isStatic), true, funcScope, container); + } + funcDecl.type.symbol.flags |= TypeScript.SymbolFlags.TypeSetDuringScopeAssignment; + } + if(funcDecl.name && funcDecl.type) { + funcDecl.name.sym = funcDecl.type.symbol; + } + funcDecl.scopeType = funcDecl.type; + if(funcDecl.isOverload) { + return; + } + var funcTable = new TypeScript.StringHashTable(); + var funcMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(funcTable, new TypeScript.StringHashTable())); + var ambientFuncTable = new TypeScript.StringHashTable(); + var ambientFuncMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(ambientFuncTable, new TypeScript.StringHashTable())); + var funcStaticTable = new TypeScript.StringHashTable(); + var funcStaticMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(funcStaticTable, new TypeScript.StringHashTable())); + var ambientFuncStaticTable = new TypeScript.StringHashTable(); + var ambientFuncStaticMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(ambientFuncStaticTable, new TypeScript.StringHashTable())); + funcDecl.unitIndex = context.typeFlow.checker.locationInfo.unitIndex; + var locals = new TypeScript.SymbolScopeBuilder(funcMembers, ambientFuncMembers, null, null, parentScope, localContainer); + var statics = new TypeScript.SymbolScopeBuilder(funcStaticMembers, ambientFuncStaticMembers, null, null, parentScope, null); + if(funcDecl.isConstructor && context.scopeChain.thisType) { + context.scopeChain.thisType.constructorScope = locals; + } + funcDecl.symbols = funcTable; + if(!funcDecl.isSpecialFn()) { + var group = funcDecl.type; + var signature = funcDecl.signature; + if(!funcDecl.isConstructor) { + group.containedScope = locals; + locals.container = group.symbol; + group.memberScope = statics; + statics.container = group.symbol; + } + funcDecl.enclosingFnc = context.scopeChain.fnc; + group.enclosingType = isStatic ? context.scopeChain.classType : context.scopeChain.thisType; + var fgSym = ast.type.symbol; + if(((funcDecl.fncFlags & TypeScript.FncFlags.Signature) == TypeScript.FncFlags.None) && funcDecl.vars) { + context.typeFlow.addLocalsFromScope(locals, fgSym, funcDecl.vars, funcTable, false); + context.typeFlow.addLocalsFromScope(statics, fgSym, funcDecl.statics, funcStaticTable, false); + } + if(signature.parameters) { + var len = signature.parameters.length; + for(var i = 0; i < len; i++) { + var paramSym = signature.parameters[i]; + context.typeFlow.checker.resolveTypeLink(locals, paramSym.parameter.typeLink, true); + } + } + context.typeFlow.checker.resolveTypeLink(locals, signature.returnType, funcDecl.isSignature()); + } + if(!funcDecl.isConstructor || TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { + var thisType = (funcDecl.isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) ? context.scopeChain.thisType : null; + pushAssignScope(locals, context, thisType, null, funcDecl); + } + if(funcDecl.name && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFunctionExpression) && !funcDecl.isAccessor()) { + if(funcDecl.name.sym) { + funcTable.add(funcDecl.name.actualText, funcDecl.name.sym); + } + } + } + TypeScript.preAssignFuncDeclScopes = preAssignFuncDeclScopes; + function preAssignCatchScopes(ast, context) { + var catchBlock = ast; + if(catchBlock.param) { + var catchTable = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + var catchLocals = new TypeScript.SymbolScopeBuilder(catchTable, null, null, null, context.scopeChain.scope, context.scopeChain.scope.container); + catchBlock.containedScope = catchLocals; + pushAssignScope(catchLocals, context, context.scopeChain.thisType, context.scopeChain.classType, context.scopeChain.fnc); + } + } + TypeScript.preAssignCatchScopes = preAssignCatchScopes; + function preAssignScopes(ast, parent, walker) { + var context = walker.state; + var go = true; + if(ast) { + if(ast.nodeType == TypeScript.NodeType.List) { + var list = ast; + list.enclosingScope = context.scopeChain.scope; + } else if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { + preAssignModuleScopes(ast, context); + } else if(ast.nodeType == TypeScript.NodeType.ClassDeclaration) { + preAssignClassScopes(ast, context); + } else if(ast.nodeType == TypeScript.NodeType.InterfaceDeclaration) { + preAssignInterfaceScopes(ast, context); + } else if(ast.nodeType == TypeScript.NodeType.With) { + preAssignWithScopes(ast, context); + } else if(ast.nodeType == TypeScript.NodeType.FuncDecl) { + preAssignFuncDeclScopes(ast, context); + } else if(ast.nodeType == TypeScript.NodeType.Catch) { + preAssignCatchScopes(ast, context); + } else if(ast.nodeType == TypeScript.NodeType.TypeRef) { + go = false; + } + } + walker.options.goChildren = go; + return ast; + } + TypeScript.preAssignScopes = preAssignScopes; + function postAssignScopes(ast, parent, walker) { + var context = walker.state; + var go = true; + if(ast) { + if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { + var prevModDecl = ast; + popAssignScope(context); + context.modDeclChain.pop(); + if(context.modDeclChain.length >= 1) { + context.typeFlow.checker.currentModDecl = context.modDeclChain[context.modDeclChain.length - 1]; + } + } else if(ast.nodeType == TypeScript.NodeType.ClassDeclaration) { + popAssignScope(context); + } else if(ast.nodeType == TypeScript.NodeType.InterfaceDeclaration) { + popAssignScope(context); + } else if(ast.nodeType == TypeScript.NodeType.With) { + popAssignScope(context); + } else if(ast.nodeType == TypeScript.NodeType.FuncDecl) { + var funcDecl = ast; + if((!funcDecl.isConstructor || TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) && !funcDecl.isOverload) { + popAssignScope(context); + } + } else if(ast.nodeType == TypeScript.NodeType.Catch) { + var catchBlock = ast; + if(catchBlock.param) { + popAssignScope(context); + } + } else { + go = false; + } + } + walker.options.goChildren = go; + return ast; + } + TypeScript.postAssignScopes = postAssignScopes; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var TypeCollectionContext = (function () { + function TypeCollectionContext(scopeChain, checker) { + this.scopeChain = scopeChain; + this.checker = checker; + this.script = null; + } + return TypeCollectionContext; + })(); + TypeScript.TypeCollectionContext = TypeCollectionContext; + var MemberScopeContext = (function () { + function MemberScopeContext(flow, pos, matchFlag) { + this.flow = flow; + this.pos = pos; + this.matchFlag = matchFlag; + this.type = null; + this.ast = null; + this.options = new TypeScript.AstWalkOptions(); + } + return MemberScopeContext; + })(); + TypeScript.MemberScopeContext = MemberScopeContext; + var EnclosingScopeContext = (function () { + function EnclosingScopeContext(logger, script, text, pos, isMemberCompletion) { + this.logger = logger; + this.script = script; + this.text = text; + this.pos = pos; + this.isMemberCompletion = isMemberCompletion; + this.scopeGetter = null; + this.objectLiteralScopeGetter = null; + this.scopeStartAST = null; + this.skipNextFuncDeclForClass = false; + this.deepestModuleDecl = null; + this.enclosingClassDecl = null; + this.enclosingObjectLit = null; + this.publicsOnly = true; + this.useFullAst = false; + } + EnclosingScopeContext.prototype.getScope = function () { + return this.scopeGetter(); + }; + EnclosingScopeContext.prototype.getObjectLiteralScope = function () { + return this.objectLiteralScopeGetter(); + }; + EnclosingScopeContext.prototype.getScopeAST = function () { + return this.scopeStartAST; + }; + EnclosingScopeContext.prototype.getScopePosition = function () { + return this.scopeStartAST.minChar; + }; + EnclosingScopeContext.prototype.getScriptFragmentStartAST = function () { + return this.scopeStartAST; + }; + EnclosingScopeContext.prototype.getScriptFragmentPosition = function () { + return this.getScriptFragmentStartAST().minChar; + }; + EnclosingScopeContext.prototype.getScriptFragment = function () { + if(this.scriptFragment == null) { + var ast = this.getScriptFragmentStartAST(); + var minChar = ast.minChar; + var limChar = (this.isMemberCompletion ? this.pos : this.pos + 1); + this.scriptFragment = TypeScript.quickParse(this.logger, ast, this.text, minChar, limChar, null).Script; + } + return this.scriptFragment; + }; + return EnclosingScopeContext; + })(); + TypeScript.EnclosingScopeContext = EnclosingScopeContext; + function preFindMemberScope(ast, parent, walker) { + var memScope = walker.state; + if(TypeScript.hasFlag(ast.flags, memScope.matchFlag) && ((memScope.pos < 0) || (memScope.pos == ast.limChar))) { + memScope.ast = ast; + if((ast.type == null) && (memScope.pos >= 0)) { + memScope.flow.inScopeTypeCheck(ast, memScope.scope); + } + memScope.type = ast.type; + memScope.options.stopWalk(); + } + return ast; + } + TypeScript.preFindMemberScope = preFindMemberScope; + function pushTypeCollectionScope(container, valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, context, thisType, classType, moduleDecl) { + var builder = new TypeScript.SymbolScopeBuilder(valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, null, container); + var chain = new TypeScript.ScopeChain(container, context.scopeChain, builder); + chain.thisType = thisType; + chain.classType = classType; + chain.moduleDecl = moduleDecl; + context.scopeChain = chain; + } + TypeScript.pushTypeCollectionScope = pushTypeCollectionScope; + function popTypeCollectionScope(context) { + context.scopeChain = context.scopeChain.previous; + } + TypeScript.popTypeCollectionScope = popTypeCollectionScope; + function preFindEnclosingScope(ast, parent, walker) { + var context = walker.state; + var minChar = ast.minChar; + var limChar = ast.limChar; + if(ast.nodeType == TypeScript.NodeType.Script && context.pos > limChar) { + limChar = context.pos; + } + if((minChar <= context.pos) && (limChar >= context.pos)) { + switch(ast.nodeType) { + case TypeScript.NodeType.Script: + var script = ast; + context.scopeGetter = function () { + return script.bod === null ? null : script.bod.enclosingScope; + }; + context.scopeStartAST = script; + break; + case TypeScript.NodeType.ClassDeclaration: + context.scopeGetter = function () { + return (ast.type === null || ast.type.instanceType.containedScope === null) ? null : ast.type.instanceType.containedScope; + }; + context.scopeStartAST = ast; + context.enclosingClassDecl = ast; + break; + case TypeScript.NodeType.ObjectLit: + var objectLit = ast; + if(objectLit.targetType) { + context.scopeGetter = function () { + return objectLit.targetType.containedScope; + }; + context.objectLiteralScopeGetter = function () { + return objectLit.targetType.memberScope; + }; + context.enclosingObjectLit = objectLit; + } + break; + case TypeScript.NodeType.ModuleDeclaration: + context.deepestModuleDecl = ast; + context.scopeGetter = function () { + return ast.type === null ? null : ast.type.containedScope; + }; + context.scopeStartAST = ast; + break; + case TypeScript.NodeType.InterfaceDeclaration: + context.scopeGetter = function () { + return (ast.type === null) ? null : ast.type.containedScope; + }; + context.scopeStartAST = ast; + break; + case TypeScript.NodeType.FuncDecl: + { + var funcDecl = ast; + if(context.skipNextFuncDeclForClass) { + context.skipNextFuncDeclForClass = false; + } else { + context.scopeGetter = function () { + if(funcDecl.isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { + if(ast.type && ast.type.enclosingType) { + return ast.type.enclosingType.constructorScope; + } + } + if(funcDecl.scopeType) { + return funcDecl.scopeType.containedScope; + } + if(funcDecl.type) { + return funcDecl.type.containedScope; + } + return null; + }; + context.scopeStartAST = ast; + } + } + break; + } + walker.options.goChildren = true; + } else { + walker.options.goChildren = false; + } + return ast; + } + TypeScript.preFindEnclosingScope = preFindEnclosingScope; + function findEnclosingScopeAt(logger, script, text, pos, isMemberCompletion) { + var context = new EnclosingScopeContext(logger, script, text, pos, isMemberCompletion); + TypeScript.getAstWalkerFactory().walk(script, preFindEnclosingScope, null, null, context); + if(context.scopeStartAST === null) { + return null; + } + return context; + } + TypeScript.findEnclosingScopeAt = findEnclosingScopeAt; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Signature = (function () { + function Signature() { + this.hasVariableArgList = false; + this.parameters = null; + this.declAST = null; + this.typeCheckStatus = TypeScript.TypeCheckStatus.NotStarted; + this.nonOptionalParameterCount = 0; + } + Signature.prototype.specializeType = function (pattern, replacement, checker) { + var result = new Signature(); + if(this.hasVariableArgList) { + result.hasVariableArgList = true; + } + result.returnType = new TypeScript.TypeLink(); + if(this.returnType.type) { + result.returnType.type = this.returnType.type.specializeType(pattern, replacement, checker, false); + } else { + result.returnType.type = checker.anyType; + } + if(this.parameters) { + result.parameters = []; + for(var i = 0, len = this.parameters.length; i < len; i++) { + var oldSym = this.parameters[i]; + var paramDef = new TypeScript.ValueLocation(); + var paramSym = new TypeScript.ParameterSymbol(oldSym.name, oldSym.location, checker.locationInfo.unitIndex, paramDef); + paramSym.declAST = this.declAST; + paramDef.symbol = paramSym; + paramDef.typeLink = new TypeScript.TypeLink(); + result.parameters[i] = paramSym; + var oldType = oldSym.getType(); + if(oldType) { + paramDef.typeLink.type = oldType.specializeType(pattern, replacement, checker, false); + } else { + paramDef.typeLink.type = checker.anyType; + } + } + } + result.nonOptionalParameterCount = this.nonOptionalParameterCount; + result.declAST = this.declAST; + return result; + }; + Signature.prototype.toString = function () { + return this.toStringHelper(false, false, null); + }; + Signature.prototype.toStringHelper = function (shortform, brackets, scope) { + return this.toStringHelperEx(shortform, brackets, scope).toString(); + }; + Signature.prototype.toStringHelperEx = function (shortform, brackets, scope, prefix) { + if (typeof prefix === "undefined") { prefix = ""; } + var builder = new TypeScript.MemberNameArray(); + if(brackets) { + builder.prefix = prefix + "["; + } else { + builder.prefix = prefix + "("; + } + var paramLen = this.parameters.length; + var len = this.hasVariableArgList ? paramLen - 1 : paramLen; + for(var i = 0; i < len; i++) { + builder.add(TypeScript.MemberName.create(this.parameters[i].name + (this.parameters[i].isOptional() ? "?" : "") + ": ")); + builder.add(this.parameters[i].getType().getScopedTypeNameEx(scope)); + if(i < paramLen - 1) { + builder.add(TypeScript.MemberName.create(", ")); + } + } + if(this.hasVariableArgList) { + builder.add(TypeScript.MemberName.create("..." + this.parameters[i].name + ": ")); + builder.add(this.parameters[i].getType().getScopedTypeNameEx(scope)); + } + if(shortform) { + if(brackets) { + builder.add(TypeScript.MemberName.create("] => ")); + } else { + builder.add(TypeScript.MemberName.create(") => ")); + } + } else { + if(brackets) { + builder.add(TypeScript.MemberName.create("]: ")); + } else { + builder.add(TypeScript.MemberName.create("): ")); + } + } + if(this.returnType.type) { + builder.add(this.returnType.type.getScopedTypeNameEx(scope)); + } else { + builder.add(TypeScript.MemberName.create("any")); + } + return builder; + }; + return Signature; + })(); + TypeScript.Signature = Signature; + var SignatureGroup = (function () { + function SignatureGroup() { + this.signatures = []; + this.hasImplementation = true; + this.definitionSignature = null; + this.hasBeenTypechecked = false; + this.flags = TypeScript.SignatureFlags.None; + } + SignatureGroup.prototype.addSignature = function (signature) { + if(this.signatures == null) { + this.signatures = new Array(); + } + this.signatures[this.signatures.length] = signature; + if(signature.declAST && !signature.declAST.isOverload && !signature.declAST.isSignature() && !TypeScript.hasFlag(signature.declAST.fncFlags, TypeScript.FncFlags.Ambient) && !TypeScript.hasFlag(signature.declAST.fncFlags, TypeScript.FncFlags.Signature)) { + this.definitionSignature = signature; + } + }; + SignatureGroup.prototype.toString = function () { + return this.signatures.toString(); + }; + SignatureGroup.prototype.toStrings = function (prefix, shortform, scope, getPrettyTypeName, useSignature) { + var _this = this; + var result = []; + var len = this.signatures.length; + if(!getPrettyTypeName && len > 1) { + shortform = false; + } + var getMemberNameOfSignature = function (signature) { + if(_this.flags & TypeScript.SignatureFlags.IsIndexer) { + return signature.toStringHelperEx(shortform, true, scope); + } else { + return signature.toStringHelperEx(shortform, false, scope, prefix); + } + }; + if(useSignature) { + result.push(getMemberNameOfSignature(useSignature)); + } else { + for(var i = 0; i < len; i++) { + if(len > 1 && this.signatures[i] == this.definitionSignature) { + continue; + } + result.push(getMemberNameOfSignature(this.signatures[i])); + if(getPrettyTypeName) { + break; + } + } + } + if(getPrettyTypeName && len > 1) { + var lastMemberName = result[result.length - 1]; + var overloadString = " (+ " + ((this.definitionSignature != null) ? len - 2 : len - 1) + " overload(s))"; + lastMemberName.add(TypeScript.MemberName.create(overloadString)); + } + return result; + }; + SignatureGroup.prototype.specializeType = function (pattern, replacement, checker) { + var result = new SignatureGroup(); + if(this.signatures) { + for(var i = 0, len = this.signatures.length; i < len; i++) { + result.addSignature(this.signatures[i].specializeType(pattern, replacement, checker)); + } + } + return result; + }; + SignatureGroup.prototype.verifySignatures = function (checker) { + var len = 0; + if(this.signatures && ((len = this.signatures.length) > 0)) { + for(var i = 0; i < len; i++) { + for(var j = i + 1; j < len; j++) { + if(this.signatures[i].declAST && this.signatures[j].declAST && (TypeScript.hasFlag(this.signatures[i].declAST.fncFlags, TypeScript.FncFlags.Signature) && TypeScript.hasFlag(this.signatures[j].declAST.fncFlags, TypeScript.FncFlags.Signature)) && checker.signaturesAreIdentical(this.signatures[i], this.signatures[j])) { + checker.errorReporter.simpleError(this.signatures[i].declAST, (this.signatures[i].declAST && this.signatures[i].declAST.name) ? "Signature for '" + this.signatures[i].declAST.name.actualText + "' is duplicated" : "Signature is duplicated"); + } + } + if(this.definitionSignature) { + if(!checker.signatureIsAssignableToTarget(this.definitionSignature, this.signatures[i])) { + checker.errorReporter.simpleError(this.signatures[i].declAST, "Overload signature is not compatible with function definition"); + } + } + } + } + }; + SignatureGroup.prototype.typeCheck = function (checker, ast, hasConstruct) { + if(this.hasBeenTypechecked) { + return; + } + this.hasBeenTypechecked = true; + var len = 0; + if(this.signatures && ((len = this.signatures.length) > 0)) { + for(var i = 0; i < len; i++) { + if(!hasConstruct && !this.definitionSignature && this.signatures[i].declAST && this.signatures[i].declAST.isOverload && !TypeScript.hasFlag(this.signatures[i].declAST.fncFlags, TypeScript.FncFlags.Ambient)) { + checker.errorReporter.simpleError(this.signatures[i].declAST, "Overload declaration lacks definition"); + } + if(this.signatures[i].declAST && this.signatures[i].declAST.isConstructor && this.signatures[i].declAST.classDecl && this.signatures[i].declAST.classDecl.type.symbol.typeCheckStatus == TypeScript.TypeCheckStatus.NotStarted) { + checker.typeFlow.typeCheck(this.signatures[i].declAST.classDecl); + } + checker.typeFlow.typeCheck(this.signatures[i].declAST); + } + this.verifySignatures(checker); + } + }; + return SignatureGroup; + })(); + TypeScript.SignatureGroup = SignatureGroup; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (TypeCheckStatus) { + TypeCheckStatus._map = []; + TypeCheckStatus._map[0] = "NotStarted"; + TypeCheckStatus.NotStarted = 0; + TypeCheckStatus._map[1] = "Started"; + TypeCheckStatus.Started = 1; + TypeCheckStatus._map[2] = "Finished"; + TypeCheckStatus.Finished = 2; + })(TypeScript.TypeCheckStatus || (TypeScript.TypeCheckStatus = {})); + var TypeCheckStatus = TypeScript.TypeCheckStatus; + function aLexicallyEnclosesB(a, b) { + if(a.declAST && b && b.declAST && a.declAST.nodeType == TypeScript.NodeType.FuncDecl) { + return a.declAST.minChar <= b.declAST.minChar && a.declAST.limChar >= b.declAST.limChar; + } else { + return false; + } + } + TypeScript.aLexicallyEnclosesB = aLexicallyEnclosesB; + function aEnclosesB(a, b) { + while(a.container) { + if(a == b || aLexicallyEnclosesB(a.container, b)) { + return true; + } + a = a.container; + } + return false; + } + TypeScript.aEnclosesB = aEnclosesB; + var Symbol = (function () { + function Symbol(name, location, length, unitIndex) { + this.name = name; + this.location = location; + this.length = length; + this.unitIndex = unitIndex; + this.bound = false; + this.flags = TypeScript.SymbolFlags.None; + this.isObjectLitField = false; + this.declAST = null; + this.declModule = null; + this.passSymbolCreated = TypeScript.CompilerDiagnostics.analysisPass; + } + Symbol.prototype.instanceScope = function () { + return null; + }; + Symbol.prototype.isVariable = function () { + return false; + }; + Symbol.prototype.isMember = function () { + return false; + }; + Symbol.prototype.isInferenceSymbol = function () { + return false; + }; + Symbol.prototype.isWith = function () { + return false; + }; + Symbol.prototype.writeable = function () { + return false; + }; + Symbol.prototype.isType = function () { + return false; + }; + Symbol.prototype.getType = function () { + return null; + }; + Symbol.prototype.isAccessor = function () { + return false; + }; + Symbol.prototype.isInstanceProperty = function () { + return TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Property) && (!TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.ModuleMember)); + }; + Symbol.prototype.getTypeName = function (scope) { + return this.getTypeNameEx(scope).toString(); + }; + Symbol.prototype.getTypeNameEx = function (scope) { + return TypeScript.MemberName.create(this.toString()); + }; + Symbol.prototype.getOptionalNameString = function () { + return TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Optional) ? "?" : ""; + }; + Symbol.prototype.pathToRoot = function () { + var path = new Array(); + var node = this; + while(node && (node.name != TypeScript.globalId)) { + path[path.length] = node; + node = node.container; + } + return path; + }; + Symbol.prototype.findCommonAncestorPath = function (b) { + if(this.container == null) { + return new Array(); + } + var aPath = this.container.pathToRoot(); + var bPath; + if(b) { + bPath = b.pathToRoot(); + } else { + bPath = new Array(); + } + var commonNodeIndex = -1; + for(var i = 0, aLen = aPath.length; i < aLen; i++) { + var aNode = aPath[i]; + for(var j = 0, bLen = bPath.length; j < bLen; j++) { + var bNode = bPath[j]; + if(aNode == bNode) { + commonNodeIndex = i; + break; + } + } + if(commonNodeIndex >= 0) { + break; + } + } + if(commonNodeIndex >= 0) { + return aPath.slice(0, commonNodeIndex); + } else { + return aPath; + } + }; + Symbol.prototype.getPrettyName = function (scopeSymbol) { + return this.name; + }; + Symbol.prototype.scopeRelativeName = function (scope) { + if(scope == null) { + return this.getPrettyName(null) + this.getOptionalNameString(); + } + var lca = this.findCommonAncestorPath(scope.container); + var builder = ""; + for(var i = 0, len = lca.length; i < len; i++) { + var prettyName = lca[i].getPrettyName(i == len - 1 ? scope.container : lca[i + 1]); + builder = prettyName + "." + builder; + } + builder += this.getPrettyName(len == 0 ? scope.container : lca[0]) + this.getOptionalNameString(); + return builder; + }; + Symbol.prototype.fullName = function (scope) { + var scopeSymbol = !scope ? null : scope.container; + var scopeRootPath = !scopeSymbol ? [] : scopeSymbol.pathToRoot(); + var dynamicModuleRoot = null; + if(scopeRootPath.length > 0 && scopeRootPath[scopeRootPath.length - 1].declAST && scopeRootPath[scopeRootPath.length - 1].declAST.nodeType == TypeScript.NodeType.ModuleDeclaration && (scopeRootPath[scopeRootPath.length - 1].declAST).isWholeFile()) { + dynamicModuleRoot = scopeRootPath[scopeRootPath.length - 1]; + } + var builder = this.getPrettyName(scopeSymbol); + var ancestor = this.container; + while(ancestor && (ancestor.name != TypeScript.globalId) && ancestor != dynamicModuleRoot) { + builder = ancestor.getPrettyName(scopeSymbol) + "." + builder; + ancestor = ancestor.container; + } + return builder; + }; + Symbol.prototype.isExternallyVisible = function (checker) { + if(this == checker.gloMod) { + return true; + } + if(TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Private)) { + return false; + } + if(!TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Exported)) { + return this.container == checker.gloMod; + } + return this.container.isExternallyVisible(checker); + }; + Symbol.prototype.visible = function (scope, checker) { + if(checker == null || this.container == checker.gloMod) { + return true; + } + if(TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.ModuleMember)) { + if(TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Exported)) { + if(!TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Private)) { + return true; + } else { + return aEnclosesB(this, scope.container); + } + } else { + return checker && (checker.currentModDecl == this.declModule) || (checker.currentModDecl && checker.currentModDecl.mod && checker.currentModDecl.mod.symbol && this.declModule && this.declModule.mod && this.declModule.mod.symbol && aEnclosesB(checker.currentModDecl.mod.symbol, this.declModule.mod.symbol)); + } + } else { + var isFunction = this.declAST && this.declAST.nodeType == TypeScript.NodeType.FuncDecl; + var isMethod = isFunction && (this.declAST).isMethod(); + var isStaticFunction = isFunction && TypeScript.hasFlag((this.declAST).fncFlags, TypeScript.FncFlags.Static); + var isPrivateMethod = isMethod && TypeScript.hasFlag((this.declAST).fncFlags, TypeScript.FncFlags.Private); + var isAlias = this.isType() && (this).aliasLink; + if(this.isMember() || isMethod || isStaticFunction || isAlias) { + if(TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Private) || isPrivateMethod) { + if(scope.container == null && this.container != scope.container) { + return false; + } else { + return this.container == null ? true : aEnclosesB(scope.container, this.container); + } + } else { + return true; + } + } else if(this.container) { + return aEnclosesB(this, scope.container); + } else { + return true; + } + } + }; + Symbol.prototype.addRef = function (identifier) { + if(!this.refs) { + this.refs = []; + } + this.refs[this.refs.length] = identifier; + }; + Symbol.prototype.toString = function () { + if(this.name) { + return this.name; + } else { + return "_anonymous"; + } + }; + Symbol.prototype.print = function (outfile) { + outfile.Write(this.toString()); + }; + Symbol.prototype.specializeType = function (pattern, replacement, checker) { + throw new Error("please implement in derived class"); + }; + Symbol.prototype.setType = function (type) { + throw new Error("please implement in derived class"); + }; + Symbol.prototype.kind = function () { + throw new Error("please implement in derived class"); + }; + Symbol.prototype.getInterfaceDeclFromSymbol = function (checker) { + if(this.declAST != null) { + if(this.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) { + return this.declAST; + } else if(this.container != null && this.container != checker.gloMod && this.container.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) { + return this.container.declAST; + } + } + return null; + }; + Symbol.prototype.getVarDeclFromSymbol = function () { + if(this.declAST != null && this.declAST.nodeType == TypeScript.NodeType.VarDecl) { + return this.declAST; + } + return null; + }; + Symbol.prototype.getDocComments = function () { + if(this.declAST != null) { + return this.declAST.getDocComments(); + } + return []; + }; + Symbol.prototype.isStatic = function () { + return TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Static); + }; + return Symbol; + })(); + TypeScript.Symbol = Symbol; + var ValueLocation = (function () { + function ValueLocation() { } + return ValueLocation; + })(); + TypeScript.ValueLocation = ValueLocation; + var InferenceSymbol = (function (_super) { + __extends(InferenceSymbol, _super); + function InferenceSymbol(name, location, length, unitIndex) { + _super.call(this, name, location, length, unitIndex); + this.typeCheckStatus = TypeCheckStatus.NotStarted; + } + InferenceSymbol.prototype.isInferenceSymbol = function () { + return true; + }; + InferenceSymbol.prototype.transferVarFlags = function (varFlags) { + if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Ambient)) { + this.flags |= TypeScript.SymbolFlags.Ambient; + } + if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Constant)) { + this.flags |= TypeScript.SymbolFlags.Constant; + } + if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Static)) { + this.flags |= TypeScript.SymbolFlags.Static; + } + if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Property)) { + this.flags |= TypeScript.SymbolFlags.Property; + } + if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Private)) { + this.flags |= TypeScript.SymbolFlags.Private; + } + if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Public)) { + this.flags |= TypeScript.SymbolFlags.Public; + } + if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Readonly)) { + this.flags |= TypeScript.SymbolFlags.Readonly; + } + if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Exported)) { + this.flags |= TypeScript.SymbolFlags.Exported; + } + }; + return InferenceSymbol; + })(Symbol); + TypeScript.InferenceSymbol = InferenceSymbol; + var TypeSymbol = (function (_super) { + __extends(TypeSymbol, _super); + function TypeSymbol(locName, location, length, unitIndex, type) { + _super.call(this, locName, location, length, unitIndex); + this.type = type; + this.expansions = []; + this.expansionsDeclAST = []; + this.isDynamic = false; + this.isMethod = false; + this.aliasLink = null; + this.onlyReferencedAsTypeRef = TypeScript.optimizeModuleCodeGen; + this.prettyName = this.name; + } + TypeSymbol.prototype.addLocation = function (loc) { + if(this.additionalLocations == null) { + this.additionalLocations = []; + } + this.additionalLocations[this.additionalLocations.length] = loc; + }; + TypeSymbol.prototype.kind = function () { + return TypeScript.SymbolKind.Type; + }; + TypeSymbol.prototype.isType = function () { + return true; + }; + TypeSymbol.prototype.getType = function () { + return this.type; + }; + TypeSymbol.prototype.getTypeNameEx = function (scope) { + return this.type.getMemberTypeNameEx(this.name ? this.name + this.getOptionalNameString() : "", false, false, scope); + }; + TypeSymbol.prototype.instanceScope = function () { + if(!(this.type.typeFlags & TypeScript.TypeFlags.IsClass) && this.type.isClass()) { + return this.type.instanceType.constructorScope; + } else { + return this.type.containedScope; + } + }; + TypeSymbol.prototype.toString = function () { + var result = this.type.getTypeName(); + if(this.name) { + result = this.name + ":" + result; + } + return result; + }; + TypeSymbol.prototype.isClass = function () { + return this.instanceType != null; + }; + TypeSymbol.prototype.isFunction = function () { + return this.declAST != null && this.declAST.nodeType == TypeScript.NodeType.FuncDecl; + }; + TypeSymbol.prototype.specializeType = function (pattern, replacement, checker) { + if(this.type == pattern) { + return replacement.symbol; + } else { + var replType = this.type.specializeType(pattern, replacement, checker, false); + if(replType != this.type) { + var result = new TypeSymbol(this.name, -1, 0, -1, replType); + return result; + } else { + return this; + } + } + }; + TypeSymbol.prototype.getPrettyName = function (scopeSymbol) { + if(!!scopeSymbol && TypeScript.isQuoted(this.prettyName) && this.type.isModuleType()) { + var symbolPath = scopeSymbol.pathToRoot(); + var prettyName = this.getPrettyNameOfDynamicModule(symbolPath); + if(prettyName != null) { + return prettyName.name; + } + } + return this.prettyName; + }; + TypeSymbol.prototype.getPrettyNameOfDynamicModule = function (scopeSymbolPath) { + var scopeSymbolPathLength = scopeSymbolPath.length; + var externalSymbol = null; + if(scopeSymbolPath.length > 0 && scopeSymbolPath[scopeSymbolPathLength - 1].getType().isModuleType() && (scopeSymbolPath[scopeSymbolPathLength - 1]).isDynamic) { + if(scopeSymbolPathLength > 1 && scopeSymbolPath[scopeSymbolPathLength - 2].getType().isModuleType() && (scopeSymbolPath[scopeSymbolPathLength - 2]).isDynamic) { + var moduleType = scopeSymbolPath[scopeSymbolPathLength - 2].getType(); + externalSymbol = moduleType.findDynamicModuleName(this.type); + } + if(externalSymbol == null) { + var moduleType = scopeSymbolPath[scopeSymbolPathLength - 1].getType(); + externalSymbol = moduleType.findDynamicModuleName(this.type); + } + } + return externalSymbol; + }; + TypeSymbol.prototype.getDocComments = function () { + var comments = []; + if(this.declAST != null) { + comments = comments.concat(this.declAST.getDocComments()); + } + for(var i = 0; i < this.expansionsDeclAST.length; i++) { + comments = comments.concat(this.expansionsDeclAST[i].getDocComments()); + } + return comments; + }; + return TypeSymbol; + })(InferenceSymbol); + TypeScript.TypeSymbol = TypeSymbol; + var WithSymbol = (function (_super) { + __extends(WithSymbol, _super); + function WithSymbol(location, unitIndex, withType) { + _super.call(this, "with", location, 4, unitIndex, withType); + } + WithSymbol.prototype.isWith = function () { + return true; + }; + return WithSymbol; + })(TypeSymbol); + TypeScript.WithSymbol = WithSymbol; + var FieldSymbol = (function (_super) { + __extends(FieldSymbol, _super); + function FieldSymbol(name, location, unitIndex, canWrite, field) { + _super.call(this, name, location, name.length, unitIndex); + this.canWrite = canWrite; + this.field = field; + this.getter = null; + this.setter = null; + this.hasBeenEmitted = false; + this.name = name; + this.location = location; + } + FieldSymbol.prototype.kind = function () { + return TypeScript.SymbolKind.Field; + }; + FieldSymbol.prototype.writeable = function () { + return this.isAccessor() ? this.setter != null : this.canWrite; + }; + FieldSymbol.prototype.getType = function () { + return this.field.typeLink.type; + }; + FieldSymbol.prototype.getTypeNameEx = function (scope) { + return TypeScript.MemberName.create(this.field.typeLink.type ? this.field.typeLink.type.getScopedTypeNameEx(scope) : TypeScript.MemberName.create("any"), this.name + this.getOptionalNameString() + ": ", ""); + }; + FieldSymbol.prototype.isMember = function () { + return true; + }; + FieldSymbol.prototype.setType = function (type) { + this.field.typeLink.type = type; + }; + FieldSymbol.prototype.isAccessor = function () { + return this.getter != null || this.setter != null; + }; + FieldSymbol.prototype.isVariable = function () { + return true; + }; + FieldSymbol.prototype.toString = function () { + return this.getTypeNameEx(null).toString(); + }; + FieldSymbol.prototype.specializeType = function (pattern, replacement, checker) { + var rType = this.field.typeLink.type.specializeType(pattern, replacement, checker, false); + if(rType != this.field.typeLink.type) { + var fieldDef = new ValueLocation(); + var result = new FieldSymbol(this.name, 0, checker.locationInfo.unitIndex, this.canWrite, fieldDef); + result.flags = this.flags; + fieldDef.symbol = result; + fieldDef.typeLink = new TypeScript.TypeLink(); + result.setType(rType); + result.typeCheckStatus = TypeCheckStatus.Finished; + return result; + } else { + return this; + } + }; + FieldSymbol.prototype.getDocComments = function () { + if(this.getter != null || this.setter != null) { + var comments = []; + if(this.getter != null) { + comments = comments.concat(this.getter.getDocComments()); + } + if(this.setter != null) { + comments = comments.concat(this.setter.getDocComments()); + } + return comments; + } else if(this.declAST != null) { + return this.declAST.getDocComments(); + } + return []; + }; + return FieldSymbol; + })(InferenceSymbol); + TypeScript.FieldSymbol = FieldSymbol; + var ParameterSymbol = (function (_super) { + __extends(ParameterSymbol, _super); + function ParameterSymbol(name, location, unitIndex, parameter) { + _super.call(this, name, location, name.length, unitIndex); + this.parameter = parameter; + this.paramDocComment = null; + this.funcDecl = null; + this.argsOffset = (-1); + this.name = name; + this.location = location; + } + ParameterSymbol.prototype.kind = function () { + return TypeScript.SymbolKind.Parameter; + }; + ParameterSymbol.prototype.writeable = function () { + return true; + }; + ParameterSymbol.prototype.getType = function () { + return this.parameter.typeLink.type; + }; + ParameterSymbol.prototype.setType = function (type) { + this.parameter.typeLink.type = type; + }; + ParameterSymbol.prototype.isVariable = function () { + return true; + }; + ParameterSymbol.prototype.isOptional = function () { + if(this.parameter && this.parameter.symbol && this.parameter.symbol.declAST) { + return (this.parameter.symbol.declAST).isOptional; + } else { + return false; + } + }; + ParameterSymbol.prototype.getTypeNameEx = function (scope) { + return TypeScript.MemberName.create(this.getType().getScopedTypeNameEx(scope), this.name + (this.isOptional() ? "?" : "") + ": ", ""); + }; + ParameterSymbol.prototype.toString = function () { + return this.getTypeNameEx(null).toString(); + }; + ParameterSymbol.prototype.specializeType = function (pattern, replacement, checker) { + var rType = this.parameter.typeLink.type.specializeType(pattern, replacement, checker, false); + if(this.parameter.typeLink.type != rType) { + var paramDef = new ValueLocation(); + var result = new ParameterSymbol(this.name, 0, checker.locationInfo.unitIndex, paramDef); + paramDef.symbol = result; + result.setType(rType); + return result; + } else { + return this; + } + }; + ParameterSymbol.prototype.getParameterDocComments = function () { + if(!this.paramDocComment) { + var parameterComments = []; + if(this.funcDecl) { + var fncDocComments = this.funcDecl.getDocComments(); + var paramComment = TypeScript.Comment.getParameterDocCommentText(this.name, fncDocComments); + if(paramComment != "") { + parameterComments.push(paramComment); + } + } + var docComments = TypeScript.Comment.getDocCommentText(this.getDocComments()); + if(docComments != "") { + parameterComments.push(docComments); + } + this.paramDocComment = parameterComments.join("\n"); + } + return this.paramDocComment; + }; + ParameterSymbol.prototype.fullName = function () { + return this.name; + }; + return ParameterSymbol; + })(InferenceSymbol); + TypeScript.ParameterSymbol = ParameterSymbol; + var VariableSymbol = (function (_super) { + __extends(VariableSymbol, _super); + function VariableSymbol(name, location, unitIndex, variable) { + _super.call(this, name, location, name.length, unitIndex); + this.variable = variable; + } + VariableSymbol.prototype.kind = function () { + return TypeScript.SymbolKind.Variable; + }; + VariableSymbol.prototype.writeable = function () { + return true; + }; + VariableSymbol.prototype.getType = function () { + return this.variable.typeLink.type; + }; + VariableSymbol.prototype.getTypeNameEx = function (scope) { + return TypeScript.MemberName.create(this.getType().getScopedTypeNameEx(scope), this.name + ": ", ""); + }; + VariableSymbol.prototype.setType = function (type) { + this.variable.typeLink.type = type; + }; + VariableSymbol.prototype.isVariable = function () { + return true; + }; + return VariableSymbol; + })(InferenceSymbol); + TypeScript.VariableSymbol = VariableSymbol; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ScopedMembers = (function () { + function ScopedMembers(dualMembers) { + this.dualMembers = dualMembers; + this.allMembers = this.dualMembers; + this.publicMembers = this.dualMembers.primaryTable; + this.privateMembers = this.dualMembers.secondaryTable; + } + ScopedMembers.prototype.addPublicMember = function (key, data) { + return this.dualMembers.primaryTable.add(key, data); + }; + ScopedMembers.prototype.addPrivateMember = function (key, data) { + return this.dualMembers.secondaryTable.add(key, data); + }; + return ScopedMembers; + })(); + TypeScript.ScopedMembers = ScopedMembers; + (function (SymbolKind) { + SymbolKind._map = []; + SymbolKind._map[0] = "None"; + SymbolKind.None = 0; + SymbolKind._map[1] = "Type"; + SymbolKind.Type = 1; + SymbolKind._map[2] = "Field"; + SymbolKind.Field = 2; + SymbolKind._map[3] = "Parameter"; + SymbolKind.Parameter = 3; + SymbolKind._map[4] = "Variable"; + SymbolKind.Variable = 4; + })(TypeScript.SymbolKind || (TypeScript.SymbolKind = {})); + var SymbolKind = TypeScript.SymbolKind; + var SymbolScope = (function () { + function SymbolScope(container) { + this.container = container; + } + SymbolScope.prototype.printLabel = function () { + return "base"; + }; + SymbolScope.prototype.getAllSymbolNames = function (members) { + return [ + "please", + "implement", + "in", + "derived", + "classes" + ]; + }; + SymbolScope.prototype.getAllTypeSymbolNames = function (members) { + return [ + "please", + "implement", + "in", + "derived", + "classes" + ]; + }; + SymbolScope.prototype.getAllValueSymbolNames = function (members) { + return [ + "please", + "implement", + "in", + "derived", + "classes" + ]; + }; + SymbolScope.prototype.search = function (filter, name, publicOnly, typespace) { + return null; + }; + SymbolScope.prototype.findLocal = function (name, publicOnly, typespace) { + return null; + }; + SymbolScope.prototype.find = function (name, publicOnly, typespace) { + return null; + }; + SymbolScope.prototype.findImplementation = function (name, publicOnly, typespace) { + return null; + }; + SymbolScope.prototype.findAmbient = function (name, publicOnly, typespace) { + return null; + }; + SymbolScope.prototype.print = function (outfile) { + if(this.container) { + outfile.WriteLine(this.printLabel() + " scope with container: " + this.container.name + "..."); + } else { + outfile.WriteLine(this.printLabel() + " scope..."); + } + }; + SymbolScope.prototype.enter = function (container, ast, symbol, errorReporter, publicOnly, typespace, ambient) { + throw new Error("please implement in derived class"); + }; + SymbolScope.prototype.getTable = function () { + throw new Error("please implement in derived class"); + }; + return SymbolScope; + })(); + TypeScript.SymbolScope = SymbolScope; + function symbolCanBeUsed(sym, publicOnly) { + return publicOnly ? !(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Private) || (sym.declAST && sym.declAST.nodeType == TypeScript.NodeType.FuncDecl && TypeScript.hasFlag((sym.declAST).fncFlags, TypeScript.FncFlags.Private))) : true; + } + var SymbolAggregateScope = (function (_super) { + __extends(SymbolAggregateScope, _super); + function SymbolAggregateScope(container) { + _super.call(this, container); + this.valueCache = null; + this.valueImplCache = null; + this.valueAmbientCache = null; + this.typeCache = null; + this.typeImplCache = null; + this.typeAmbientCache = null; + this.parents = null; + this.container = container; + } + SymbolAggregateScope.prototype.printLabel = function () { + return "agg"; + }; + SymbolAggregateScope.prototype.search = function (filter, name, publicOnly, typespace) { + if(this.parents) { + for(var i = 0; i < this.parents.length; i++) { + var sym = this.parents[i].search(filter, name, publicOnly, typespace); + if(sym) { + if(filter.update(sym)) { + return sym; + } + } + } + } + return filter.result; + }; + SymbolAggregateScope.prototype.getAllSymbolNames = function (members) { + var result = []; + if(this.parents) { + for(var i = 0; i < this.parents.length; i++) { + var parentResult = this.parents[i].getAllSymbolNames(members); + if(parentResult) { + result = result.concat(parentResult); + } + } + } + return result; + }; + SymbolAggregateScope.prototype.getAllTypeSymbolNames = function (members) { + var result = []; + if(this.parents) { + for(var i = 0; i < this.parents.length; i++) { + var parentResult = this.parents[i].getAllTypeSymbolNames(members); + if(parentResult) { + result = result.concat(parentResult); + } + } + } + return result; + }; + SymbolAggregateScope.prototype.getAllValueSymbolNames = function (members) { + var result = []; + if(this.parents) { + for(var i = 0; i < this.parents.length; i++) { + var parentResult = this.parents[i].getAllValueSymbolNames(members); + if(parentResult) { + result = result.concat(parentResult); + } + } + } + return result; + }; + SymbolAggregateScope.prototype.print = function (outfile) { + _super.prototype.print.call(this, outfile); + if(this.parents) { + for(var i = 0; i < this.parents.length; i++) { + this.parents[i].print(outfile); + } + } + }; + SymbolAggregateScope.prototype.findImplementation = function (name, publicOnly, typespace) { + var sym = null; + var i = 0; + var implCache = this.valueImplCache; + if(typespace) { + implCache = this.typeImplCache; + } + if(implCache && ((sym = implCache.lookup(name)) != null) && (publicOnly ? !(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Private) || (sym.declAST && sym.declAST.nodeType == TypeScript.NodeType.FuncDecl && TypeScript.hasFlag((sym.declAST).fncFlags, TypeScript.FncFlags.Private))) : true)) { + return sym; + } + if(this.parents) { + for(i = 0; i < this.parents.length; i++) { + sym = this.parents[i].findImplementation(name, publicOnly, typespace); + if(sym) { + break; + } + } + } + if(implCache) { + if(typespace) { + this.typeImplCache = new TypeScript.StringHashTable(); + implCache = this.typeImplCache; + } else { + this.valueImplCache = new TypeScript.StringHashTable(); + implCache = this.valueImplCache; + } + } + implCache.add(name, sym); + return sym; + }; + SymbolAggregateScope.prototype.find = function (name, publicOnly, typespace) { + var sym = null; + var i = 0; + var cache = this.valueCache; + if(typespace) { + cache = this.typeCache; + } + if(cache && ((sym = cache.lookup(name)) != null) && (publicOnly ? !(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Private) || (sym.declAST && sym.declAST.nodeType == TypeScript.NodeType.FuncDecl && TypeScript.hasFlag((sym.declAST).fncFlags, TypeScript.FncFlags.Private))) : true)) { + return sym; + } + if(this.parents) { + for(i = 0; i < this.parents.length; i++) { + sym = this.parents[i].find(name, publicOnly, typespace); + if(sym) { + break; + } + } + } + if(cache == null) { + if(typespace) { + this.typeCache = new TypeScript.StringHashTable(); + cache = this.typeCache; + } else { + this.valueCache = new TypeScript.StringHashTable(); + cache = this.valueCache; + } + } + cache.add(name, sym); + return sym; + }; + SymbolAggregateScope.prototype.findAmbient = function (name, publicOnly, typespace) { + var sym = null; + var i = 0; + var cache = this.valueAmbientCache; + if(typespace) { + cache = this.typeAmbientCache; + } + if(cache && ((sym = cache.lookup(name)) != null)) { + return sym; + } + if(this.parents) { + for(i = 0; i < this.parents.length; i++) { + sym = this.parents[i].findAmbient(name, publicOnly, typespace); + if(sym) { + break; + } + } + } + if(cache == null) { + if(typespace) { + this.typeAmbientCache = new TypeScript.StringHashTable(); + cache = this.typeAmbientCache; + } else { + this.valueAmbientCache = new TypeScript.StringHashTable(); + cache = this.valueAmbientCache; + } + } + cache.add(name, sym); + return sym; + }; + SymbolAggregateScope.prototype.addParentScope = function (parent) { + if(this.parents == null) { + this.parents = new Array(); + } + this.parents[this.parents.length] = parent; + }; + return SymbolAggregateScope; + })(SymbolScope); + TypeScript.SymbolAggregateScope = SymbolAggregateScope; + var SymbolTableScope = (function (_super) { + __extends(SymbolTableScope, _super); + function SymbolTableScope(valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, container) { + _super.call(this, container); + this.valueMembers = valueMembers; + this.ambientValueMembers = ambientValueMembers; + this.enclosedTypes = enclosedTypes; + this.ambientEnclosedTypes = ambientEnclosedTypes; + this.container = container; + } + SymbolTableScope.prototype.printLabel = function () { + return "table"; + }; + SymbolTableScope.prototype.getAllSymbolNames = function (members) { + var result = this.getAllTypeSymbolNames(members); + return result.concat(this.getAllValueSymbolNames(members)); + }; + SymbolTableScope.prototype.getAllTypeSymbolNames = function (members) { + var result = []; + if(this.ambientEnclosedTypes) { + result = result.concat(this.ambientEnclosedTypes.allMembers.getAllKeys()); + } + if(this.enclosedTypes) { + result = result.concat(this.enclosedTypes.allMembers.getAllKeys()); + } + return result; + }; + SymbolTableScope.prototype.getAllValueSymbolNames = function (members) { + var result = []; + if(this.ambientValueMembers) { + result = result.concat(this.ambientValueMembers.allMembers.getAllKeys()); + } + if(this.valueMembers) { + result = result.concat(this.valueMembers.allMembers.getAllKeys()); + } + return result; + }; + SymbolTableScope.prototype.search = function (filter, name, publicOnly, typespace) { + var sym = this.find(name, publicOnly, typespace); + filter.update(sym); + return filter.result; + }; + SymbolTableScope.prototype.find = function (name, publicOnly, typespace) { + var table = null; + var ambientTable = null; + if(typespace) { + table = (this.enclosedTypes == null) ? null : publicOnly ? this.enclosedTypes.publicMembers : this.enclosedTypes.allMembers; + ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; + } else { + table = (this.valueMembers == null) ? null : publicOnly ? this.valueMembers.publicMembers : this.valueMembers.allMembers; + ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; + } + if(ambientTable) { + var s = ambientTable.lookup(name); + if(s) { + return s; + } + } + if(table) { + var s = table.lookup(name); + if(s) { + return s; + } + } + return null; + }; + SymbolTableScope.prototype.findAmbient = function (name, publicOnly, typespace) { + var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; + if(typespace) { + ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; + } + if(ambientTable) { + var s = ambientTable.lookup(name); + if(s) { + return s; + } + } + return null; + }; + SymbolTableScope.prototype.print = function (outfile) { + _super.prototype.print.call(this, outfile); + if(this.ambientValueMembers) { + this.ambientValueMembers.allMembers.map(function (key, sym, context) { + outfile.WriteLine(" " + key); + }, null); + } + if(this.valueMembers) { + this.valueMembers.allMembers.map(function (key, sym, context) { + outfile.WriteLine(" " + key); + }, null); + } + if(this.ambientEnclosedTypes) { + this.ambientEnclosedTypes.allMembers.map(function (key, sym, context) { + outfile.WriteLine(" " + key); + }, null); + } + if(this.enclosedTypes) { + this.enclosedTypes.allMembers.map(function (key, sym, context) { + outfile.WriteLine(" " + key); + }, null); + } + }; + SymbolTableScope.prototype.findImplementation = function (name, publicOnly, typespace) { + var sym = this.find(name, publicOnly, typespace); + if(sym) { + if(sym.kind() == SymbolKind.Type) { + var typeSym = sym; + if(!typeSym.type.hasImplementation()) { + sym = null; + } + } else if(sym.container) { + if(sym.container.kind() == SymbolKind.Type) { + var ctypeSym = sym.container; + if(!ctypeSym.type.hasImplementation()) { + sym = null; + } + } + } + } + return sym; + }; + SymbolTableScope.prototype.getTable = function () { + return this.valueMembers.publicMembers; + }; + return SymbolTableScope; + })(SymbolScope); + TypeScript.SymbolTableScope = SymbolTableScope; + var SymbolScopeBuilder = (function (_super) { + __extends(SymbolScopeBuilder, _super); + function SymbolScopeBuilder(valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, parent, container) { + _super.call(this, container); + this.valueMembers = valueMembers; + this.ambientValueMembers = ambientValueMembers; + this.enclosedTypes = enclosedTypes; + this.ambientEnclosedTypes = ambientEnclosedTypes; + this.parent = parent; + this.container = container; + } + SymbolScopeBuilder.prototype.printLabel = function () { + return "builder"; + }; + SymbolScopeBuilder.prototype.getAllSymbolNames = function (members) { + var result = this.getAllTypeSymbolNames(members); + return result.concat(this.getAllValueSymbolNames(members)); + }; + SymbolScopeBuilder.prototype.getAllTypeSymbolNames = function (members) { + var result = []; + if(this.ambientEnclosedTypes) { + result = result.concat(this.ambientEnclosedTypes.allMembers.getAllKeys()); + } + if(this.enclosedTypes) { + result = result.concat(this.enclosedTypes.allMembers.getAllKeys()); + } + if(!members && this.parent) { + var parentResult = this.parent.getAllTypeSymbolNames(members); + if(parentResult) { + result = result.concat(parentResult); + } + } + return result; + }; + SymbolScopeBuilder.prototype.getAllValueSymbolNames = function (members) { + var result = []; + if(this.ambientValueMembers) { + result = result.concat(this.ambientValueMembers.allMembers.getAllKeys()); + } + if(this.valueMembers) { + result = result.concat(this.valueMembers.allMembers.getAllKeys()); + } + if(!members && this.parent) { + var parentResult = this.parent.getAllValueSymbolNames(members); + if(parentResult) { + result = result.concat(parentResult); + } + } + return result; + }; + SymbolScopeBuilder.prototype.search = function (filter, name, publicOnly, typespace) { + var sym = null; + var table = (this.valueMembers == null) ? null : publicOnly ? this.valueMembers.publicMembers : this.valueMembers.allMembers; + var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; + if(typespace) { + table = (this.enclosedTypes == null) ? null : publicOnly ? this.enclosedTypes.publicMembers : this.enclosedTypes.allMembers; + ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; + } + if(ambientTable) { + if((sym = ambientTable.lookup(name)) != null) { + if(filter.update(sym)) { + return sym; + } + } + } + if(table) { + if((sym = table.lookup(name)) != null) { + if(filter.update(sym)) { + return sym; + } + } + } + if(this.parent) { + sym = this.parent.search(filter, name, publicOnly, typespace); + if(sym) { + if(filter.update(sym)) { + return sym; + } + } + } + return filter.result; + }; + SymbolScopeBuilder.prototype.print = function (outfile) { + _super.prototype.print.call(this, outfile); + if(this.ambientValueMembers) { + this.ambientValueMembers.allMembers.map(function (key, s, context) { + var sym = s; + outfile.WriteLine(" " + key); + }, null); + } + if(this.valueMembers) { + this.valueMembers.allMembers.map(function (key, s, context) { + var sym = s; + outfile.WriteLine(" " + key); + }, null); + } + if(this.ambientEnclosedTypes) { + this.ambientEnclosedTypes.allMembers.map(function (key, s, context) { + var sym = s; + outfile.WriteLine(" " + key); + }, null); + } + if(this.enclosedTypes) { + this.enclosedTypes.allMembers.map(function (key, s, context) { + var sym = s; + outfile.WriteLine(" " + key); + }, null); + } + if(this.parent) { + this.parent.print(outfile); + } + }; + SymbolScopeBuilder.prototype.find = function (name, publicOnly, typespace) { + var sym = null; + var table = (this.valueMembers == null) ? null : publicOnly ? this.valueMembers.publicMembers : this.valueMembers.allMembers; + var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; + if(typespace) { + table = (this.enclosedTypes == null) ? null : publicOnly ? this.enclosedTypes.publicMembers : this.enclosedTypes.allMembers; + ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; + } + if(ambientTable && ((sym = ambientTable.lookup(name)) != null)) { + return sym; + } + if(table && ((sym = table.lookup(name)) != null)) { + return sym; + } + if(this.parent) { + return this.parent.find(name, publicOnly, typespace); + } + return null; + }; + SymbolScopeBuilder.prototype.findAmbient = function (name, publicOnly, typespace) { + var sym = null; + var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; + if(typespace) { + ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; + } + if(ambientTable && ((sym = ambientTable.lookup(name)) != null)) { + return sym; + } + if(this.parent) { + return this.parent.findAmbient(name, publicOnly, typespace); + } + return null; + }; + SymbolScopeBuilder.prototype.findLocal = function (name, publicOnly, typespace) { + var sym = null; + var table = (this.valueMembers == null) ? null : publicOnly ? this.valueMembers.publicMembers : this.valueMembers.allMembers; + var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; + if(typespace) { + table = (this.enclosedTypes == null) ? null : publicOnly ? this.enclosedTypes.publicMembers : this.enclosedTypes.allMembers; + ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; + } + if(table) { + if((sym = table.lookup(name)) != null) { + if(sym) { + return sym; + } + } + } + if(ambientTable) { + if((sym = ambientTable.lookup(name)) != null) { + if(sym) { + return sym; + } + } + } + return null; + }; + SymbolScopeBuilder.prototype.enter = function (container, ast, symbol, errorReporter, insertAsPublic, typespace, ambient) { + var table = null; + if(ambient) { + if(typespace) { + table = (this.ambientEnclosedTypes == null) ? null : insertAsPublic ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.privateMembers; + } else { + table = (this.ambientValueMembers == null) ? null : insertAsPublic ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.privateMembers; + } + } else { + if(typespace) { + table = (this.enclosedTypes == null) ? null : insertAsPublic ? this.enclosedTypes.publicMembers : this.enclosedTypes.privateMembers; + } else { + table = (this.valueMembers == null) ? null : insertAsPublic ? this.valueMembers.publicMembers : this.valueMembers.privateMembers; + } + } + if(table) { + if(!table.add(symbol.name, symbol)) { + errorReporter.duplicateIdentifier(ast, symbol.name); + } + } else { + TypeScript.CompilerDiagnostics.Alert("YYYYY"); + } + symbol.container = container; + }; + SymbolScopeBuilder.prototype.getTable = function () { + return this.valueMembers.allMembers; + }; + return SymbolScopeBuilder; + })(SymbolScope); + TypeScript.SymbolScopeBuilder = SymbolScopeBuilder; + var FilteredSymbolScope = (function (_super) { + __extends(FilteredSymbolScope, _super); + function FilteredSymbolScope(scope, container, filter) { + _super.call(this, container); + this.scope = scope; + this.filter = filter; + } + FilteredSymbolScope.prototype.print = function (outfile) { + this.scope.print(outfile); + }; + FilteredSymbolScope.prototype.find = function (name, publicOnly, typespace) { + this.filter.reset(); + return this.scope.search(this.filter, name, publicOnly, typespace); + }; + FilteredSymbolScope.prototype.findLocal = function (name, publicOnly, typespace) { + return this.scope.findLocal(name, publicOnly, typespace); + }; + return FilteredSymbolScope; + })(SymbolScope); + TypeScript.FilteredSymbolScope = FilteredSymbolScope; + var FilteredSymbolScopeBuilder = (function (_super) { + __extends(FilteredSymbolScopeBuilder, _super); + function FilteredSymbolScopeBuilder(valueMembers, parent, container, filter) { + _super.call(this, valueMembers, null, null, null, parent, container); + this.filter = filter; + } + FilteredSymbolScopeBuilder.prototype.findLocal = function (name, publicOnly, typespace) { + var sym = _super.prototype.findLocal.call(this, name, publicOnly, typespace); + if(sym) { + if(!this.filter(sym)) { + return null; + } + } + return sym; + }; + FilteredSymbolScopeBuilder.prototype.search = function (filter, name, publicOnly, typespace) { + throw new Error("please implement"); + }; + FilteredSymbolScopeBuilder.prototype.find = function (name, publicOnly, typespace) { + var sym = _super.prototype.findLocal.call(this, name, publicOnly, typespace); + if(sym) { + if(!this.filter(sym)) { + return null; + } + } + return _super.prototype.find.call(this, name, publicOnly, typespace); + }; + return FilteredSymbolScopeBuilder; + })(SymbolScopeBuilder); + TypeScript.FilteredSymbolScopeBuilder = FilteredSymbolScopeBuilder; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (TokenID) { + TokenID._map = []; + TokenID._map[0] = "Any"; + TokenID.Any = 0; + TokenID._map[1] = "Bool"; + TokenID.Bool = 1; + TokenID._map[2] = "Break"; + TokenID.Break = 2; + TokenID._map[3] = "Case"; + TokenID.Case = 3; + TokenID._map[4] = "Catch"; + TokenID.Catch = 4; + TokenID._map[5] = "Class"; + TokenID.Class = 5; + TokenID._map[6] = "Const"; + TokenID.Const = 6; + TokenID._map[7] = "Continue"; + TokenID.Continue = 7; + TokenID._map[8] = "Debugger"; + TokenID.Debugger = 8; + TokenID._map[9] = "Default"; + TokenID.Default = 9; + TokenID._map[10] = "Delete"; + TokenID.Delete = 10; + TokenID._map[11] = "Do"; + TokenID.Do = 11; + TokenID._map[12] = "Else"; + TokenID.Else = 12; + TokenID._map[13] = "Enum"; + TokenID.Enum = 13; + TokenID._map[14] = "Export"; + TokenID.Export = 14; + TokenID._map[15] = "Extends"; + TokenID.Extends = 15; + TokenID._map[16] = "Declare"; + TokenID.Declare = 16; + TokenID._map[17] = "False"; + TokenID.False = 17; + TokenID._map[18] = "Finally"; + TokenID.Finally = 18; + TokenID._map[19] = "For"; + TokenID.For = 19; + TokenID._map[20] = "Function"; + TokenID.Function = 20; + TokenID._map[21] = "Constructor"; + TokenID.Constructor = 21; + TokenID._map[22] = "Get"; + TokenID.Get = 22; + TokenID._map[23] = "If"; + TokenID.If = 23; + TokenID._map[24] = "Implements"; + TokenID.Implements = 24; + TokenID._map[25] = "Import"; + TokenID.Import = 25; + TokenID._map[26] = "In"; + TokenID.In = 26; + TokenID._map[27] = "InstanceOf"; + TokenID.InstanceOf = 27; + TokenID._map[28] = "Interface"; + TokenID.Interface = 28; + TokenID._map[29] = "Let"; + TokenID.Let = 29; + TokenID._map[30] = "Module"; + TokenID.Module = 30; + TokenID._map[31] = "New"; + TokenID.New = 31; + TokenID._map[32] = "Number"; + TokenID.Number = 32; + TokenID._map[33] = "Null"; + TokenID.Null = 33; + TokenID._map[34] = "Package"; + TokenID.Package = 34; + TokenID._map[35] = "Private"; + TokenID.Private = 35; + TokenID._map[36] = "Protected"; + TokenID.Protected = 36; + TokenID._map[37] = "Public"; + TokenID.Public = 37; + TokenID._map[38] = "Return"; + TokenID.Return = 38; + TokenID._map[39] = "Set"; + TokenID.Set = 39; + TokenID._map[40] = "Static"; + TokenID.Static = 40; + TokenID._map[41] = "String"; + TokenID.String = 41; + TokenID._map[42] = "Super"; + TokenID.Super = 42; + TokenID._map[43] = "Switch"; + TokenID.Switch = 43; + TokenID._map[44] = "This"; + TokenID.This = 44; + TokenID._map[45] = "Throw"; + TokenID.Throw = 45; + TokenID._map[46] = "True"; + TokenID.True = 46; + TokenID._map[47] = "Try"; + TokenID.Try = 47; + TokenID._map[48] = "TypeOf"; + TokenID.TypeOf = 48; + TokenID._map[49] = "Var"; + TokenID.Var = 49; + TokenID._map[50] = "Void"; + TokenID.Void = 50; + TokenID._map[51] = "With"; + TokenID.With = 51; + TokenID._map[52] = "While"; + TokenID.While = 52; + TokenID._map[53] = "Yield"; + TokenID.Yield = 53; + TokenID._map[54] = "Semicolon"; + TokenID.Semicolon = 54; + TokenID._map[55] = "OpenParen"; + TokenID.OpenParen = 55; + TokenID._map[56] = "CloseParen"; + TokenID.CloseParen = 56; + TokenID._map[57] = "OpenBracket"; + TokenID.OpenBracket = 57; + TokenID._map[58] = "CloseBracket"; + TokenID.CloseBracket = 58; + TokenID._map[59] = "OpenBrace"; + TokenID.OpenBrace = 59; + TokenID._map[60] = "CloseBrace"; + TokenID.CloseBrace = 60; + TokenID._map[61] = "Comma"; + TokenID.Comma = 61; + TokenID._map[62] = "Equals"; + TokenID.Equals = 62; + TokenID._map[63] = "PlusEquals"; + TokenID.PlusEquals = 63; + TokenID._map[64] = "MinusEquals"; + TokenID.MinusEquals = 64; + TokenID._map[65] = "AsteriskEquals"; + TokenID.AsteriskEquals = 65; + TokenID._map[66] = "SlashEquals"; + TokenID.SlashEquals = 66; + TokenID._map[67] = "PercentEquals"; + TokenID.PercentEquals = 67; + TokenID._map[68] = "AmpersandEquals"; + TokenID.AmpersandEquals = 68; + TokenID._map[69] = "CaretEquals"; + TokenID.CaretEquals = 69; + TokenID._map[70] = "BarEquals"; + TokenID.BarEquals = 70; + TokenID._map[71] = "LessThanLessThanEquals"; + TokenID.LessThanLessThanEquals = 71; + TokenID._map[72] = "GreaterThanGreaterThanEquals"; + TokenID.GreaterThanGreaterThanEquals = 72; + TokenID._map[73] = "GreaterThanGreaterThanGreaterThanEquals"; + TokenID.GreaterThanGreaterThanGreaterThanEquals = 73; + TokenID._map[74] = "Question"; + TokenID.Question = 74; + TokenID._map[75] = "Colon"; + TokenID.Colon = 75; + TokenID._map[76] = "BarBar"; + TokenID.BarBar = 76; + TokenID._map[77] = "AmpersandAmpersand"; + TokenID.AmpersandAmpersand = 77; + TokenID._map[78] = "Bar"; + TokenID.Bar = 78; + TokenID._map[79] = "Caret"; + TokenID.Caret = 79; + TokenID._map[80] = "And"; + TokenID.And = 80; + TokenID._map[81] = "EqualsEquals"; + TokenID.EqualsEquals = 81; + TokenID._map[82] = "ExclamationEquals"; + TokenID.ExclamationEquals = 82; + TokenID._map[83] = "EqualsEqualsEquals"; + TokenID.EqualsEqualsEquals = 83; + TokenID._map[84] = "ExclamationEqualsEquals"; + TokenID.ExclamationEqualsEquals = 84; + TokenID._map[85] = "LessThan"; + TokenID.LessThan = 85; + TokenID._map[86] = "LessThanEquals"; + TokenID.LessThanEquals = 86; + TokenID._map[87] = "GreaterThan"; + TokenID.GreaterThan = 87; + TokenID._map[88] = "GreaterThanEquals"; + TokenID.GreaterThanEquals = 88; + TokenID._map[89] = "LessThanLessThan"; + TokenID.LessThanLessThan = 89; + TokenID._map[90] = "GreaterThanGreaterThan"; + TokenID.GreaterThanGreaterThan = 90; + TokenID._map[91] = "GreaterThanGreaterThanGreaterThan"; + TokenID.GreaterThanGreaterThanGreaterThan = 91; + TokenID._map[92] = "Plus"; + TokenID.Plus = 92; + TokenID._map[93] = "Minus"; + TokenID.Minus = 93; + TokenID._map[94] = "Asterisk"; + TokenID.Asterisk = 94; + TokenID._map[95] = "Slash"; + TokenID.Slash = 95; + TokenID._map[96] = "Percent"; + TokenID.Percent = 96; + TokenID._map[97] = "Tilde"; + TokenID.Tilde = 97; + TokenID._map[98] = "Exclamation"; + TokenID.Exclamation = 98; + TokenID._map[99] = "PlusPlus"; + TokenID.PlusPlus = 99; + TokenID._map[100] = "MinusMinus"; + TokenID.MinusMinus = 100; + TokenID._map[101] = "Dot"; + TokenID.Dot = 101; + TokenID._map[102] = "DotDotDot"; + TokenID.DotDotDot = 102; + TokenID._map[103] = "Error"; + TokenID.Error = 103; + TokenID._map[104] = "EndOfFile"; + TokenID.EndOfFile = 104; + TokenID._map[105] = "EqualsGreaterThan"; + TokenID.EqualsGreaterThan = 105; + TokenID._map[106] = "Identifier"; + TokenID.Identifier = 106; + TokenID._map[107] = "StringLiteral"; + TokenID.StringLiteral = 107; + TokenID._map[108] = "RegularExpressionLiteral"; + TokenID.RegularExpressionLiteral = 108; + TokenID._map[109] = "NumberLiteral"; + TokenID.NumberLiteral = 109; + TokenID._map[110] = "Whitespace"; + TokenID.Whitespace = 110; + TokenID._map[111] = "Comment"; + TokenID.Comment = 111; + TokenID._map[112] = "Lim"; + TokenID.Lim = 112; + TokenID.LimFixed = TokenID.EqualsGreaterThan; + TokenID.LimKeyword = TokenID.Yield; + })(TypeScript.TokenID || (TypeScript.TokenID = {})); + var TokenID = TypeScript.TokenID; + TypeScript.tokenTable = new Array(); + TypeScript.nodeTypeTable = new Array(); + TypeScript.nodeTypeToTokTable = new Array(); + TypeScript.noRegexTable = new Array(); + TypeScript.noRegexTable[TokenID.Identifier] = true; + TypeScript.noRegexTable[TokenID.StringLiteral] = true; + TypeScript.noRegexTable[TokenID.NumberLiteral] = true; + TypeScript.noRegexTable[TokenID.RegularExpressionLiteral] = true; + TypeScript.noRegexTable[TokenID.This] = true; + TypeScript.noRegexTable[TokenID.PlusPlus] = true; + TypeScript.noRegexTable[TokenID.MinusMinus] = true; + TypeScript.noRegexTable[TokenID.CloseParen] = true; + TypeScript.noRegexTable[TokenID.CloseBracket] = true; + TypeScript.noRegexTable[TokenID.CloseBrace] = true; + TypeScript.noRegexTable[TokenID.True] = true; + TypeScript.noRegexTable[TokenID.False] = true; + (function (OperatorPrecedence) { + OperatorPrecedence._map = []; + OperatorPrecedence._map[0] = "None"; + OperatorPrecedence.None = 0; + OperatorPrecedence._map[1] = "Comma"; + OperatorPrecedence.Comma = 1; + OperatorPrecedence._map[2] = "Assignment"; + OperatorPrecedence.Assignment = 2; + OperatorPrecedence._map[3] = "Conditional"; + OperatorPrecedence.Conditional = 3; + OperatorPrecedence._map[4] = "LogicalOr"; + OperatorPrecedence.LogicalOr = 4; + OperatorPrecedence._map[5] = "LogicalAnd"; + OperatorPrecedence.LogicalAnd = 5; + OperatorPrecedence._map[6] = "BitwiseOr"; + OperatorPrecedence.BitwiseOr = 6; + OperatorPrecedence._map[7] = "BitwiseExclusiveOr"; + OperatorPrecedence.BitwiseExclusiveOr = 7; + OperatorPrecedence._map[8] = "BitwiseAnd"; + OperatorPrecedence.BitwiseAnd = 8; + OperatorPrecedence._map[9] = "Equality"; + OperatorPrecedence.Equality = 9; + OperatorPrecedence._map[10] = "Relational"; + OperatorPrecedence.Relational = 10; + OperatorPrecedence._map[11] = "Shift"; + OperatorPrecedence.Shift = 11; + OperatorPrecedence._map[12] = "Additive"; + OperatorPrecedence.Additive = 12; + OperatorPrecedence._map[13] = "Multiplicative"; + OperatorPrecedence.Multiplicative = 13; + OperatorPrecedence._map[14] = "Unary"; + OperatorPrecedence.Unary = 14; + OperatorPrecedence._map[15] = "Lim"; + OperatorPrecedence.Lim = 15; + })(TypeScript.OperatorPrecedence || (TypeScript.OperatorPrecedence = {})); + var OperatorPrecedence = TypeScript.OperatorPrecedence; + (function (Reservation) { + Reservation._map = []; + Reservation.None = 0; + Reservation.Javascript = 1; + Reservation.JavascriptFuture = 2; + Reservation.TypeScript = 4; + Reservation.JavascriptFutureStrict = 8; + Reservation.TypeScriptAndJS = Reservation.Javascript | Reservation.TypeScript; + Reservation.TypeScriptAndJSFuture = Reservation.JavascriptFuture | Reservation.TypeScript; + Reservation.TypeScriptAndJSFutureStrict = Reservation.JavascriptFutureStrict | Reservation.TypeScript; + })(TypeScript.Reservation || (TypeScript.Reservation = {})); + var Reservation = TypeScript.Reservation; + var TokenInfo = (function () { + function TokenInfo(tokenId, reservation, binopPrecedence, binopNodeType, unopPrecedence, unopNodeType, text, ers) { + this.tokenId = tokenId; + this.reservation = reservation; + this.binopPrecedence = binopPrecedence; + this.binopNodeType = binopNodeType; + this.unopPrecedence = unopPrecedence; + this.unopNodeType = unopNodeType; + this.text = text; + this.ers = ers; + } + return TokenInfo; + })(); + TypeScript.TokenInfo = TokenInfo; + function setTokenInfo(tokenId, reservation, binopPrecedence, binopNodeType, unopPrecedence, unopNodeType, text, ers) { + if(tokenId !== undefined) { + TypeScript.tokenTable[tokenId] = new TokenInfo(tokenId, reservation, binopPrecedence, binopNodeType, unopPrecedence, unopNodeType, text, ers); + if(binopNodeType != TypeScript.NodeType.None) { + TypeScript.nodeTypeTable[binopNodeType] = text; + TypeScript.nodeTypeToTokTable[binopNodeType] = tokenId; + } + if(unopNodeType != TypeScript.NodeType.None) { + TypeScript.nodeTypeTable[unopNodeType] = text; + } + } + } + setTokenInfo(TokenID.Any, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "any", TypeScript.ErrorRecoverySet.PrimType); + setTokenInfo(TokenID.Bool, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "bool", TypeScript.ErrorRecoverySet.PrimType); + setTokenInfo(TokenID.Break, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "break", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.Case, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "case", TypeScript.ErrorRecoverySet.SCase); + setTokenInfo(TokenID.Catch, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "catch", TypeScript.ErrorRecoverySet.Catch); + setTokenInfo(TokenID.Class, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "class", TypeScript.ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.Const, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "const", TypeScript.ErrorRecoverySet.Var); + setTokenInfo(TokenID.Continue, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "continue", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.Debugger, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.Debugger, "debugger", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.Default, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "default", TypeScript.ErrorRecoverySet.SCase); + setTokenInfo(TokenID.Delete, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.Delete, "delete", TypeScript.ErrorRecoverySet.Prefix); + setTokenInfo(TokenID.Do, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "do", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.Else, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "else", TypeScript.ErrorRecoverySet.Else); + setTokenInfo(TokenID.Enum, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "enum", TypeScript.ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.Export, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "export", TypeScript.ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.Extends, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "extends", TypeScript.ErrorRecoverySet.None); + setTokenInfo(TokenID.Declare, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "declare", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.False, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "false", TypeScript.ErrorRecoverySet.RLit); + setTokenInfo(TokenID.Finally, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "finally", TypeScript.ErrorRecoverySet.Catch); + setTokenInfo(TokenID.For, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "for", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.Function, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "function", TypeScript.ErrorRecoverySet.Func); + setTokenInfo(TokenID.Constructor, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "constructor", TypeScript.ErrorRecoverySet.Func); + setTokenInfo(TokenID.Get, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "get", TypeScript.ErrorRecoverySet.Func); + setTokenInfo(TokenID.Set, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "set", TypeScript.ErrorRecoverySet.Func); + setTokenInfo(TokenID.If, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "if", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.Implements, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "implements", TypeScript.ErrorRecoverySet.None); + setTokenInfo(TokenID.Import, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "import", TypeScript.ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.In, Reservation.TypeScriptAndJS, OperatorPrecedence.Relational, TypeScript.NodeType.In, OperatorPrecedence.None, TypeScript.NodeType.None, "in", TypeScript.ErrorRecoverySet.None); + setTokenInfo(TokenID.InstanceOf, Reservation.TypeScriptAndJS, OperatorPrecedence.Relational, TypeScript.NodeType.InstOf, OperatorPrecedence.None, TypeScript.NodeType.None, "instanceof", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.Interface, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "interface", TypeScript.ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.Let, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "let", TypeScript.ErrorRecoverySet.None); + setTokenInfo(TokenID.Module, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "module", TypeScript.ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.New, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "new", TypeScript.ErrorRecoverySet.PreOp); + setTokenInfo(TokenID.Number, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "number", TypeScript.ErrorRecoverySet.PrimType); + setTokenInfo(TokenID.Null, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "null", TypeScript.ErrorRecoverySet.RLit); + setTokenInfo(TokenID.Package, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "package", TypeScript.ErrorRecoverySet.None); + setTokenInfo(TokenID.Private, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "private", TypeScript.ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.Protected, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "protected", TypeScript.ErrorRecoverySet.None); + setTokenInfo(TokenID.Public, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "public", TypeScript.ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.Return, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "return", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.Static, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "static", TypeScript.ErrorRecoverySet.None); + setTokenInfo(TokenID.String, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "string", TypeScript.ErrorRecoverySet.PrimType); + setTokenInfo(TokenID.Super, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "super", TypeScript.ErrorRecoverySet.RLit); + setTokenInfo(TokenID.Switch, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "switch", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.This, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "this", TypeScript.ErrorRecoverySet.RLit); + setTokenInfo(TokenID.Throw, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "throw", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.True, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "true", TypeScript.ErrorRecoverySet.RLit); + setTokenInfo(TokenID.Try, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "try", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.TypeOf, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.Typeof, "typeof", TypeScript.ErrorRecoverySet.Prefix); + setTokenInfo(TokenID.Var, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "var", TypeScript.ErrorRecoverySet.Var); + setTokenInfo(TokenID.Void, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.Void, "void", TypeScript.ErrorRecoverySet.Prefix); + setTokenInfo(TokenID.With, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.With, "with", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.While, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "while", TypeScript.ErrorRecoverySet.While); + setTokenInfo(TokenID.Yield, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "yield", TypeScript.ErrorRecoverySet.None); + setTokenInfo(TokenID.Identifier, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "identifier", TypeScript.ErrorRecoverySet.ID); + setTokenInfo(TokenID.NumberLiteral, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "numberLiteral", TypeScript.ErrorRecoverySet.Literal); + setTokenInfo(TokenID.RegularExpressionLiteral, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "regex", TypeScript.ErrorRecoverySet.RegExp); + setTokenInfo(TokenID.StringLiteral, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "qstring", TypeScript.ErrorRecoverySet.Literal); + setTokenInfo(TokenID.Semicolon, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, ";", TypeScript.ErrorRecoverySet.SColon); + setTokenInfo(TokenID.CloseParen, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, ")", TypeScript.ErrorRecoverySet.RParen); + setTokenInfo(TokenID.CloseBracket, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "]", TypeScript.ErrorRecoverySet.RBrack); + setTokenInfo(TokenID.OpenBrace, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "{", TypeScript.ErrorRecoverySet.LCurly); + setTokenInfo(TokenID.CloseBrace, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "}", TypeScript.ErrorRecoverySet.RCurly); + setTokenInfo(TokenID.DotDotDot, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "...", TypeScript.ErrorRecoverySet.None); + setTokenInfo(TokenID.Comma, Reservation.None, OperatorPrecedence.Comma, TypeScript.NodeType.Comma, OperatorPrecedence.None, TypeScript.NodeType.None, ",", TypeScript.ErrorRecoverySet.Comma); + setTokenInfo(TokenID.Equals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.Asg, OperatorPrecedence.None, TypeScript.NodeType.None, "=", TypeScript.ErrorRecoverySet.Asg); + setTokenInfo(TokenID.PlusEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgAdd, OperatorPrecedence.None, TypeScript.NodeType.None, "+=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.MinusEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgSub, OperatorPrecedence.None, TypeScript.NodeType.None, "-=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.AsteriskEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgMul, OperatorPrecedence.None, TypeScript.NodeType.None, "*=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.SlashEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgDiv, OperatorPrecedence.None, TypeScript.NodeType.None, "/=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.PercentEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgMod, OperatorPrecedence.None, TypeScript.NodeType.None, "%=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.AmpersandEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgAnd, OperatorPrecedence.None, TypeScript.NodeType.None, "&=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.CaretEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgXor, OperatorPrecedence.None, TypeScript.NodeType.None, "^=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.BarEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgOr, OperatorPrecedence.None, TypeScript.NodeType.None, "|=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.LessThanLessThanEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgLsh, OperatorPrecedence.None, TypeScript.NodeType.None, "<<=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.GreaterThanGreaterThanEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgRsh, OperatorPrecedence.None, TypeScript.NodeType.None, ">>=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.GreaterThanGreaterThanGreaterThanEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgRs2, OperatorPrecedence.None, TypeScript.NodeType.None, ">>>=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.Question, Reservation.None, OperatorPrecedence.Conditional, TypeScript.NodeType.ConditionalExpression, OperatorPrecedence.None, TypeScript.NodeType.None, "?", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.Colon, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, ":", TypeScript.ErrorRecoverySet.Colon); + setTokenInfo(TokenID.BarBar, Reservation.None, OperatorPrecedence.LogicalOr, TypeScript.NodeType.LogOr, OperatorPrecedence.None, TypeScript.NodeType.None, "||", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.AmpersandAmpersand, Reservation.None, OperatorPrecedence.LogicalAnd, TypeScript.NodeType.LogAnd, OperatorPrecedence.None, TypeScript.NodeType.None, "&&", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.Bar, Reservation.None, OperatorPrecedence.BitwiseOr, TypeScript.NodeType.Or, OperatorPrecedence.None, TypeScript.NodeType.None, "|", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.Caret, Reservation.None, OperatorPrecedence.BitwiseExclusiveOr, TypeScript.NodeType.Xor, OperatorPrecedence.None, TypeScript.NodeType.None, "^", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.And, Reservation.None, OperatorPrecedence.BitwiseAnd, TypeScript.NodeType.And, OperatorPrecedence.None, TypeScript.NodeType.None, "&", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.EqualsEquals, Reservation.None, OperatorPrecedence.Equality, TypeScript.NodeType.Eq, OperatorPrecedence.None, TypeScript.NodeType.None, "==", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.ExclamationEquals, Reservation.None, OperatorPrecedence.Equality, TypeScript.NodeType.Ne, OperatorPrecedence.None, TypeScript.NodeType.None, "!=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.EqualsEqualsEquals, Reservation.None, OperatorPrecedence.Equality, TypeScript.NodeType.Eqv, OperatorPrecedence.None, TypeScript.NodeType.None, "===", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.ExclamationEqualsEquals, Reservation.None, OperatorPrecedence.Equality, TypeScript.NodeType.NEqv, OperatorPrecedence.None, TypeScript.NodeType.None, "!==", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.LessThan, Reservation.None, OperatorPrecedence.Relational, TypeScript.NodeType.Lt, OperatorPrecedence.None, TypeScript.NodeType.None, "<", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.LessThanEquals, Reservation.None, OperatorPrecedence.Relational, TypeScript.NodeType.Le, OperatorPrecedence.None, TypeScript.NodeType.None, "<=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.GreaterThan, Reservation.None, OperatorPrecedence.Relational, TypeScript.NodeType.Gt, OperatorPrecedence.None, TypeScript.NodeType.None, ">", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.GreaterThanEquals, Reservation.None, OperatorPrecedence.Relational, TypeScript.NodeType.Ge, OperatorPrecedence.None, TypeScript.NodeType.None, ">=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.LessThanLessThan, Reservation.None, OperatorPrecedence.Shift, TypeScript.NodeType.Lsh, OperatorPrecedence.None, TypeScript.NodeType.None, "<<", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.GreaterThanGreaterThan, Reservation.None, OperatorPrecedence.Shift, TypeScript.NodeType.Rsh, OperatorPrecedence.None, TypeScript.NodeType.None, ">>", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.GreaterThanGreaterThanGreaterThan, Reservation.None, OperatorPrecedence.Shift, TypeScript.NodeType.Rs2, OperatorPrecedence.None, TypeScript.NodeType.None, ">>>", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.Plus, Reservation.None, OperatorPrecedence.Additive, TypeScript.NodeType.Add, OperatorPrecedence.Unary, TypeScript.NodeType.Pos, "+", TypeScript.ErrorRecoverySet.AddOp); + setTokenInfo(TokenID.Minus, Reservation.None, OperatorPrecedence.Additive, TypeScript.NodeType.Sub, OperatorPrecedence.Unary, TypeScript.NodeType.Neg, "-", TypeScript.ErrorRecoverySet.AddOp); + setTokenInfo(TokenID.Asterisk, Reservation.None, OperatorPrecedence.Multiplicative, TypeScript.NodeType.Mul, OperatorPrecedence.None, TypeScript.NodeType.None, "*", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.Slash, Reservation.None, OperatorPrecedence.Multiplicative, TypeScript.NodeType.Div, OperatorPrecedence.None, TypeScript.NodeType.None, "/", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.Percent, Reservation.None, OperatorPrecedence.Multiplicative, TypeScript.NodeType.Mod, OperatorPrecedence.None, TypeScript.NodeType.None, "%", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.Tilde, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.Not, "~", TypeScript.ErrorRecoverySet.PreOp); + setTokenInfo(TokenID.Exclamation, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.LogNot, "!", TypeScript.ErrorRecoverySet.PreOp); + setTokenInfo(TokenID.PlusPlus, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.IncPre, "++", TypeScript.ErrorRecoverySet.PreOp); + setTokenInfo(TokenID.MinusMinus, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.DecPre, "--", TypeScript.ErrorRecoverySet.PreOp); + setTokenInfo(TokenID.OpenParen, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "(", TypeScript.ErrorRecoverySet.LParen); + setTokenInfo(TokenID.OpenBracket, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "[", TypeScript.ErrorRecoverySet.LBrack); + setTokenInfo(TokenID.Dot, Reservation.None, OperatorPrecedence.Unary, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, ".", TypeScript.ErrorRecoverySet.Dot); + setTokenInfo(TokenID.EndOfFile, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "", TypeScript.ErrorRecoverySet.EOF); + setTokenInfo(TokenID.EqualsGreaterThan, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "=>", TypeScript.ErrorRecoverySet.None); + function lookupToken(tokenId) { + return TypeScript.tokenTable[tokenId]; + } + TypeScript.lookupToken = lookupToken; + (function (TokenClass) { + TokenClass._map = []; + TokenClass._map[0] = "Punctuation"; + TokenClass.Punctuation = 0; + TokenClass._map[1] = "Keyword"; + TokenClass.Keyword = 1; + TokenClass._map[2] = "Operator"; + TokenClass.Operator = 2; + TokenClass._map[3] = "Comment"; + TokenClass.Comment = 3; + TokenClass._map[4] = "Whitespace"; + TokenClass.Whitespace = 4; + TokenClass._map[5] = "Identifier"; + TokenClass.Identifier = 5; + TokenClass._map[6] = "NumberLiteral"; + TokenClass.NumberLiteral = 6; + TokenClass._map[7] = "StringLiteral"; + TokenClass.StringLiteral = 7; + TokenClass._map[8] = "RegExpLiteral"; + TokenClass.RegExpLiteral = 8; + })(TypeScript.TokenClass || (TypeScript.TokenClass = {})); + var TokenClass = TypeScript.TokenClass; + var SavedToken = (function () { + function SavedToken(tok, minChar, limChar) { + this.tok = tok; + this.minChar = minChar; + this.limChar = limChar; + } + return SavedToken; + })(); + TypeScript.SavedToken = SavedToken; + var Token = (function () { + function Token(tokenId) { + this.tokenId = tokenId; + } + Token.prototype.toString = function () { + return "token: " + this.tokenId + " " + this.getText() + " (" + (TokenID)._map[this.tokenId] + ")"; + }; + Token.prototype.print = function (line, outfile) { + outfile.WriteLine(this.toString() + ",on line" + line); + }; + Token.prototype.getText = function () { + return TypeScript.tokenTable[this.tokenId].text; + }; + Token.prototype.classification = function () { + if(this.tokenId <= TokenID.LimKeyword) { + return TokenClass.Keyword; + } else { + var tokenInfo = lookupToken(this.tokenId); + if(tokenInfo != undefined) { + if((tokenInfo.unopNodeType != TypeScript.NodeType.None) || (tokenInfo.binopNodeType != TypeScript.NodeType.None)) { + return TokenClass.Operator; + } + } + } + return TokenClass.Punctuation; + }; + return Token; + })(); + TypeScript.Token = Token; + var NumberLiteralToken = (function (_super) { + __extends(NumberLiteralToken, _super); + function NumberLiteralToken(value, text) { + _super.call(this, TokenID.NumberLiteral); + this.value = value; + this.text = text; + } + NumberLiteralToken.prototype.getText = function () { + return this.text; + }; + NumberLiteralToken.prototype.classification = function () { + return TokenClass.NumberLiteral; + }; + return NumberLiteralToken; + })(Token); + TypeScript.NumberLiteralToken = NumberLiteralToken; + var StringLiteralToken = (function (_super) { + __extends(StringLiteralToken, _super); + function StringLiteralToken(value) { + _super.call(this, TokenID.StringLiteral); + this.value = value; + } + StringLiteralToken.prototype.getText = function () { + return this.value; + }; + StringLiteralToken.prototype.classification = function () { + return TokenClass.StringLiteral; + }; + return StringLiteralToken; + })(Token); + TypeScript.StringLiteralToken = StringLiteralToken; + var IdentifierToken = (function (_super) { + __extends(IdentifierToken, _super); + function IdentifierToken(value, hasEscapeSequence) { + _super.call(this, TokenID.Identifier); + this.value = value; + this.hasEscapeSequence = hasEscapeSequence; + } + IdentifierToken.prototype.getText = function () { + return this.value; + }; + IdentifierToken.prototype.classification = function () { + return TokenClass.Identifier; + }; + return IdentifierToken; + })(Token); + TypeScript.IdentifierToken = IdentifierToken; + var WhitespaceToken = (function (_super) { + __extends(WhitespaceToken, _super); + function WhitespaceToken(tokenId, value) { + _super.call(this, tokenId); + this.value = value; + } + WhitespaceToken.prototype.getText = function () { + return this.value; + }; + WhitespaceToken.prototype.classification = function () { + return TokenClass.Whitespace; + }; + return WhitespaceToken; + })(Token); + TypeScript.WhitespaceToken = WhitespaceToken; + var CommentToken = (function (_super) { + __extends(CommentToken, _super); + function CommentToken(tokenID, value, isBlock, startPos, line, endsLine) { + _super.call(this, tokenID); + this.value = value; + this.isBlock = isBlock; + this.startPos = startPos; + this.line = line; + this.endsLine = endsLine; + } + CommentToken.prototype.getText = function () { + return this.value; + }; + CommentToken.prototype.classification = function () { + return TokenClass.Comment; + }; + return CommentToken; + })(Token); + TypeScript.CommentToken = CommentToken; + var RegularExpressionLiteralToken = (function (_super) { + __extends(RegularExpressionLiteralToken, _super); + function RegularExpressionLiteralToken(text) { + _super.call(this, TokenID.RegularExpressionLiteral); + this.text = text; + } + RegularExpressionLiteralToken.prototype.getText = function () { + return this.text; + }; + RegularExpressionLiteralToken.prototype.classification = function () { + return TokenClass.RegExpLiteral; + }; + return RegularExpressionLiteralToken; + })(Token); + TypeScript.RegularExpressionLiteralToken = RegularExpressionLiteralToken; + TypeScript.staticTokens = new Array(); + function initializeStaticTokens() { + for(var i = 0; i <= TokenID.LimFixed; i++) { + TypeScript.staticTokens[i] = new Token(i); + } + } + TypeScript.initializeStaticTokens = initializeStaticTokens; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ArrayCache = (function () { + function ArrayCache() { + this.arrayBase = null; + } + ArrayCache.prototype.specialize = function (arrInstType, checker) { + if(this.arrayBase == null) { + this.arrayBase = arrInstType.specializeType(checker.wildElm.type, this.arrayType.elementType, checker, true); + } + return this.arrayBase; + }; + return ArrayCache; + })(); + TypeScript.ArrayCache = ArrayCache; + var TypeComparisonInfo = (function () { + function TypeComparisonInfo() { + this.onlyCaptureFirstError = false; + this.flags = TypeScript.TypeRelationshipFlags.SuccessfulComparison; + this.message = ""; + } + TypeComparisonInfo.prototype.addMessageToFront = function (message) { + if(!this.onlyCaptureFirstError) { + this.message = this.message ? message + ":\n\t" + this.message : message; + } else { + this.setMessage(message); + } + }; + TypeComparisonInfo.prototype.setMessage = function (message) { + this.message = message; + }; + return TypeComparisonInfo; + })(); + TypeScript.TypeComparisonInfo = TypeComparisonInfo; + (function (TypeCheckCollectionMode) { + TypeCheckCollectionMode._map = []; + TypeCheckCollectionMode._map[0] = "Resident"; + TypeCheckCollectionMode.Resident = 0; + TypeCheckCollectionMode._map[1] = "Transient"; + TypeCheckCollectionMode.Transient = 1; + })(TypeScript.TypeCheckCollectionMode || (TypeScript.TypeCheckCollectionMode = {})); + var TypeCheckCollectionMode = TypeScript.TypeCheckCollectionMode; + var PersistentGlobalTypeState = (function () { + function PersistentGlobalTypeState(errorReporter) { + this.errorReporter = errorReporter; + this.importedGlobalsTable = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + this.importedGlobalsTypeTable = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + this.globals = null; + this.globalTypes = null; + this.ambientGlobals = null; + this.ambientGlobalTypes = null; + this.residentGlobalValues = new TypeScript.StringHashTable(); + this.residentGlobalTypes = new TypeScript.StringHashTable(); + this.residentGlobalAmbientValues = new TypeScript.StringHashTable(); + this.residentGlobalAmbientTypes = new TypeScript.StringHashTable(); + this.residentTypeCheck = true; + this.mod = null; + this.gloMod = null; + this.wildElm = null; + this.importedGlobals = new TypeScript.SymbolScopeBuilder(null, this.importedGlobalsTable, null, this.importedGlobalsTypeTable, null, null); + this.dualGlobalValues = new TypeScript.DualStringHashTable(this.residentGlobalValues, new TypeScript.StringHashTable()); + this.dualGlobalTypes = new TypeScript.DualStringHashTable(this.residentGlobalTypes, new TypeScript.StringHashTable()); + this.dualAmbientGlobalValues = new TypeScript.DualStringHashTable(this.residentGlobalAmbientValues, new TypeScript.StringHashTable()); + this.dualAmbientGlobalTypes = new TypeScript.DualStringHashTable(this.residentGlobalAmbientTypes, new TypeScript.StringHashTable()); + var dualGlobalScopedMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(this.dualGlobalValues, new TypeScript.StringHashTable())); + var dualGlobalScopedAmbientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(this.dualAmbientGlobalValues, new TypeScript.StringHashTable())); + var dualGlobalScopedEnclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(this.dualGlobalTypes, new TypeScript.StringHashTable())); + var dualGlobalScopedAmbientEnclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(this.dualAmbientGlobalTypes, new TypeScript.StringHashTable())); + this.globalScope = new TypeScript.SymbolScopeBuilder(dualGlobalScopedMembers, dualGlobalScopedAmbientMembers, dualGlobalScopedEnclosedTypes, dualGlobalScopedAmbientEnclosedTypes, this.importedGlobals, null); + this.voidType = this.enterPrimitive(TypeScript.Primitive.Void, "void"); + this.booleanType = this.enterPrimitive(TypeScript.Primitive.Boolean, "bool"); + this.doubleType = this.enterPrimitive(TypeScript.Primitive.Double, "number"); + this.importedGlobals.ambientEnclosedTypes.addPublicMember("number", this.doubleType.symbol); + this.stringType = this.enterPrimitive(TypeScript.Primitive.String, "string"); + this.anyType = this.enterPrimitive(TypeScript.Primitive.Any, "any"); + this.nullType = this.enterPrimitive(TypeScript.Primitive.Null, "null"); + this.undefinedType = this.enterPrimitive(TypeScript.Primitive.Undefined, "undefined"); + this.setCollectionMode(TypeCheckCollectionMode.Resident); + this.wildElm = new TypeScript.TypeSymbol("_element", -1, 0, -1, new TypeScript.Type()); + this.importedGlobalsTypeTable.addPublicMember(this.wildElm.name, this.wildElm); + this.mod = new TypeScript.ModuleType(dualGlobalScopedEnclosedTypes, dualGlobalScopedAmbientEnclosedTypes); + this.mod.members = dualGlobalScopedMembers; + this.mod.ambientMembers = dualGlobalScopedAmbientMembers; + this.mod.containedScope = this.globalScope; + this.gloMod = new TypeScript.TypeSymbol(TypeScript.globalId, -1, 0, -1, this.mod); + this.mod.members.addPublicMember(this.gloMod.name, this.gloMod); + this.defineGlobalValue("undefined", this.undefinedType); + } + PersistentGlobalTypeState.prototype.enterPrimitive = function (flags, name) { + var primitive = new TypeScript.Type(); + primitive.primitiveTypeClass = flags; + var symbol = new TypeScript.TypeSymbol(name, -1, name.length, -1, primitive); + symbol.typeCheckStatus = TypeScript.TypeCheckStatus.Finished; + primitive.symbol = symbol; + this.importedGlobals.enter(null, null, symbol, this.errorReporter, true, true, true); + return primitive; + }; + PersistentGlobalTypeState.prototype.setCollectionMode = function (mode) { + this.residentTypeCheck = this.dualGlobalValues.insertPrimary = this.dualGlobalTypes.insertPrimary = this.dualAmbientGlobalValues.insertPrimary = this.dualAmbientGlobalTypes.insertPrimary = mode == TypeCheckCollectionMode.Resident; + }; + PersistentGlobalTypeState.prototype.refreshPersistentState = function () { + this.globals = new TypeScript.StringHashTable(); + this.globalTypes = new TypeScript.StringHashTable(); + this.ambientGlobals = new TypeScript.StringHashTable(); + this.ambientGlobalTypes = new TypeScript.StringHashTable(); + this.globalTypes.add(this.voidType.symbol.name, this.voidType.symbol); + this.globalTypes.add(this.booleanType.symbol.name, this.booleanType.symbol); + this.globalTypes.add(this.doubleType.symbol.name, this.doubleType.symbol); + this.globalTypes.add("number", this.doubleType.symbol); + this.globalTypes.add(this.stringType.symbol.name, this.stringType.symbol); + this.globalTypes.add(this.anyType.symbol.name, this.anyType.symbol); + this.globalTypes.add(this.nullType.symbol.name, this.nullType.symbol); + this.globalTypes.add(this.undefinedType.symbol.name, this.undefinedType.symbol); + this.dualGlobalValues.secondaryTable = this.globals; + this.dualGlobalTypes.secondaryTable = this.globalTypes; + this.dualAmbientGlobalValues.secondaryTable = this.ambientGlobals; + this.dualAmbientGlobalTypes.secondaryTable = this.ambientGlobalTypes; + }; + PersistentGlobalTypeState.prototype.defineGlobalValue = function (name, type) { + var valueLocation = new TypeScript.ValueLocation(); + valueLocation.typeLink = new TypeScript.TypeLink(); + var sym = new TypeScript.VariableSymbol(name, 0, -1, valueLocation); + sym.setType(type); + sym.typeCheckStatus = TypeScript.TypeCheckStatus.Finished; + sym.container = this.gloMod; + this.importedGlobalsTable.addPublicMember(name, sym); + }; + return PersistentGlobalTypeState; + })(); + TypeScript.PersistentGlobalTypeState = PersistentGlobalTypeState; + var ContextualTypeContext = (function () { + function ContextualTypeContext(contextualType, provisional, contextID) { + this.contextualType = contextualType; + this.provisional = provisional; + this.contextID = contextID; + this.targetSig = null; + this.targetThis = null; + this.targetAccessorType = null; + } + return ContextualTypeContext; + })(); + TypeScript.ContextualTypeContext = ContextualTypeContext; + var ContextualTypingContextStack = (function () { + function ContextualTypingContextStack(checker) { + this.checker = checker; + this.contextStack = []; + this.hadProvisionalErrors = false; + } + ContextualTypingContextStack.contextID = TypeScript.TypeCheckStatus.Finished + 1; + ContextualTypingContextStack.prototype.pushContextualType = function (type, provisional) { + this.contextStack.push(new ContextualTypeContext(type, provisional, ContextualTypingContextStack.contextID++)); + this.checker.errorReporter.pushToErrorSink = provisional; + }; + ContextualTypingContextStack.prototype.popContextualType = function () { + var tc = this.contextStack.pop(); + this.checker.errorReporter.pushToErrorSink = this.isProvisional(); + this.hadProvisionalErrors = this.hadProvisionalErrors || (tc.provisional && (this.checker.errorReporter.getCapturedErrors().length)); + this.checker.errorReporter.freeCapturedErrors(); + return tc; + }; + ContextualTypingContextStack.prototype.getContextualType = function () { + return (!this.contextStack.length ? null : this.contextStack[this.contextStack.length - 1]); + }; + ContextualTypingContextStack.prototype.getContextID = function () { + return (!this.contextStack.length ? TypeScript.TypeCheckStatus.Finished : this.contextStack[this.contextStack.length - 1].contextID); + }; + ContextualTypingContextStack.prototype.isProvisional = function () { + return (!this.contextStack.length ? false : this.contextStack[this.contextStack.length - 1].provisional); + }; + return ContextualTypingContextStack; + })(); + TypeScript.ContextualTypingContextStack = ContextualTypingContextStack; + var TypeChecker = (function () { + function TypeChecker(persistentState) { + this.persistentState = persistentState; + this.errorReporter = null; + this.checkControlFlow = false; + this.printControlFlowGraph = false; + this.checkControlFlowUseDef = false; + this.styleSettings = null; + this.units = null; + this.anon = "_anonymous"; + this.locationInfo = null; + this.typeFlow = null; + this.currentCompareA = null; + this.currentCompareB = null; + this.currentModDecl = null; + this.inBind = false; + this.inWith = false; + this.errorsOnWith = true; + this.currentContextualTypeContext = null; + this.resolvingBases = false; + this.canCallDefinitionSignature = false; + this.assignableCache = { + }; + this.subtypeCache = { + }; + this.identicalCache = { + }; + this.provisionalStartedTypecheckObjects = []; + this.mustCaptureGlobalThis = false; + this.voidType = this.persistentState.voidType; + this.booleanType = this.persistentState.booleanType; + this.numberType = this.persistentState.doubleType; + this.stringType = this.persistentState.stringType; + this.anyType = this.persistentState.anyType; + this.nullType = this.persistentState.nullType; + this.undefinedType = this.persistentState.undefinedType; + this.globals = this.persistentState.dualGlobalValues; + this.globalTypes = this.persistentState.dualGlobalTypes; + this.ambientGlobals = this.persistentState.dualAmbientGlobalValues; + this.ambientGlobalTypes = this.persistentState.dualAmbientGlobalTypes; + this.gloModType = this.persistentState.mod; + this.gloMod = this.persistentState.gloMod; + this.wildElm = this.persistentState.wildElm; + this.globalScope = this.persistentState.globalScope; + this.typingContextStack = new ContextualTypingContextStack(this); + } + TypeChecker.prototype.setStyleOptions = function (style) { + this.styleSettings = style; + }; + TypeChecker.prototype.setContextualType = function (type, provisional) { + this.typingContextStack.pushContextualType(type, provisional); + this.currentContextualTypeContext = this.typingContextStack.getContextualType(); + }; + TypeChecker.prototype.unsetContextualType = function () { + var lastTC = this.typingContextStack.popContextualType(); + this.currentContextualTypeContext = this.typingContextStack.getContextualType(); + return lastTC; + }; + TypeChecker.prototype.hadProvisionalErrors = function () { + return this.typingContextStack.hadProvisionalErrors; + }; + TypeChecker.prototype.resetProvisionalErrors = function () { + if(!this.typingContextStack.getContextualType()) { + this.typingContextStack.hadProvisionalErrors = false; + } + }; + TypeChecker.prototype.typeCheckWithContextualType = function (contextType, provisional, condition, ast) { + if(condition) { + this.setContextualType(contextType, this.typingContextStack.isProvisional() || provisional); + } + this.typeFlow.typeCheck(ast); + if(condition) { + this.unsetContextualType(); + } + }; + TypeChecker.prototype.resetTargetType = function () { + this.currentContextualTypeContext = this.typingContextStack.getContextualType(); + }; + TypeChecker.prototype.killCurrentContextualType = function () { + this.currentContextualTypeContext = null; + this.errorReporter.pushToErrorSink = false; + }; + TypeChecker.prototype.hasTargetType = function () { + return this.currentContextualTypeContext && this.currentContextualTypeContext.contextualType; + }; + TypeChecker.prototype.getTargetTypeContext = function () { + return this.currentContextualTypeContext; + }; + TypeChecker.prototype.inProvisionalTypecheckMode = function () { + return this.typingContextStack.isProvisional(); + }; + TypeChecker.prototype.getTypeCheckFinishedStatus = function () { + if(this.inProvisionalTypecheckMode()) { + return this.typingContextStack.getContextID(); + } + return TypeScript.TypeCheckStatus.Finished; + }; + TypeChecker.prototype.typeStatusIsFinished = function (status) { + return status == TypeScript.TypeCheckStatus.Finished || (this.inProvisionalTypecheckMode() && status == this.typingContextStack.getContextID()); + }; + TypeChecker.prototype.addStartedPTO = function (pto) { + if(this.inProvisionalTypecheckMode()) { + this.provisionalStartedTypecheckObjects[this.provisionalStartedTypecheckObjects.length] = pto; + } + }; + TypeChecker.prototype.cleanStartedPTO = function () { + for(var i = 0; i < this.provisionalStartedTypecheckObjects.length; i++) { + if(this.provisionalStartedTypecheckObjects[i].typeCheckStatus >= this.typingContextStack.getContextID()) { + this.provisionalStartedTypecheckObjects[i].typeCheckStatus = TypeScript.TypeCheckStatus.NotStarted; + } + } + this.provisionalStartedTypecheckObjects = []; + }; + TypeChecker.prototype.collectTypes = function (ast) { + if(ast.nodeType == TypeScript.NodeType.Script) { + var script = ast; + this.locationInfo = script.locationInfo; + } + var globalChain = new TypeScript.ScopeChain(this.gloMod, null, this.globalScope); + var context = new TypeScript.TypeCollectionContext(globalChain, this); + TypeScript.getAstWalkerFactory().walk(ast, TypeScript.preCollectTypes, TypeScript.postCollectTypes, null, context); + }; + TypeChecker.prototype.makeArrayType = function (type) { + if(type.arrayCache == null) { + type.arrayCache = new ArrayCache(); + type.arrayCache.arrayType = new TypeScript.Type(); + type.arrayCache.arrayType.elementType = type; + type.arrayCache.arrayType.symbol = type.symbol; + } + return type.arrayCache.arrayType; + }; + TypeChecker.prototype.getParameterList = function (funcDecl, container) { + var args = funcDecl.arguments; + var parameterTable = null; + var parameterBuilder = null; + var len = args.members.length; + var nonOptionalParams = 0; + var result = []; + if(len > 0) { + parameterTable = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + parameterBuilder = new TypeScript.SymbolScopeBuilder(parameterTable, null, null, null, null, container); + for(var i = 0; i < len; i++) { + var parameter = args.members[i]; + var paramDef = new TypeScript.ValueLocation(); + var parameterSymbol = new TypeScript.ParameterSymbol(parameter.id.text, parameter.minChar, this.locationInfo.unitIndex, paramDef); + parameterSymbol.declAST = parameter; + parameterSymbol.funcDecl = funcDecl; + parameter.id.sym = parameterSymbol; + parameter.sym = parameterSymbol; + paramDef.symbol = parameterSymbol; + paramDef.typeLink = TypeScript.getTypeLink(parameter.typeExpr, this, false); + parameterBuilder.enter(null, parameter, parameterSymbol, this.errorReporter, true, false, false); + result[result.length] = parameterSymbol; + if(!parameter.isOptionalArg()) { + nonOptionalParams++; + } + } + } + return { + parameters: result, + nonOptionalParameterCount: nonOptionalParams + }; + }; + TypeChecker.prototype.createFunctionSignature = function (funcDecl, container, scope, overloadGroupSym, addToScope) { + var isExported = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Exported | TypeScript.FncFlags.ClassPropertyMethodExported) || container == this.gloMod; + var isStatic = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static); + var isPrivate = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Private); + var isDefinition = !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Signature); + var isAmbient = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Ambient); + var isConstructor = funcDecl.isConstructMember() || funcDecl.isConstructor; + var isGlobal = container == this.gloMod; + var signature = new TypeScript.Signature(); + var isLambda = funcDecl.fncFlags & TypeScript.FncFlags.IsFunctionExpression; + if(funcDecl.returnTypeAnnotation || isDefinition) { + signature.returnType = TypeScript.getTypeLink(funcDecl.returnTypeAnnotation, this, false); + } else { + signature.returnType = new TypeScript.TypeLink(); + signature.returnType.type = this.anyType; + } + signature.hasVariableArgList = funcDecl.variableArgList; + var sigData = this.getParameterList(funcDecl, container); + signature.parameters = sigData.parameters; + signature.nonOptionalParameterCount = sigData.nonOptionalParameterCount; + funcDecl.signature = signature; + signature.declAST = funcDecl; + var useOverloadGroupSym = overloadGroupSym && overloadGroupSym.getType() && !overloadGroupSym.isAccessor() && (funcDecl.isSignature() || (isAmbient == TypeScript.hasFlag(overloadGroupSym.flags, TypeScript.SymbolFlags.Ambient))); + if(useOverloadGroupSym && isPrivate != TypeScript.hasFlag(overloadGroupSym.flags, TypeScript.SymbolFlags.Private)) { + this.errorReporter.simpleError(funcDecl, "Public/Private visibility of overloads does not agree"); + } + var groupType = useOverloadGroupSym ? overloadGroupSym.getType() : new TypeScript.Type(); + if(isConstructor) { + if(groupType.construct == null) { + groupType.construct = new TypeScript.SignatureGroup(); + } + groupType.construct.addSignature(signature); + groupType.construct.hasImplementation = !(funcDecl.isSignature()); + if(groupType.construct.hasImplementation) { + groupType.setHasImplementation(); + } + } else if(funcDecl.isIndexerMember()) { + if(groupType.index == null) { + groupType.index = new TypeScript.SignatureGroup(); + groupType.index.flags |= TypeScript.SignatureFlags.IsIndexer; + } + groupType.index.addSignature(signature); + groupType.index.hasImplementation = !(funcDecl.isSignature()); + if(groupType.index.hasImplementation) { + groupType.setHasImplementation(); + } + } else { + if(groupType.call == null) { + groupType.call = new TypeScript.SignatureGroup(); + } + groupType.call.addSignature(signature); + groupType.call.hasImplementation = !(funcDecl.isSignature()); + if(groupType.call.hasImplementation) { + groupType.setHasImplementation(); + } + } + var instanceType = groupType.instanceType; + var funcName = null; + var usedHint = false; + if(funcDecl.name && !funcDecl.name.isMissing()) { + funcName = funcDecl.name.text; + } else if(funcDecl.hint) { + funcName = funcDecl.hint; + usedHint = true; + } + if(groupType.symbol == null) { + groupType.symbol = new TypeScript.TypeSymbol(funcName ? funcName : this.anon, funcDecl.minChar, funcDecl.limChar - funcDecl.minChar, this.locationInfo.unitIndex, groupType); + if(!useOverloadGroupSym) { + groupType.symbol.declAST = funcDecl; + } + } + if(isStatic) { + groupType.symbol.flags |= TypeScript.SymbolFlags.Static; + } + if(isAmbient) { + groupType.symbol.flags |= TypeScript.SymbolFlags.Ambient; + } + if(isPrivate) { + groupType.symbol.flags |= TypeScript.SymbolFlags.Private; + } + groupType.symbol.isMethod = funcDecl.isMethod(); + if(groupType.symbol.isMethod) { + groupType.symbol.flags |= TypeScript.SymbolFlags.Property; + } + funcDecl.type = groupType; + if(!isConstructor) { + if(funcName && !isLambda && !funcDecl.isAccessor() && !usedHint) { + if(addToScope) { + if(funcDecl.isMethod() && isStatic) { + if(!(container).type.members.publicMembers.add(funcName, groupType.symbol)) { + this.errorReporter.duplicateIdentifier(funcDecl, funcName); + } + groupType.symbol.container = container; + } else if(overloadGroupSym == null || (overloadGroupSym.declAST && !(overloadGroupSym.declAST).isOverload && (container.isType()))) { + scope.enter(container, funcDecl, groupType.symbol, this.errorReporter, !isPrivate && (isExported || isStatic || isGlobal), false, isAmbient); + } + } else if(!funcDecl.isSpecialFn()) { + groupType.symbol.container = container; + } + } else if(!funcDecl.isSpecialFn()) { + groupType.symbol.container = container; + } + } + if(useOverloadGroupSym) { + var overloadGroupType = overloadGroupSym ? overloadGroupSym.getType() : null; + var classType = groupType; + if(classType != overloadGroupType) { + if(classType.construct == null) { + if(overloadGroupType && overloadGroupType.construct) { + classType.construct = overloadGroupType.construct; + } else { + classType.construct = new TypeScript.SignatureGroup(); + } + } else if(overloadGroupType) { + if(overloadGroupType.construct) { + classType.construct.signatures.concat(overloadGroupType.construct.signatures); + } + } + if(overloadGroupType) { + if(classType.call == null) { + classType.call = overloadGroupType.call; + } else if(overloadGroupType.call) { + classType.call.signatures.concat(overloadGroupType.call.signatures); + } + if(!isStatic) { + if(classType.instanceType == null) { + classType.instanceType = overloadGroupType.instanceType; + } + var instanceType = classType.instanceType; + if(instanceType) { + if(instanceType.call == null) { + instanceType.call = overloadGroupType.call; + } else if(overloadGroupType.call) { + instanceType.call.signatures.concat(overloadGroupType.call.signatures); + } + } + } + if(classType.index == null) { + classType.index = overloadGroupType.index; + } else if(overloadGroupType.index) { + classType.index.signatures.concat(overloadGroupType.index.signatures); + } + } + } + } + return signature; + }; + TypeChecker.prototype.createAccessorSymbol = function (funcDecl, fgSym, enclosingClass, addToMembers, isClassProperty, scope, container) { + var accessorSym = null; + var sig = funcDecl.signature; + var nameText = funcDecl.name.text; + var isStatic = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static); + var isPrivate = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Private); + if(fgSym == null) { + var field = new TypeScript.ValueLocation(); + accessorSym = new TypeScript.FieldSymbol(nameText, funcDecl.minChar, this.locationInfo.unitIndex, false, field); + field.symbol = accessorSym; + accessorSym.declAST = funcDecl; + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { + if(accessorSym.getter) { + this.errorReporter.simpleError(funcDecl, "Redeclaration of property getter"); + } + accessorSym.getter = sig.declAST.type.symbol; + } else { + if(accessorSym.setter) { + this.errorReporter.simpleError(funcDecl, "Redeclaration of property setter"); + } + accessorSym.setter = sig.declAST.type.symbol; + } + field.typeLink = TypeScript.getTypeLink(null, this, false); + if(addToMembers) { + if(enclosingClass) { + if(!enclosingClass.members.publicMembers.add(nameText, accessorSym)) { + this.errorReporter.duplicateIdentifier(funcDecl, accessorSym.name); + } + accessorSym.container = enclosingClass.symbol; + } else { + this.errorReporter.simpleError(funcDecl, "Accessor property may not be added in this context"); + } + } else { + scope.enter(container, funcDecl, accessorSym, this.errorReporter, !isPrivate || isStatic, false, false); + } + if(isClassProperty) { + accessorSym.flags |= TypeScript.SymbolFlags.Property; + } + if(isStatic) { + accessorSym.flags |= TypeScript.SymbolFlags.Static; + } + if(isPrivate) { + accessorSym.flags |= TypeScript.SymbolFlags.Private; + } else { + accessorSym.flags |= TypeScript.SymbolFlags.Public; + } + } else { + accessorSym = (fgSym); + if(isPrivate != TypeScript.hasFlag(accessorSym.flags, TypeScript.SymbolFlags.Private)) { + this.errorReporter.simpleError(funcDecl, "Getter and setter accessors do not agree in visibility"); + } + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { + if(accessorSym.getter) { + this.errorReporter.simpleError(funcDecl, "Redeclaration of property getter"); + } + accessorSym.getter = funcDecl.type.symbol; + } else { + if(accessorSym.setter) { + this.errorReporter.simpleError(funcDecl, "Redeclaration of property setter"); + } + accessorSym.setter = funcDecl.type.symbol; + } + } + return accessorSym; + }; + TypeChecker.prototype.addBases = function (resultScope, type, baseContext) { + resultScope.addParentScope(new TypeScript.SymbolTableScope(type.members, type.ambientMembers, type.getAllEnclosedTypes(), type.getAllAmbientEnclosedTypes(), type.symbol)); + var i = 0; + var parent; + if(type.extendsList) { + for(var len = type.extendsList.length; i < len; i++) { + parent = type.extendsList[i]; + if(baseContext.baseId == parent.typeID) { + this.errorReporter.reportErrorFromSym(parent.symbol, "Type '" + baseContext.base + "' is recursively referenced as a base class of itself"); + parent.symbol.flags |= TypeScript.SymbolFlags.RecursivelyReferenced; + break; + } + this.addBases(resultScope, parent, baseContext); + } + } + }; + TypeChecker.prototype.scopeOf = function (type) { + var resultScope = new TypeScript.SymbolAggregateScope(type.symbol); + var baseContext = { + base: type.symbol && type.symbol.name ? type.symbol.name : "{}", + baseId: type.typeID + }; + this.addBases(resultScope, type, baseContext); + return resultScope; + }; + TypeChecker.prototype.lookupMemberTypeSymbol = function (containingType, name) { + var symbol = null; + if(containingType.containedScope) { + symbol = containingType.containedScope.find(name, false, true); + } else if(containingType.members) { + symbol = containingType.members.allMembers.lookup(name); + if(symbol == null && containingType.ambientMembers) { + symbol = containingType.ambientMembers.allMembers.lookup(name); + } + } + if(symbol == null || !symbol.isType()) { + var typeMembers = containingType.getAllEnclosedTypes(); + var ambientTypeMembers = containingType.getAllAmbientEnclosedTypes(); + if(typeMembers) { + symbol = typeMembers.allMembers.lookup(name); + if(symbol == null && ambientTypeMembers) { + symbol = ambientTypeMembers.allMembers.lookup(name); + } + } + } + if(symbol && symbol.isType()) { + return symbol; + } else { + return null; + } + }; + TypeChecker.prototype.findSymbolForDynamicModule = function (idText, currentFileName, search) { + var originalIdText = idText; + var symbol = search(idText); + if(symbol == null) { + if(!symbol) { + idText = TypeScript.swapQuotes(originalIdText); + symbol = search(idText); + } + if(!symbol) { + idText = TypeScript.stripQuotes(originalIdText) + ".ts"; + symbol = search(idText); + } + if(!symbol) { + idText = TypeScript.stripQuotes(originalIdText) + ".str"; + symbol = search(idText); + } + if(!symbol) { + idText = TypeScript.stripQuotes(originalIdText) + ".d.ts"; + symbol = search(idText); + } + if(!symbol) { + idText = TypeScript.stripQuotes(originalIdText) + ".d.str"; + symbol = search(idText); + } + if(!symbol && !TypeScript.isRelative(originalIdText)) { + idText = originalIdText; + var strippedIdText = TypeScript.stripQuotes(idText); + var path = TypeScript.getRootFilePath(TypeScript.switchToForwardSlashes(currentFileName)); + while(symbol == null && path != "") { + idText = TypeScript.normalizePath(path + strippedIdText + ".ts"); + symbol = search(idText); + if(symbol == null) { + idText = TypeScript.changePathToSTR(idText); + symbol = search(idText); + } + if(symbol == null) { + idText = TypeScript.changePathToDTS(idText); + symbol = search(idText); + } + if(symbol == null) { + idText = TypeScript.changePathToDSTR(idText); + symbol = search(idText); + } + if(symbol == null) { + if(path === '/') { + path = ''; + } else { + path = TypeScript.normalizePath(path + ".."); + path = path && path != '/' ? path + '/' : path; + } + } + } + } + } + return symbol; + }; + TypeChecker.prototype.resolveTypeMember = function (scope, dotNode) { + var lhs = dotNode.operand1; + var rhs = dotNode.operand2; + var resultType = this.anyType; + var lhsType = this.anyType; + if(lhs && rhs && (rhs.nodeType == TypeScript.NodeType.Name)) { + if(lhs.nodeType == TypeScript.NodeType.Dot) { + lhsType = this.resolveTypeMember(scope, lhs); + } else if(lhs.nodeType == TypeScript.NodeType.Name) { + var identifier = lhs; + var symbol = scope.find(identifier.text, false, true); + if(symbol == null) { + this.errorReporter.unresolvedSymbol(identifier, identifier.actualText); + } else if(symbol.isType()) { + var typeSymbol = symbol; + if(typeSymbol.aliasLink && !typeSymbol.type && typeSymbol.aliasLink.alias.nodeType == TypeScript.NodeType.Name) { + var modPath = (typeSymbol.aliasLink.alias).text; + var modSym = this.findSymbolForDynamicModule(modPath, this.locationInfo.filename, function (id) { + return scope.find(id, false, true); + }); + if(modSym) { + typeSymbol.type = modSym.getType(); + } + } + if(TypeScript.optimizeModuleCodeGen && symbol) { + var symType = symbol.getType(); + if(symType && typeSymbol.aliasLink && typeSymbol.onlyReferencedAsTypeRef) { + var modDecl = symType.symbol.declAST; + if(modDecl && TypeScript.hasFlag(modDecl.modFlags, TypeScript.ModuleFlags.IsDynamic)) { + typeSymbol.onlyReferencedAsTypeRef = !this.resolvingBases; + } + } + } + if(!symbol.visible(scope, this)) { + this.errorReporter.simpleError(lhs, "The symbol '" + identifier.actualText + "' is not visible at this point"); + } + lhsType = symbol.getType(); + identifier.sym = symbol; + } else { + this.errorReporter.simpleError(lhs, "Expected type"); + } + } + if(!lhsType) { + lhsType = this.anyType; + } + if(lhsType != this.anyType) { + var rhsIdentifier = rhs; + var resultSymbol = this.lookupMemberTypeSymbol(lhsType, rhsIdentifier.text); + if(resultSymbol == null) { + resultType = this.anyType; + this.errorReporter.simpleError(dotNode, "Expected type"); + } else { + resultType = resultSymbol.getType(); + if(!resultSymbol.visible(scope, this)) { + this.errorReporter.simpleError(lhs, "The symbol '" + (rhs).actualText + "' is not visible at this point"); + } + } + rhsIdentifier.sym = resultType.symbol; + } + } + if(resultType.isClass()) { + resultType = resultType.instanceType; + } + return resultType; + }; + TypeChecker.prototype.resolveFuncDecl = function (funcDecl, scope, fgSym) { + var functionGroupSymbol = this.createFunctionSignature(funcDecl, scope.container, scope, fgSym, false).declAST.type.symbol; + var signatures; + if(funcDecl.isConstructMember()) { + signatures = functionGroupSymbol.type.construct.signatures; + } else if(funcDecl.isIndexerMember()) { + signatures = functionGroupSymbol.type.getInstanceType().index.signatures; + } else { + signatures = functionGroupSymbol.type.call.signatures; + } + var signature = signatures[signatures.length - 1]; + var len = signature.parameters.length; + for(var i = 0; i < len; i++) { + var paramSym = signature.parameters[i]; + this.resolveTypeLink(scope, paramSym.parameter.typeLink, true); + } + if(len && funcDecl.variableArgList) { + if(!signature.parameters[len - 1].parameter.typeLink.type.elementType) { + this.errorReporter.simpleErrorFromSym(signature.parameters[len - 1].parameter.symbol, "... parameter must have array type"); + signature.parameters[len - 1].parameter.typeLink.type = this.makeArrayType(signature.parameters[len - 1].parameter.typeLink.type); + } + } + this.resolveTypeLink(scope, signature.returnType, funcDecl.isSignature()); + return functionGroupSymbol; + }; + TypeChecker.prototype.resolveVarDecl = function (varDecl, scope) { + var field = new TypeScript.ValueLocation(); + var fieldSymbol = new TypeScript.FieldSymbol(varDecl.id.text, varDecl.minChar, this.locationInfo.unitIndex, (varDecl.varFlags & TypeScript.VarFlags.Readonly) == TypeScript.VarFlags.None, field); + fieldSymbol.transferVarFlags(varDecl.varFlags); + field.symbol = fieldSymbol; + fieldSymbol.declAST = varDecl; + field.typeLink = TypeScript.getTypeLink(varDecl.typeExpr, this, varDecl.init == null); + this.resolveTypeLink(scope, field.typeLink, true); + varDecl.sym = fieldSymbol; + varDecl.type = field.typeLink.type; + return fieldSymbol; + }; + TypeChecker.prototype.resolveTypeLink = function (scope, typeLink, supplyVar) { + var arrayCount = 0; + if(typeLink.type == null) { + var ast = typeLink.ast; + if(ast) { + while(typeLink.type == null) { + switch(ast.nodeType) { + case TypeScript.NodeType.Name: + var identifier = ast; + var symbol = scope.find(identifier.text, false, true); + if(symbol == null) { + typeLink.type = this.anyType; + this.errorReporter.unresolvedSymbol(identifier, identifier.actualText); + } else if(symbol.isType()) { + if(!symbol.visible(scope, this)) { + this.errorReporter.simpleError(ast, "The symbol '" + identifier.actualText + "' is not visible at this point"); + } + identifier.sym = symbol; + typeLink.type = symbol.getType(); + if(typeLink.type) { + if(typeLink.type.isClass()) { + typeLink.type = typeLink.type.instanceType; + } + } else { + typeLink.type = this.anyType; + } + } else { + typeLink.type = this.anyType; + this.errorReporter.simpleError(ast, "Expected type"); + } + break; + case TypeScript.NodeType.Dot: + typeLink.type = this.resolveTypeMember(scope, ast); + break; + case TypeScript.NodeType.TypeRef: + var typeRef = ast; + arrayCount = typeRef.arrayCount; + ast = typeRef.term; + if(ast == null) { + typeLink.type = this.anyType; + } + break; + case TypeScript.NodeType.InterfaceDeclaration: + var interfaceDecl = ast; + var interfaceType = new TypeScript.Type(); + var interfaceSymbol = new TypeScript.TypeSymbol((interfaceDecl.name).text, ast.minChar, ast.limChar - ast.minChar, this.locationInfo.unitIndex, interfaceType); + interfaceType.symbol = interfaceSymbol; + interfaceType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + interfaceType.containedScope = new TypeScript.SymbolTableScope(interfaceType.members, null, null, null, interfaceSymbol); + interfaceType.containedScope.container = interfaceSymbol; + interfaceType.memberScope = interfaceType.containedScope; + var memberList = interfaceDecl.members; + var props = memberList.members; + var propsLen = props.length; + for(var j = 0; j < propsLen; j++) { + var propDecl = props[j]; + var propSym = null; + var addMember = true; + var id = null; + if(propDecl.nodeType == TypeScript.NodeType.FuncDecl) { + var funcDecl = propDecl; + id = funcDecl.name; + propSym = interfaceType.members.allMembers.lookup(funcDecl.getNameText()); + addMember = (propSym == null); + if(funcDecl.isSpecialFn()) { + addMember = false; + propSym = this.resolveFuncDecl(funcDecl, scope, interfaceSymbol); + } else { + propSym = this.resolveFuncDecl(funcDecl, scope, propSym); + } + funcDecl.type = (propSym).type; + } else { + id = (propDecl).id; + propSym = this.resolveVarDecl(propDecl, scope); + addMember = !id.isMissing(); + } + if(addMember) { + if(id && TypeScript.hasFlag(id.flags, TypeScript.ASTFlags.OptionalName)) { + propSym.flags |= TypeScript.SymbolFlags.Optional; + } + if(!interfaceType.members.allMembers.add(propSym.name, propSym)) { + this.errorReporter.duplicateIdentifier(ast, propSym.name); + } + } + } + ast.type = interfaceType; + typeLink.type = interfaceType; + break; + case TypeScript.NodeType.FuncDecl: + var tsym = this.resolveFuncDecl(ast, scope, null); + typeLink.type = tsym.type; + break; + default: + typeLink.type = this.anyType; + this.errorReporter.simpleError(ast, "Expected type"); + break; + } + } + } + for(var count = arrayCount; count > 0; count--) { + typeLink.type = this.makeArrayType(typeLink.type); + } + if(supplyVar && (typeLink.type == null)) { + typeLink.type = this.anyType; + } + if(typeLink.ast) { + typeLink.ast.type = typeLink.type; + } + } + }; + TypeChecker.prototype.resolveBaseTypeLink = function (typeLink, scope) { + this.resolvingBases = true; + this.resolveTypeLink(scope, typeLink, true); + this.resolvingBases = false; + var extendsType = null; + if(typeLink.type.isClass()) { + extendsType = typeLink.type.instanceType; + } else { + extendsType = typeLink.type; + } + return extendsType; + }; + TypeChecker.prototype.findMostApplicableSignature = function (signatures, args) { + if(signatures.length == 1) { + return { + sig: signatures[0].signature, + ambiguous: false + }; + } + var best = signatures[0]; + var Q = null; + var AType = null; + var PType = null; + var QType = null; + var ambiguous = false; + for(var qSig = 1; qSig < signatures.length; qSig++) { + Q = signatures[qSig]; + var i = 0; + for(i = 0; args && i < args.members.length; i++) { + AType = args.members[i].type; + PType = i < best.signature.parameters.length ? best.signature.parameters[i].getType() : best.signature.parameters[best.signature.parameters.length - 1].getType().elementType; + QType = i < Q.signature.parameters.length ? Q.signature.parameters[i].getType() : Q.signature.parameters[Q.signature.parameters.length - 1].getType().elementType; + if(this.typesAreIdentical(PType, QType)) { + continue; + } else if(this.typesAreIdentical(AType, PType)) { + break; + } else if(this.typesAreIdentical(AType, QType)) { + best = Q; + break; + } else if(this.sourceIsSubtypeOfTarget(PType, QType)) { + break; + } else if(this.sourceIsSubtypeOfTarget(QType, PType)) { + best = Q; + break; + } else if(Q.hadProvisionalErrors) { + break; + } else if(best.hadProvisionalErrors) { + best = Q; + break; + } + } + if(!args || i == args.members.length) { + var collection = { + getLength: function () { + return 2; + }, + setTypeAtIndex: function (index, type) { + }, + getTypeAtIndex: function (index) { + return index ? Q.signature.returnType.type : best.signature.returnType.type; + } + }; + var bct = this.findBestCommonType(best.signature.returnType.type, null, collection, true); + ambiguous = !bct; + } else { + ambiguous = false; + } + } + return { + sig: best.signature, + ambiguous: ambiguous + }; + }; + TypeChecker.prototype.getApplicableSignatures = function (signatures, args, comparisonInfo) { + var applicableSigs = []; + var memberType = null; + var miss = false; + var cxt = null; + var hadProvisionalErrors = false; + for(var i = 0; i < signatures.length; i++) { + miss = false; + for(var j = 0; j < args.members.length; j++) { + if(j >= signatures[i].parameters.length) { + continue; + } + memberType = signatures[i].parameters[j].getType(); + if(signatures[i].declAST.variableArgList && (j >= signatures[i].nonOptionalParameterCount - 1) && memberType.isArray()) { + memberType = memberType.elementType; + } + if(memberType == this.anyType) { + continue; + } else if(args.members[j].nodeType == TypeScript.NodeType.FuncDecl) { + if(this.typeFlow.functionInterfaceType && memberType == this.typeFlow.functionInterfaceType) { + continue; + } + if(!this.canContextuallyTypeFunction(memberType, args.members[j], true)) { + if(this.canContextuallyTypeFunction(memberType, args.members[j], false)) { + this.typeFlow.typeCheck(args.members[j]); + if(!this.sourceIsAssignableToTarget(args.members[j].type, memberType, comparisonInfo)) { + break; + } + } else { + break; + } + } else { + this.typeCheckWithContextualType(memberType, true, true, args.members[j]); + this.cleanStartedPTO(); + hadProvisionalErrors = this.hadProvisionalErrors(); + if(!this.sourceIsAssignableToTarget(args.members[j].type, memberType, comparisonInfo)) { + if(comparisonInfo) { + comparisonInfo.setMessage("Could not apply type '" + memberType.getTypeName() + "' to argument " + (j + 1) + ", which is of type '" + args.members[j].type.getTypeName() + "'"); + } + miss = true; + } + this.resetProvisionalErrors(); + if(miss) { + break; + } + } + } else if(args.members[j].nodeType == TypeScript.NodeType.ObjectLit) { + if(this.typeFlow.objectInterfaceType && memberType == this.typeFlow.objectInterfaceType) { + continue; + } + this.typeCheckWithContextualType(memberType, true, true, args.members[j]); + this.cleanStartedPTO(); + hadProvisionalErrors = this.hadProvisionalErrors(); + if(!this.sourceIsAssignableToTarget(args.members[j].type, memberType, comparisonInfo)) { + if(comparisonInfo) { + comparisonInfo.setMessage("Could not apply type '" + memberType.getTypeName() + "' to argument " + (j + 1) + ", which is of type '" + args.members[j].type.getTypeName() + "'"); + } + miss = true; + } + this.resetProvisionalErrors(); + if(miss) { + break; + } + } else if(args.members[j].nodeType == TypeScript.NodeType.ArrayLit) { + if(this.typeFlow.arrayInterfaceType && memberType == this.typeFlow.arrayInterfaceType) { + continue; + } + this.typeCheckWithContextualType(memberType, true, true, args.members[j]); + this.cleanStartedPTO(); + hadProvisionalErrors = this.hadProvisionalErrors(); + if(!this.sourceIsAssignableToTarget(args.members[j].type, memberType, comparisonInfo)) { + if(comparisonInfo) { + comparisonInfo.setMessage("Could not apply type '" + memberType.getTypeName() + "' to argument " + (j + 1) + ", which is of type '" + args.members[j].type.getTypeName() + "'"); + } + break; + } + this.resetProvisionalErrors(); + if(miss) { + break; + } + } + } + if(j == args.members.length) { + applicableSigs[applicableSigs.length] = { + signature: signatures[i], + hadProvisionalErrors: hadProvisionalErrors + }; + } + hadProvisionalErrors = false; + } + return applicableSigs; + }; + TypeChecker.prototype.canContextuallyTypeFunction = function (candidateType, funcDecl, beStringent) { + if(funcDecl.isParenthesized || funcDecl.isMethod() || beStringent && funcDecl.returnTypeAnnotation || funcDecl.isInlineCallLiteral) { + return false; + } + beStringent = beStringent || (this.typeFlow.functionInterfaceType == candidateType); + if(!beStringent) { + return true; + } + if(!funcDecl.signature) { + this.createFunctionSignature(funcDecl, this.typeFlow.scope.container, this.typeFlow.scope, null, null); + this.typeFlow.typeCheck(funcDecl); + } + var signature = funcDecl.signature; + var paramLen = signature.parameters.length; + for(var i = 0; i < paramLen; i++) { + var param = signature.parameters[i]; + var symbol = param; + var argDecl = symbol.declAST; + if(beStringent && argDecl.typeExpr) { + return false; + } + } + if(candidateType.construct && candidateType.call) { + return false; + } + var candidateSigs = candidateType.construct ? candidateType.construct : candidateType.call; + if(!candidateSigs || candidateSigs.signatures.length > 1) { + return false; + } + return true; + }; + TypeChecker.prototype.canContextuallyTypeObjectLiteral = function (targetType, objectLit) { + if(targetType == this.typeFlow.objectInterfaceType) { + return true; + } + var memberDecls = objectLit.operand; + if(!(memberDecls && targetType.memberScope)) { + return false; + } + var id = null; + var targetMember = null; + var text = ""; + var foundSyms = { + }; + for(var i = 0; i < memberDecls.members.length; i++) { + id = (memberDecls.members[i]).operand1; + if(id.nodeType == TypeScript.NodeType.Name) { + text = (id).text; + } else if(id.nodeType == TypeScript.NodeType.QString) { + var idText = (id).text; + text = idText.substring(1, idText.length - 1); + } else { + return false; + } + targetMember = targetType.memberScope.find(text, true, false); + if(!targetMember) { + return false; + } + foundSyms[text] = true; + } + var targetMembers = targetType.memberScope.getAllValueSymbolNames(true); + for(var i = 0; i < targetMembers.length; i++) { + var memberName = targetMembers[i]; + var memberSym = targetType.memberScope.find(memberName, true, false); + if(!foundSyms[targetMembers[i]] && !TypeScript.hasFlag(memberSym.flags, TypeScript.SymbolFlags.Optional)) { + return false; + } + } + return true; + }; + TypeChecker.prototype.widenType = function (t) { + if(t == this.undefinedType || t == this.nullType) { + return this.anyType; + } + return t; + }; + TypeChecker.prototype.isNullOrUndefinedType = function (t) { + return t == this.undefinedType || t == this.nullType; + }; + TypeChecker.prototype.findBestCommonType = function (initialType, targetType, collection, acceptVoid, comparisonInfo) { + var i = 0; + var len = collection.getLength(); + var nlastChecked = 0; + var bestCommonType = initialType; + if(targetType) { + bestCommonType = bestCommonType ? bestCommonType.mergeOrdered(targetType, this, acceptVoid) : targetType; + } + var convergenceType = bestCommonType; + while(nlastChecked < len) { + for(i = 0; i < len; i++) { + if(i == nlastChecked) { + continue; + } + if(convergenceType && (bestCommonType = convergenceType.mergeOrdered(collection.getTypeAtIndex(i), this, acceptVoid, comparisonInfo))) { + convergenceType = bestCommonType; + } + if(bestCommonType == this.anyType || bestCommonType == null) { + break; + } else if(targetType) { + collection.setTypeAtIndex(i, targetType); + } + } + if(convergenceType && bestCommonType) { + break; + } + nlastChecked++; + if(nlastChecked < len) { + convergenceType = collection.getTypeAtIndex(nlastChecked); + } + } + return acceptVoid ? bestCommonType : (bestCommonType == this.voidType ? null : bestCommonType); + }; + TypeChecker.prototype.typesAreIdentical = function (t1, t2) { + if(t1 == t2) { + return true; + } + if(!t1 || !t2) { + return false; + } + if(t1.isClass() || t1.isClassInstance()) { + return false; + } + var comboId = (t2.typeID << 16) | t1.typeID; + if(this.identicalCache[comboId]) { + return true; + } + if((t1.typeFlags & TypeScript.TypeFlags.IsEnum) || (t2.typeFlags & TypeScript.TypeFlags.IsEnum)) { + return false; + } + if(t1.isArray() || t2.isArray()) { + if(!(t1.isArray() && t2.isArray())) { + return false; + } + this.identicalCache[comboId] = false; + var ret = this.typesAreIdentical(t1.elementType, t2.elementType); + if(ret) { + this.subtypeCache[comboId] = true; + } else { + this.subtypeCache[comboId] = undefined; + } + return ret; + } + if(t1.primitiveTypeClass != t2.primitiveTypeClass) { + return false; + } + this.identicalCache[comboId] = false; + if(t1.memberScope && t2.memberScope) { + var t1MemberKeys = t1.memberScope.getAllValueSymbolNames(true).sort(); + var t2MemberKeys = t2.memberScope.getAllValueSymbolNames(true).sort(); + if(t1MemberKeys.length != t2MemberKeys.length) { + this.identicalCache[comboId] = undefined; + return false; + } + var t1MemberSymbol = null; + var t2MemberSymbol = null; + var t1MemberType = null; + var t2MemberType = null; + for(var iMember = 0; iMember < t1MemberKeys.length; iMember++) { + if(t1MemberKeys[iMember] != t2MemberKeys[iMember]) { + this.identicalCache[comboId] = undefined; + return false; + } + t1MemberSymbol = t1.memberScope.find(t1MemberKeys[iMember], false, false); + t2MemberSymbol = t2.memberScope.find(t2MemberKeys[iMember], false, false); + if((t1MemberSymbol.flags & TypeScript.SymbolFlags.Optional) != (t2MemberSymbol.flags & TypeScript.SymbolFlags.Optional)) { + this.identicalCache[comboId] = undefined; + return false; + } + t1MemberType = t1MemberSymbol.getType(); + t2MemberType = t2MemberSymbol.getType(); + if(t1MemberType && t2MemberType && (this.identicalCache[(t2MemberType.typeID << 16) | t1MemberType.typeID] != undefined)) { + continue; + } + if(!this.typesAreIdentical(t1MemberType, t2MemberType)) { + this.identicalCache[comboId] = undefined; + return false; + } + } + } else if(t1.memberScope || t2.memberScope) { + this.identicalCache[comboId] = undefined; + return false; + } + if(!this.signatureGroupsAreIdentical(t1.call, t2.call)) { + this.identicalCache[comboId] = undefined; + return false; + } + if(!this.signatureGroupsAreIdentical(t1.construct, t2.construct)) { + this.identicalCache[comboId] = undefined; + return false; + } + if(!this.signatureGroupsAreIdentical(t1.index, t2.index)) { + this.identicalCache[comboId] = undefined; + return false; + } + this.identicalCache[comboId] = true; + return true; + }; + TypeChecker.prototype.signatureGroupsAreIdentical = function (sg1, sg2) { + if(sg1 == sg2) { + return true; + } + if(!sg1 || !sg2) { + return false; + } + if(sg1.signatures.length != sg2.signatures.length) { + return false; + } + var sig1 = null; + var sig2 = null; + var sigsMatch = false; + for(var iSig1 = 0; iSig1 < sg1.signatures.length; iSig1++) { + sig1 = sg1.signatures[iSig1]; + for(var iSig2 = 0; iSig2 < sg2.signatures.length; iSig2++) { + sig2 = sg2.signatures[iSig2]; + if(this.signaturesAreIdentical(sig1, sig2)) { + sigsMatch = true; + break; + } + } + if(sigsMatch) { + sigsMatch = false; + continue; + } + return false; + } + return true; + }; + TypeChecker.prototype.signaturesAreIdentical = function (s1, s2) { + if(s1.hasVariableArgList != s2.hasVariableArgList) { + return false; + } + if(s1.nonOptionalParameterCount != s2.nonOptionalParameterCount) { + return false; + } + if(s1.parameters.length != s2.parameters.length) { + return false; + } + if(!this.typesAreIdentical(s1.returnType.type, s2.returnType.type)) { + return false; + } + for(var iParam = 0; iParam < s1.parameters.length; iParam++) { + if(!this.typesAreIdentical(s1.parameters[iParam].parameter.typeLink.type, s2.parameters[iParam].parameter.typeLink.type)) { + return false; + } + } + return true; + }; + TypeChecker.prototype.sourceIsSubtypeOfTarget = function (source, target, comparisonInfo) { + return this.sourceIsRelatableToTarget(source, target, false, this.subtypeCache, comparisonInfo); + }; + TypeChecker.prototype.signatureGroupIsSubtypeOfTarget = function (sg1, sg2, comparisonInfo) { + return this.signatureGroupIsRelatableToTarget(sg1, sg2, false, this.subtypeCache, comparisonInfo); + }; + TypeChecker.prototype.signatureIsSubtypeOfTarget = function (s1, s2, comparisonInfo) { + return this.signatureIsRelatableToTarget(s1, s2, false, this.subtypeCache, comparisonInfo); + }; + TypeChecker.prototype.sourceIsAssignableToTarget = function (source, target, comparisonInfo) { + return this.sourceIsRelatableToTarget(source, target, true, this.assignableCache, comparisonInfo); + }; + TypeChecker.prototype.signatureGroupIsAssignableToTarget = function (sg1, sg2, comparisonInfo) { + return this.signatureGroupIsRelatableToTarget(sg1, sg2, true, this.assignableCache, comparisonInfo); + }; + TypeChecker.prototype.signatureIsAssignableToTarget = function (s1, s2, comparisonInfo) { + return this.signatureIsRelatableToTarget(s1, s2, true, this.assignableCache, comparisonInfo); + }; + TypeChecker.prototype.sourceIsRelatableToTarget = function (source, target, assignableTo, comparisonCache, comparisonInfo) { + if(source == target) { + return true; + } + if(!(source && target)) { + return true; + } + var comboId = (source.typeID << 16) | target.typeID; + if(comparisonCache[comboId] != undefined) { + return true; + } + if(assignableTo) { + if(source == this.anyType || target == this.anyType) { + return true; + } + } else { + if(target == this.anyType) { + return true; + } + } + if(source == this.undefinedType) { + return true; + } + if((source == this.nullType) && (target != this.undefinedType && target != this.voidType)) { + return true; + } + if(target == this.numberType && (source.typeFlags & TypeScript.TypeFlags.IsEnum)) { + return true; + } + if(source == this.numberType && (target.typeFlags & TypeScript.TypeFlags.IsEnum)) { + return true; + } + if((source.typeFlags & TypeScript.TypeFlags.IsEnum) || (target.typeFlags & TypeScript.TypeFlags.IsEnum)) { + return false; + } + if(source.isArray() || target.isArray()) { + if(!(source.isArray() && target.isArray())) { + return false; + } + comparisonCache[comboId] = false; + var ret = this.sourceIsRelatableToTarget(source.elementType, target.elementType, assignableTo, comparisonCache, comparisonInfo); + if(ret) { + comparisonCache[comboId] = true; + } else { + comparisonCache[comboId] = undefined; + } + return ret; + } + if(source.primitiveTypeClass != target.primitiveTypeClass) { + if(target.primitiveTypeClass == TypeScript.Primitive.None) { + if(source == this.numberType && this.typeFlow.numberInterfaceType) { + source = this.typeFlow.numberInterfaceType; + } else if(source == this.stringType && this.typeFlow.stringInterfaceType) { + source = this.typeFlow.stringInterfaceType; + } else if(source == this.booleanType && this.typeFlow.booleanInterfaceType) { + source = this.typeFlow.booleanInterfaceType; + } else { + return false; + } + } else { + return false; + } + } + comparisonCache[comboId] = false; + if(source.hasBase(target)) { + comparisonCache[comboId] = true; + return true; + } + if(this.typeFlow.objectInterfaceType && target == this.typeFlow.objectInterfaceType) { + return true; + } + if(this.typeFlow.functionInterfaceType && (source.call || source.construct) && target == this.typeFlow.functionInterfaceType) { + return true; + } + if(target.isClass() || target.isClassInstance()) { + comparisonCache[comboId] = undefined; + return false; + } + if(target.memberScope && source.memberScope) { + var mPropKeys = target.memberScope.getAllValueSymbolNames(true); + var mProp = null; + var nProp = null; + var mPropType = null; + var nPropType = null; + var inferenceSymbol = null; + for(var iMProp = 0; iMProp < mPropKeys.length; iMProp++) { + mProp = target.memberScope.find(mPropKeys[iMProp], false, false); + nProp = source.memberScope.find(mPropKeys[iMProp], false, false); + if(mProp.name == "arguments" && this.typeFlow.iargumentsInterfaceType && (this.typeFlow.iargumentsInterfaceType.symbol.flags & TypeScript.SymbolFlags.CompilerGenerated) && mProp.kind() == TypeScript.SymbolKind.Variable && (mProp).variable.typeLink.type == this.typeFlow.iargumentsInterfaceType) { + continue; + } + if(mProp.isInferenceSymbol()) { + inferenceSymbol = mProp; + if(inferenceSymbol.typeCheckStatus == TypeScript.TypeCheckStatus.NotStarted) { + this.typeFlow.typeCheck(mProp.declAST); + } + } + mPropType = mProp.getType(); + if(!nProp) { + if(this.typeFlow.objectInterfaceType) { + nProp = this.typeFlow.objectInterfaceType.memberScope.find(mPropKeys[iMProp], false, false); + } + if(!nProp) { + if(this.typeFlow.functionInterfaceType && (mPropType.call || mPropType.construct)) { + nProp = this.typeFlow.functionInterfaceType.memberScope.find(mPropKeys[iMProp], false, false); + } + if(!nProp) { + if(!(mProp.flags & TypeScript.SymbolFlags.Optional)) { + comparisonCache[comboId] = undefined; + if(comparisonInfo) { + comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.RequiredPropertyIsMissing; + comparisonInfo.addMessageToFront("Type '" + source.getTypeName() + "' is missing property '" + mPropKeys[iMProp] + "' from type '" + target.getTypeName() + "'"); + } + return false; + } else { + continue; + } + } + } + } + if(nProp.isInferenceSymbol()) { + inferenceSymbol = nProp; + if(inferenceSymbol.typeCheckStatus == TypeScript.TypeCheckStatus.NotStarted) { + this.typeFlow.typeCheck(nProp.declAST); + } + } + nPropType = nProp.getType(); + if(mPropType && nPropType && (comparisonCache[(nPropType.typeID << 16) | mPropType.typeID] != undefined)) { + continue; + } + if(!this.sourceIsRelatableToTarget(nPropType, mPropType, assignableTo, comparisonCache, comparisonInfo)) { + comparisonCache[comboId] = undefined; + if(comparisonInfo) { + comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatiblePropertyTypes; + comparisonInfo.addMessageToFront("Types of property '" + mProp.name + "' of types '" + source.getTypeName() + "' and '" + target.getTypeName() + "' are incompatible"); + } + return false; + } + } + } + if(source.call || target.call) { + if(!this.signatureGroupIsRelatableToTarget(source.call, target.call, assignableTo, comparisonCache, comparisonInfo)) { + if(comparisonInfo) { + if(source.call && target.call) { + comparisonInfo.addMessageToFront("Call signatures of types '" + source.getTypeName() + "' and '" + target.getTypeName() + "' are incompatible"); + } else { + var hasSig = target.call ? target.getTypeName() : source.getTypeName(); + var lacksSig = !target.call ? target.getTypeName() : source.getTypeName(); + comparisonInfo.setMessage("Type '" + hasSig + "' requires a call signature, but Type '" + lacksSig + "' lacks one"); + } + comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleSignatures; + } + comparisonCache[comboId] = undefined; + return false; + } + } + if(source.construct || target.construct) { + if(!this.signatureGroupIsRelatableToTarget(source.construct, target.construct, assignableTo, comparisonCache, comparisonInfo)) { + if(comparisonInfo) { + if(source.construct && target.construct) { + comparisonInfo.addMessageToFront("Construct signatures of types '" + source.getTypeName() + "' and '" + target.getTypeName() + "' are incompatible"); + } else { + var hasSig = target.construct ? target.getTypeName() : source.getTypeName(); + var lacksSig = !target.construct ? target.getTypeName() : source.getTypeName(); + comparisonInfo.setMessage("Type '" + hasSig + "' requires a construct signature, but Type '" + lacksSig + "' lacks one"); + } + comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleSignatures; + } + comparisonCache[comboId] = undefined; + return false; + } + } + if(target.index) { + var targetIndex = !target.index && this.typeFlow.objectInterfaceType ? this.typeFlow.objectInterfaceType.index : target.index; + var sourceIndex = !source.index && this.typeFlow.objectInterfaceType ? this.typeFlow.objectInterfaceType.index : source.index; + if(!this.signatureGroupIsRelatableToTarget(sourceIndex, targetIndex, assignableTo, comparisonCache, comparisonInfo)) { + if(comparisonInfo) { + comparisonInfo.addMessageToFront("Index signatures of types '" + source.getTypeName() + "' and '" + target.getTypeName() + "' are incompatible"); + comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleSignatures; + } + comparisonCache[comboId] = undefined; + return false; + } + } + comparisonCache[comboId] = true; + return true; + }; + TypeChecker.prototype.signatureGroupIsRelatableToTarget = function (sourceSG, targetSG, assignableTo, comparisonCache, comparisonInfo) { + if(sourceSG == targetSG) { + return true; + } + if(!(sourceSG && targetSG)) { + return false; + } + var mSig = null; + var nSig = null; + var foundMatch = false; + for(var iMSig = 0; iMSig < targetSG.signatures.length; iMSig++) { + mSig = targetSG.signatures[iMSig]; + for(var iNSig = 0; iNSig < sourceSG.signatures.length; iNSig++) { + nSig = sourceSG.signatures[iNSig]; + if(this.signatureIsRelatableToTarget(nSig, mSig, assignableTo, comparisonCache, comparisonInfo)) { + foundMatch = true; + break; + } + } + if(foundMatch) { + foundMatch = false; + continue; + } + return false; + } + return true; + }; + TypeChecker.prototype.signatureIsRelatableToTarget = function (sourceSig, targetSig, assignableTo, comparisonCache, comparisonInfo) { + if(!sourceSig.parameters || !targetSig.parameters) { + return false; + } + var targetVarArgCount = targetSig.hasVariableArgList ? targetSig.nonOptionalParameterCount - 1 : targetSig.nonOptionalParameterCount; + var sourceVarArgCount = sourceSig.hasVariableArgList ? sourceSig.nonOptionalParameterCount - 1 : sourceSig.nonOptionalParameterCount; + if(sourceVarArgCount > targetVarArgCount && !targetSig.hasVariableArgList) { + if(comparisonInfo) { + comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.SourceSignatureHasTooManyParameters; + comparisonInfo.addMessageToFront("Call signature expects " + targetVarArgCount + " or fewer parameters"); + } + return false; + } + var sourceReturnType = sourceSig.returnType.type; + var targetReturnType = targetSig.returnType.type; + if(targetReturnType != this.voidType) { + if(!this.sourceIsRelatableToTarget(sourceReturnType, targetReturnType, assignableTo, comparisonCache, comparisonInfo)) { + if(comparisonInfo) { + comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleReturnTypes; + } + return false; + } + } + var len = (sourceVarArgCount < targetVarArgCount && sourceSig.hasVariableArgList) ? targetVarArgCount : sourceVarArgCount; + var sourceParamType = null; + var targetParamType = null; + var sourceParamName = ""; + var targetParamName = ""; + for(var iSource = 0, iTarget = 0; iSource < len; iSource++ , iTarget++) { + if(!sourceSig.hasVariableArgList || iSource < sourceVarArgCount) { + sourceParamType = (sourceSig.parameters[iSource]).parameter.typeLink.type; + sourceParamName = (sourceSig.parameters[iSource]).parameter.symbol.name; + } else if(iSource == sourceVarArgCount) { + sourceParamType = (sourceSig.parameters[iSource]).parameter.typeLink.type; + if(sourceParamType.elementType) { + sourceParamType = sourceParamType.elementType; + } + sourceParamName = (sourceSig.parameters[iSource]).parameter.symbol.name; + } + if(iTarget < targetSig.parameters.length && iTarget < targetVarArgCount) { + targetParamType = (targetSig.parameters[iTarget]).parameter.typeLink.type; + targetParamName = (targetSig.parameters[iTarget]).parameter.symbol.name; + } else if(targetSig.hasVariableArgList && iTarget == targetVarArgCount) { + targetParamType = (targetSig.parameters[iTarget]).parameter.typeLink.type; + if(targetParamType.elementType) { + targetParamType = targetParamType.elementType; + } + targetParamName = (targetSig.parameters[iTarget]).parameter.symbol.name; + } + if(!(this.sourceIsRelatableToTarget(sourceParamType, targetParamType, assignableTo, comparisonCache, comparisonInfo) || this.sourceIsRelatableToTarget(targetParamType, sourceParamType, assignableTo, comparisonCache, comparisonInfo))) { + if(comparisonInfo) { + comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleParameterTypes; + } + return false; + } + } + return true; + }; + return TypeChecker; + })(); + TypeScript.TypeChecker = TypeChecker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Continuation = (function () { + function Continuation(normalBlock) { + this.normalBlock = normalBlock; + this.exceptionBlock = -1; + } + return Continuation; + })(); + TypeScript.Continuation = Continuation; + function getBaseTypeLinks(bases, baseTypeLinks) { + if(bases) { + var len = bases.members.length; + if(baseTypeLinks == null) { + baseTypeLinks = new Array(); + } + for(var i = 0; i < len; i++) { + var baseExpr = bases.members[i]; + var name = baseExpr; + var typeLink = new TypeScript.TypeLink(); + typeLink.ast = name; + baseTypeLinks[baseTypeLinks.length] = typeLink; + } + } + return baseTypeLinks; + } + function getBases(type, typeDecl) { + type.extendsTypeLinks = getBaseTypeLinks(typeDecl.extendsList, type.extendsTypeLinks); + type.implementsTypeLinks = getBaseTypeLinks(typeDecl.implementsList, type.implementsTypeLinks); + } + function addPrototypeField(classType, ast, context) { + var field = new TypeScript.ValueLocation(); + field.typeLink = new TypeScript.TypeLink(); + field.typeLink.ast = ast; + field.typeLink.type = classType.instanceType; + var fieldSymbol = new TypeScript.FieldSymbol("prototype", ast.minChar, context.checker.locationInfo.unitIndex, true, field); + fieldSymbol.flags |= (TypeScript.SymbolFlags.Property | TypeScript.SymbolFlags.BuiltIn); + field.symbol = fieldSymbol; + fieldSymbol.declAST = ast; + classType.members.addPublicMember("prototype", fieldSymbol); + } + function createNewConstructGroupForType(type) { + var signature = new TypeScript.Signature(); + signature.returnType = new TypeScript.TypeLink(); + signature.returnType.type = type.instanceType; + signature.parameters = []; + type.construct = new TypeScript.SignatureGroup(); + type.construct.addSignature(signature); + } + TypeScript.createNewConstructGroupForType = createNewConstructGroupForType; + function cloneParentConstructGroupForChildType(child, parent) { + child.construct = new TypeScript.SignatureGroup(); + var sig = null; + if(!parent.construct) { + createNewConstructGroupForType(parent); + } + for(var i = 0; i < parent.construct.signatures.length; i++) { + sig = new TypeScript.Signature(); + sig.parameters = parent.construct.signatures[i].parameters; + sig.nonOptionalParameterCount = parent.construct.signatures[i].nonOptionalParameterCount; + sig.typeCheckStatus = parent.construct.signatures[i].typeCheckStatus; + sig.declAST = parent.construct.signatures[i].declAST; + sig.returnType = new TypeScript.TypeLink(); + sig.returnType.type = child.instanceType; + child.construct.addSignature(sig); + } + } + TypeScript.cloneParentConstructGroupForChildType = cloneParentConstructGroupForChildType; + TypeScript.globalId = "__GLO"; + function findTypeSymbolInScopeChain(name, scopeChain) { + var symbol = scopeChain.scope.find(name, false, true); + if(symbol == null && scopeChain.previous) { + symbol = findTypeSymbolInScopeChain(name, scopeChain.previous); + } + return symbol; + } + function findSymbolFromAlias(alias, context) { + var symbol = null; + switch(alias.nodeType) { + case TypeScript.NodeType.Name: + var name = (alias).text; + var isDynamic = TypeScript.isQuoted(name); + var findSym = function (id) { + if(context.members) { + return context.members.lookup(name); + } else { + return findTypeSymbolInScopeChain(name, context.topLevelScope); + } + }; + if(isDynamic) { + symbol = context.tcContext.checker.findSymbolForDynamicModule(name, context.tcContext.script.locationInfo.filename, findSym); + } else { + symbol = findSym(name); + } + break; + case TypeScript.NodeType.Dot: + var dottedExpr = alias; + var op1Sym = findSymbolFromAlias(dottedExpr.operand1, context); + if(op1Sym && op1Sym.getType()) { + symbol = findSymbolFromAlias(dottedExpr.operand2, context); + } + break; + default: + break; + } + if(symbol) { + var symType = symbol.getType(); + if(symType) { + var members = symType.members; + if(members) { + context.members = members.publicMembers; + } + } + } + return symbol; + } + function preCollectImportTypes(ast, parent, context) { + var scopeChain = context.scopeChain; + var typeSymbol = null; + var modType = null; + var importDecl = ast; + var aliasedModSymbol = findSymbolFromAlias(importDecl.alias, { + topLevelScope: scopeChain, + members: null, + tcContext: context + }); + var isGlobal = context.scopeChain.container == context.checker.gloMod; + if(aliasedModSymbol) { + var aliasedModType = aliasedModSymbol.getType(); + if(aliasedModType) { + modType = aliasedModType; + } + } + typeSymbol = new TypeScript.TypeSymbol(importDecl.id.text, importDecl.id.minChar, importDecl.limChar - importDecl.minChar, context.checker.locationInfo.unitIndex, modType); + typeSymbol.aliasLink = importDecl; + if(context.scopeChain.moduleDecl) { + typeSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; + typeSymbol.declModule = context.scopeChain.moduleDecl; + } + typeSymbol.declAST = importDecl; + importDecl.id.sym = typeSymbol; + scopeChain.scope.enter(scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isGlobal, true, false); + scopeChain.scope.enter(scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isGlobal, false, false); + return true; + } + TypeScript.preCollectImportTypes = preCollectImportTypes; + function preCollectModuleTypes(ast, parent, context) { + var scopeChain = context.scopeChain; + var moduleDecl = ast; + var isAmbient = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.Ambient); + var isEnum = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsEnum); + var isGlobal = context.scopeChain.container == context.checker.gloMod; + var isExported = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.Exported); + var modName = (moduleDecl.name).text; + var isDynamic = TypeScript.isQuoted(modName); + var symbol = scopeChain.scope.findLocal(modName, false, false); + var typeSymbol = null; + var modType = null; + if(symbol && symbol.declAST && symbol.declAST.nodeType != TypeScript.NodeType.ModuleDeclaration) { + context.checker.errorReporter.simpleError(moduleDecl, "Conflicting symbol name for module '" + modName + "'"); + symbol = null; + modName = ""; + } + if(symbol) { + var modDeclAST = symbol.declAST; + var modDeclASTIsExported = TypeScript.hasFlag(modDeclAST.modFlags, TypeScript.ModuleFlags.Exported); + if((modDeclASTIsExported && !isExported) || (!modDeclASTIsExported && isExported)) { + context.checker.errorReporter.simpleError(moduleDecl, 'All contributions to a module must be "export" or none'); + } + } + if((symbol == null) || (symbol.kind() != TypeScript.SymbolKind.Type)) { + if(modType == null) { + var enclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + var ambientEnclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + modType = new TypeScript.ModuleType(enclosedTypes, ambientEnclosedTypes); + if(isEnum) { + modType.typeFlags |= TypeScript.TypeFlags.IsEnum; + } + modType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + modType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + modType.setHasImplementation(); + } + typeSymbol = new TypeScript.TypeSymbol(modName, moduleDecl.name.minChar, modName.length, context.checker.locationInfo.unitIndex, modType); + typeSymbol.isDynamic = TypeScript.isQuoted(moduleDecl.prettyName); + if(context.scopeChain.moduleDecl) { + typeSymbol.declModule = context.scopeChain.moduleDecl; + } + typeSymbol.declAST = moduleDecl; + typeSymbol.prettyName = moduleDecl.prettyName; + scopeChain.scope.enter(scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, true, isAmbient); + scopeChain.scope.enter(scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, false, isAmbient); + modType.symbol = typeSymbol; + } else { + typeSymbol = symbol; + var publicEnclosedTypes = typeSymbol.type.getAllEnclosedTypes().publicMembers; + var publicEnclosedTypesTable = (publicEnclosedTypes == null) ? new TypeScript.StringHashTable() : publicEnclosedTypes; + var enclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(publicEnclosedTypesTable, new TypeScript.StringHashTable())); + var publicEnclosedAmbientTypes = typeSymbol.type.getAllAmbientEnclosedTypes().publicMembers; + var publicAmbientEnclosedTypesTable = (publicEnclosedAmbientTypes == null) ? new TypeScript.StringHashTable() : publicEnclosedAmbientTypes; + var ambientEnclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(publicAmbientEnclosedTypesTable, new TypeScript.StringHashTable())); + var publicMembers = typeSymbol.type.members.publicMembers; + var publicMembersTable = (publicMembers == null) ? new TypeScript.StringHashTable() : publicMembers; + var members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(publicMembersTable, new TypeScript.StringHashTable())); + var publicAmbientMembers = typeSymbol.type.ambientMembers.publicMembers; + var publicAmbientMembersTable = (publicAmbientMembers == null) ? new TypeScript.StringHashTable() : publicAmbientMembers; + var ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(publicAmbientMembersTable, new TypeScript.StringHashTable())); + modType = new TypeScript.ModuleType(enclosedTypes, ambientEnclosedTypes); + if(isEnum) { + modType.typeFlags |= TypeScript.TypeFlags.IsEnum; + } + modType.members = members; + modType.ambientMembers = ambientMembers; + modType.setHasImplementation(); + modType.symbol = typeSymbol; + typeSymbol.addLocation(moduleDecl.minChar); + typeSymbol.expansions.push(modType); + typeSymbol.expansionsDeclAST.push(moduleDecl); + } + if(context.scopeChain.moduleDecl) { + context.scopeChain.moduleDecl.recordNonInterface(); + } + if(isExported) { + typeSymbol.flags |= TypeScript.SymbolFlags.Exported; + } + if((context.scopeChain.moduleDecl) || (context.scopeChain.container == context.checker.gloMod)) { + typeSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; + } + moduleDecl.mod = modType; + TypeScript.pushTypeCollectionScope(typeSymbol, modType.members, modType.ambientMembers, modType.enclosedTypes, modType.ambientEnclosedTypes, context, null, null, moduleDecl); + return true; + } + TypeScript.preCollectModuleTypes = preCollectModuleTypes; + function preCollectClassTypes(ast, parent, context) { + var scopeChain = context.scopeChain; + var classDecl = ast; + var classType; + var instanceType; + var typeSymbol = null; + var className = (classDecl.name).text; + var alreadyInScope = false; + var isAmbient = TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Ambient); + var isExported = TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Exported); + var isGlobal = context.scopeChain.container == context.checker.gloMod; + var containerMod = scopeChain.container; + var foundValSymbol = false; + typeSymbol = scopeChain.scope.findLocal(className, false, true); + if(!typeSymbol) { + var valTypeSymbol = scopeChain.scope.findLocal(className, false, false); + if(valTypeSymbol && valTypeSymbol.isType() && valTypeSymbol.declAST && valTypeSymbol.declAST.nodeType == TypeScript.NodeType.FuncDecl && (valTypeSymbol.declAST).isSignature()) { + typeSymbol = valTypeSymbol; + foundValSymbol = true; + if(isExported) { + typeSymbol.flags |= TypeScript.SymbolFlags.Exported; + } + if(isAmbient) { + typeSymbol.flags |= TypeScript.SymbolFlags.Ambient; + } + context.scopeChain.scope.enter(context.scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, true, isAmbient); + } + } + if(typeSymbol && !foundValSymbol && (typeSymbol.declAST != classDecl)) { + typeSymbol = null; + } + if(typeSymbol == null) { + var valueSymbol = scopeChain.scope.findLocal(className, false, false); + classType = new TypeScript.Type(); + classType.setHasImplementation(); + instanceType = new TypeScript.Type(); + instanceType.setHasImplementation(); + classType.instanceType = instanceType; + classType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + classType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + addPrototypeField(classType, classDecl, context); + instanceType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + instanceType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + typeSymbol = new TypeScript.TypeSymbol(className, classDecl.name.minChar, className.length, context.checker.locationInfo.unitIndex, classType); + typeSymbol.declAST = classDecl; + typeSymbol.instanceType = instanceType; + classType.symbol = typeSymbol; + instanceType.symbol = typeSymbol; + if(context.scopeChain.moduleDecl) { + context.scopeChain.moduleDecl.recordNonInterface(); + typeSymbol.declModule = context.scopeChain.moduleDecl; + typeSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; + } + if(isExported) { + typeSymbol.flags |= TypeScript.SymbolFlags.Exported; + } + if(isAmbient) { + typeSymbol.flags |= TypeScript.SymbolFlags.Ambient; + } + ast.type = classType; + context.scopeChain.scope.enter(context.scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, true, isAmbient); + if(valueSymbol == null) { + context.scopeChain.scope.enter(context.scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, false, isAmbient); + } + } else { + classType = typeSymbol.type; + if(classType.instanceType == null) { + classType.instanceType = new TypeScript.Type(); + classType.instanceType.setHasImplementation(); + classType.instanceType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + classType.instanceType.symbol = classType.symbol; + classType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + classType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + } + instanceType = classType.instanceType; + ast.type = classType; + } + if(!classDecl.constructorDecl) { + if(typeSymbol && typeSymbol.declAST && typeSymbol.declAST.type && typeSymbol.declAST.type.call && !(typeSymbol.declAST).isOverload) { + context.checker.errorReporter.duplicateIdentifier(typeSymbol.declAST, typeSymbol.name); + } + createNewConstructGroupForType(classDecl.type); + } + classType.typeFlags |= TypeScript.TypeFlags.IsClass; + instanceType.typeFlags |= TypeScript.TypeFlags.IsClass; + getBases(instanceType, classDecl); + TypeScript.pushTypeCollectionScope(typeSymbol, instanceType.members, instanceType.ambientMembers, null, null, context, instanceType, classType, null); + return true; + } + TypeScript.preCollectClassTypes = preCollectClassTypes; + function preCollectInterfaceTypes(ast, parent, context) { + var scopeChain = context.scopeChain; + var interfaceDecl = ast; + var interfaceSymbol = null; + var interfaceType = null; + var isExported = TypeScript.hasFlag(interfaceDecl.varFlags, TypeScript.VarFlags.Exported); + var isGlobal = context.scopeChain.container == context.checker.gloMod; + var alreadyInScope = true; + alreadyInScope = false; + var interfaceName = (interfaceDecl.name).text; + interfaceSymbol = scopeChain.scope.findLocal(interfaceName, false, true); + if(interfaceSymbol == null) { + interfaceType = new TypeScript.Type(); + interfaceSymbol = new TypeScript.TypeSymbol(interfaceName, interfaceDecl.name.minChar, interfaceName.length, context.checker.locationInfo.unitIndex, interfaceType); + interfaceType.symbol = interfaceSymbol; + interfaceType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + interfaceType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + interfaceSymbol.declAST = interfaceDecl; + interfaceSymbol.declModule = context.scopeChain.moduleDecl; + } else { + alreadyInScope = true; + interfaceType = interfaceSymbol.type; + } + if(!interfaceType) { + interfaceType = context.checker.anyType; + } + ast.type = interfaceType; + getBases(interfaceType, interfaceDecl); + if(isExported) { + interfaceSymbol.flags |= TypeScript.SymbolFlags.Exported; + } + if(context.scopeChain.moduleDecl) { + interfaceSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; + } + if(!alreadyInScope) { + context.scopeChain.scope.enter(context.scopeChain.container, ast, interfaceSymbol, context.checker.errorReporter, isGlobal || isExported, true, false); + } + TypeScript.pushTypeCollectionScope(interfaceSymbol, interfaceType.members, interfaceType.ambientMembers, null, null, context, interfaceType, null, null); + return true; + } + TypeScript.preCollectInterfaceTypes = preCollectInterfaceTypes; + function preCollectArgDeclTypes(ast, parent, context) { + var scopeChain = context.scopeChain; + var argDecl = ast; + if(TypeScript.hasFlag(argDecl.varFlags, TypeScript.VarFlags.Public | TypeScript.VarFlags.Private)) { + var field = new TypeScript.ValueLocation(); + var isPrivate = TypeScript.hasFlag(argDecl.varFlags, TypeScript.VarFlags.Private); + var fieldSymbol = new TypeScript.FieldSymbol(argDecl.id.text, argDecl.id.minChar, context.checker.locationInfo.unitIndex, !TypeScript.hasFlag(argDecl.varFlags, TypeScript.VarFlags.Readonly), field); + fieldSymbol.transferVarFlags(argDecl.varFlags); + field.symbol = fieldSymbol; + fieldSymbol.declAST = ast; + argDecl.parameterPropertySym = fieldSymbol; + context.scopeChain.scope.enter(context.scopeChain.container, ast, fieldSymbol, context.checker.errorReporter, !isPrivate, false, false); + field.typeLink = TypeScript.getTypeLink(argDecl.typeExpr, context.checker, argDecl.init == null); + argDecl.sym = fieldSymbol; + } + return false; + } + TypeScript.preCollectArgDeclTypes = preCollectArgDeclTypes; + function preCollectVarDeclTypes(ast, parent, context) { + var scopeChain = context.scopeChain; + var varDecl = ast; + var isAmbient = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Ambient); + var isExported = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Exported); + var isGlobal = context.scopeChain.container == context.checker.gloMod; + var isProperty = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Property); + var isStatic = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static); + var isPrivate = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Private); + var isOptional = TypeScript.hasFlag(varDecl.id.flags, TypeScript.ASTFlags.OptionalName); + if(context.scopeChain.moduleDecl) { + context.scopeChain.moduleDecl.recordNonInterface(); + } + if(isProperty || isExported || (context.scopeChain.container == context.checker.gloMod) || context.scopeChain.moduleDecl) { + if(isAmbient) { + var existingSym = scopeChain.scope.findLocal(varDecl.id.text, false, false); + if(existingSym) { + varDecl.sym = existingSym; + return false; + } + } + if(varDecl.id == null) { + context.checker.errorReporter.simpleError(varDecl, "Expected variable identifier at this location"); + return false; + } + var field = new TypeScript.ValueLocation(); + var fieldSymbol = new TypeScript.FieldSymbol(varDecl.id.text, varDecl.id.minChar, context.checker.locationInfo.unitIndex, (varDecl.varFlags & TypeScript.VarFlags.Readonly) == TypeScript.VarFlags.None, field); + fieldSymbol.transferVarFlags(varDecl.varFlags); + if(isOptional) { + fieldSymbol.flags |= TypeScript.SymbolFlags.Optional; + } + field.symbol = fieldSymbol; + fieldSymbol.declAST = ast; + if((context.scopeChain.moduleDecl) || (context.scopeChain.container == context.checker.gloMod)) { + fieldSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; + fieldSymbol.declModule = context.scopeChain.moduleDecl; + } + if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Property) && isStatic && context.scopeChain.classType) { + if(!context.scopeChain.classType.members.publicMembers.add(varDecl.id.text, fieldSymbol)) { + context.checker.errorReporter.duplicateIdentifier(ast, fieldSymbol.name); + } + fieldSymbol.container = context.scopeChain.classType.symbol; + } else { + context.scopeChain.scope.enter(context.scopeChain.container, ast, fieldSymbol, context.checker.errorReporter, !isPrivate && (isProperty || isExported || isGlobal || isStatic), false, isAmbient); + } + if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Exported)) { + fieldSymbol.flags |= TypeScript.SymbolFlags.Exported; + } + field.typeLink = TypeScript.getTypeLink(varDecl.typeExpr, context.checker, varDecl.init == null); + varDecl.sym = fieldSymbol; + } + return false; + } + TypeScript.preCollectVarDeclTypes = preCollectVarDeclTypes; + function preCollectFuncDeclTypes(ast, parent, context) { + var scopeChain = context.scopeChain; + if(context.scopeChain.moduleDecl) { + context.scopeChain.moduleDecl.recordNonInterface(); + } + var funcDecl = ast; + var fgSym = null; + var nameText = funcDecl.getNameText(); + var isExported = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Exported | TypeScript.FncFlags.ClassPropertyMethodExported); + var isStatic = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static); + var isPrivate = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Private); + var isConstructor = funcDecl.isConstructMember() || funcDecl.isConstructor; + var containerSym = (((funcDecl.isMethod() && isStatic) || funcDecl.isAccessor()) && context.scopeChain.classType ? context.scopeChain.classType.symbol : context.scopeChain.container); + var containerScope = context.scopeChain.scope; + var isGlobal = containerSym == context.checker.gloMod; + var isOptional = funcDecl.name && TypeScript.hasFlag(funcDecl.name.flags, TypeScript.ASTFlags.OptionalName); + var go = false; + var foundSymbol = false; + if(isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { + containerSym = containerSym.container; + containerScope = scopeChain.previous.scope; + } + funcDecl.unitIndex = context.checker.locationInfo.unitIndex; + if(!funcDecl.isConstructor && containerSym && containerSym.declAST && containerSym.declAST.nodeType == TypeScript.NodeType.FuncDecl && (containerSym.declAST).isConstructor && !funcDecl.isMethod()) { + return go; + } + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Signature)) { + var instType = context.scopeChain.thisType; + if(nameText && nameText != "__missing") { + if(isStatic) { + fgSym = containerSym.type.members.allMembers.lookup(nameText); + } else { + fgSym = containerScope.findLocal(nameText, false, false); + if(fgSym == null) { + fgSym = containerScope.findLocal(nameText, false, true); + } + } + if(fgSym) { + foundSymbol = true; + if(!funcDecl.isSignature() && (TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Ambient) != TypeScript.hasFlag(fgSym.flags, TypeScript.SymbolFlags.Ambient))) { + fgSym = null; + } + } + } + if(fgSym == null) { + if(!(funcDecl.isSpecialFn())) { + fgSym = context.checker.createFunctionSignature(funcDecl, containerSym, containerScope, null, !foundSymbol).declAST.type.symbol; + } else { + fgSym = context.checker.createFunctionSignature(funcDecl, containerSym, containerScope, containerSym, false).declAST.type.symbol; + } + if(fgSym.declAST == null || !funcDecl.isSpecialFn()) { + fgSym.declAST = ast; + } + } else { + if((fgSym.kind() == TypeScript.SymbolKind.Type)) { + fgSym = context.checker.createFunctionSignature(funcDecl, containerSym, containerScope, fgSym, false).declAST.type.symbol; + } else { + context.checker.errorReporter.simpleError(funcDecl, "Function or method '" + funcDecl.name.actualText + "' already declared as a property"); + } + } + if(funcDecl.isSpecialFn() && !isStatic) { + funcDecl.type = instType ? instType : fgSym.type; + } else { + funcDecl.type = fgSym.type; + } + } else { + if(nameText) { + if(isStatic) { + fgSym = containerSym.type.members.allMembers.lookup(nameText); + } else { + if(funcDecl.isConstructor && context.scopeChain.previous) { + fgSym = context.scopeChain.previous.scope.findLocal(nameText, false, false); + } + if(fgSym == null) { + fgSym = containerScope.findLocal(nameText, false, false); + } + } + if(fgSym) { + foundSymbol = true; + if(!isConstructor && fgSym.declAST.nodeType == TypeScript.NodeType.FuncDecl && !(fgSym.declAST).isAccessor() && !(fgSym.declAST).isSignature()) { + fgSym = null; + foundSymbol = false; + } + } + } + if(fgSym && !fgSym.isAccessor() && fgSym.type && fgSym.type.construct && fgSym.type.construct.signatures != [] && (fgSym.type.construct.signatures[0].declAST == null || !TypeScript.hasFlag(fgSym.type.construct.signatures[0].declAST.fncFlags, TypeScript.FncFlags.Ambient)) && !funcDecl.isConstructor) { + context.checker.errorReporter.simpleError(funcDecl, "Functions may not have class overloads"); + } + if(fgSym && !(fgSym.kind() == TypeScript.SymbolKind.Type) && funcDecl.isMethod() && !funcDecl.isAccessor() && !funcDecl.isConstructor) { + context.checker.errorReporter.simpleError(funcDecl, "Function or method '" + funcDecl.name.actualText + "' already declared as a property"); + fgSym.type = context.checker.anyType; + } + if(fgSym && !fgSym.isAccessor() && funcDecl.isAccessor()) { + fgSym = null; + } + var sig = context.checker.createFunctionSignature(funcDecl, containerSym, containerScope, fgSym, !foundSymbol); + if(((!fgSym || fgSym.declAST.nodeType != TypeScript.NodeType.FuncDecl) && funcDecl.isAccessor()) || (fgSym && fgSym.isAccessor())) { + funcDecl.accessorSymbol = context.checker.createAccessorSymbol(funcDecl, fgSym, containerSym.type, (funcDecl.isMethod() && isStatic), true, containerScope, containerSym); + } + funcDecl.type.symbol.declAST = ast; + if(funcDecl.isConstructor) { + go = true; + } + ; + } + if(isExported) { + if(funcDecl.type.call) { + funcDecl.type.symbol.flags |= TypeScript.SymbolFlags.Exported; + } + if(fgSym && !fgSym.isAccessor() && fgSym.kind() == TypeScript.SymbolKind.Type && fgSym.type.call) { + fgSym.flags |= TypeScript.SymbolFlags.Exported; + } + } + if(context.scopeChain.moduleDecl && !funcDecl.isSpecialFn()) { + funcDecl.type.symbol.flags |= TypeScript.SymbolFlags.ModuleMember; + funcDecl.type.symbol.declModule = context.scopeChain.moduleDecl; + } + if(fgSym && isOptional) { + fgSym.flags |= TypeScript.SymbolFlags.Optional; + } + return go; + } + TypeScript.preCollectFuncDeclTypes = preCollectFuncDeclTypes; + function preCollectTypes(ast, parent, walker) { + var context = walker.state; + var go = false; + var scopeChain = context.scopeChain; + if(ast.nodeType == TypeScript.NodeType.Script) { + var script = ast; + context.script = script; + go = true; + } else if(ast.nodeType == TypeScript.NodeType.List) { + go = true; + } else if(ast.nodeType == TypeScript.NodeType.ImportDeclaration) { + go = preCollectImportTypes(ast, parent, context); + } else if(ast.nodeType == TypeScript.NodeType.With) { + go = false; + } else if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { + go = preCollectModuleTypes(ast, parent, context); + } else if(ast.nodeType == TypeScript.NodeType.ClassDeclaration) { + go = preCollectClassTypes(ast, parent, context); + } else if(ast.nodeType == TypeScript.NodeType.Block) { + go = true; + } else if(ast.nodeType == TypeScript.NodeType.InterfaceDeclaration) { + go = preCollectInterfaceTypes(ast, parent, context); + } else if(ast.nodeType == TypeScript.NodeType.ArgDecl) { + go = preCollectArgDeclTypes(ast, parent, context); + } else if(ast.nodeType == TypeScript.NodeType.VarDecl) { + go = preCollectVarDeclTypes(ast, parent, context); + } else if(ast.nodeType == TypeScript.NodeType.FuncDecl) { + go = preCollectFuncDeclTypes(ast, parent, context); + } else { + if(ast.isStatementOrExpression() && context.scopeChain.moduleDecl) { + context.scopeChain.moduleDecl.recordNonInterface(); + } + } + walker.options.goChildren = go; + return ast; + } + TypeScript.preCollectTypes = preCollectTypes; + function postCollectTypes(ast, parent, walker) { + var context = walker.state; + if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { + TypeScript.popTypeCollectionScope(context); + } else if(ast.nodeType == TypeScript.NodeType.ClassDeclaration) { + TypeScript.popTypeCollectionScope(context); + } else if(ast.nodeType == TypeScript.NodeType.InterfaceDeclaration) { + TypeScript.popTypeCollectionScope(context); + } + return ast; + } + TypeScript.postCollectTypes = postCollectTypes; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ScopeChain = (function () { + function ScopeChain(container, previous, scope) { + this.container = container; + this.previous = previous; + this.scope = scope; + } + return ScopeChain; + })(); + TypeScript.ScopeChain = ScopeChain; + var BBUseDefInfo = (function () { + function BBUseDefInfo(bb) { + this.bb = bb; + this.defsBySymbol = new Array(); + this.useIndexBySymbol = new Array(); + } + BBUseDefInfo.prototype.updateTop = function () { + var temp = new BitVector(this.top.bitCount); + for(var i = 0, succLen = this.bb.successors.length; i < succLen; i++) { + var succ = this.bb.successors[i]; + if(succ.useDef) { + temp.union(succ.useDef.top); + } + } + temp.difference(this.kill); + temp.union(this.gen); + var changed = temp.notEq(this.top); + this.top = temp; + return changed; + }; + BBUseDefInfo.prototype.initialize = function (useDefContext) { + var _this = this; + var defSym = function (sym, context) { + if(context.isLocalSym(sym)) { + var index = context.getSymbolIndex(sym); + _this.useIndexBySymbol[index] = new Array(); + _this.defsBySymbol[index] = true; + } + }; + var useSym = function (sym, context, ast) { + if(context.isLocalSym(sym)) { + var symIndex = context.getSymbolIndex(sym); + if(_this.useIndexBySymbol[symIndex] == undefined) { + _this.useIndexBySymbol[symIndex] = new Array(); + } + var symUses = _this.useIndexBySymbol[symIndex]; + var astIndex = context.getUseIndex(ast); + context.addUse(symIndex, astIndex); + symUses.push(astIndex); + } + }; + function initUseDefPre(cur, parent, walker) { + var context = walker.state; + if(cur == null) { + cur = null; + } + if(cur.nodeType == TypeScript.NodeType.VarDecl) { + var varDecl = cur; + if(varDecl.init || TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.AutoInit)) { + defSym(varDecl.sym, context); + } + } else if(cur.nodeType == TypeScript.NodeType.Name) { + if(parent) { + if(parent.nodeType == TypeScript.NodeType.Asg) { + var asg = parent; + if(asg.operand1 == cur) { + return cur; + } + } else if(parent.nodeType == TypeScript.NodeType.VarDecl) { + var parentDecl = parent; + if(parentDecl.id == cur) { + return cur; + } + } + } + var id = cur; + useSym(id.sym, context, cur); + } else if((cur.nodeType >= TypeScript.NodeType.Asg) && (cur.nodeType <= TypeScript.NodeType.LastAsg)) { + var asg = cur; + if(asg.operand1 && (asg.operand1.nodeType == TypeScript.NodeType.Name)) { + var id = asg.operand1; + defSym(id.sym, context); + } + } else if(cur.nodeType == TypeScript.NodeType.FuncDecl) { + walker.options.goChildren = false; + } + return cur; + } + var options = new TypeScript.AstWalkOptions(); + options.reverseSiblings = true; + TypeScript.getAstWalkerFactory().walk(this.bb.content, initUseDefPre, null, options, useDefContext); + }; + BBUseDefInfo.prototype.initializeGen = function (useDefContext) { + var symbolLen = this.useIndexBySymbol.length; + var bitCount = useDefContext.uses.length; + this.gen = new BitVector(bitCount); + for(var s = 0; s < symbolLen; s++) { + var symUses = this.useIndexBySymbol[s]; + if((symUses != undefined) && (symUses.length > 0)) { + for(var u = 0, uLen = symUses.length; u < uLen; u++) { + this.gen.set(symUses[u], true); + } + } + } + this.top = this.gen; + }; + BBUseDefInfo.prototype.initializeKill = function (useDefContext) { + this.kill = new BitVector(this.gen.bitCount); + for(var s = 0, symbolLen = this.defsBySymbol.length; s < symbolLen; s++) { + if(this.defsBySymbol[s]) { + var globalSymUses = useDefContext.useIndexBySymbol[s]; + if(globalSymUses) { + for(var u = 0, useLen = globalSymUses.length; u < useLen; u++) { + this.kill.set(globalSymUses[u], true); + } + } + } + } + }; + return BBUseDefInfo; + })(); + TypeScript.BBUseDefInfo = BBUseDefInfo; + var UseDefContext = (function () { + function UseDefContext() { + this.useIndexBySymbol = new Array(); + this.uses = new Array(); + this.symbols = new Array(); + this.symbolMap = new TypeScript.StringHashTable(); + this.symbolCount = 0; + } + UseDefContext.prototype.getSymbolIndex = function (sym) { + var name = sym.name; + var index = (this.symbolMap.lookup(name)); + if(index == null) { + index = this.symbolCount++; + this.symbols[index] = sym; + this.symbolMap.add(name, index); + } + return index; + }; + UseDefContext.prototype.addUse = function (symIndex, astIndex) { + var useBySym = this.useIndexBySymbol[symIndex]; + if(useBySym == undefined) { + useBySym = new Array(); + this.useIndexBySymbol[symIndex] = useBySym; + } + useBySym[useBySym.length] = astIndex; + }; + UseDefContext.prototype.getUseIndex = function (ast) { + this.uses[this.uses.length] = ast; + return this.uses.length - 1; + }; + UseDefContext.prototype.isLocalSym = function (sym) { + return (sym && (sym.container == this.func) && (sym.kind() == TypeScript.SymbolKind.Variable)); + }; + UseDefContext.prototype.killSymbol = function (sym, bbUses) { + var index = this.symbolMap.lookup(sym.name); + var usesOfSym = this.useIndexBySymbol[index]; + for(var k = 0, len = usesOfSym.length; k < len; k++) { + bbUses.set(usesOfSym[k], true); + } + }; + return UseDefContext; + })(); + TypeScript.UseDefContext = UseDefContext; + var BitVector = (function () { + function BitVector(bitCount) { + this.bitCount = bitCount; + this.firstBits = 0; + this.restOfBits = null; + if(this.bitCount > BitVector.packBits) { + this.restOfBits = new Array(); + var len = Math.floor(this.bitCount / BitVector.packBits); + for(var i = 0; i < len; i++) { + this.restOfBits[i] = 0; + } + } + } + BitVector.packBits = 30; + BitVector.prototype.set = function (bitIndex, value) { + if(bitIndex < BitVector.packBits) { + if(value) { + this.firstBits |= (1 << bitIndex); + } else { + this.firstBits &= (~(1 << bitIndex)); + } + } else { + var offset = Math.floor(bitIndex / BitVector.packBits) - 1; + var localIndex = bitIndex % BitVector.packBits; + if(value) { + this.restOfBits[offset] |= (1 << localIndex); + } else { + this.restOfBits[offset] &= (~(1 << localIndex)); + } + } + }; + BitVector.prototype.map = function (fn) { + var k; + for(k = 0; k < BitVector.packBits; k++) { + if(k == this.bitCount) { + return; + } + if(((1 << k) & this.firstBits) != 0) { + fn(k); + } + } + if(this.restOfBits) { + var len; + var cumu = BitVector.packBits; + for(k = 0 , len = this.restOfBits.length; k < len; k++) { + var myBits = this.restOfBits[k]; + for(var j = 0; j < BitVector.packBits; j++) { + if(((1 << j) & myBits) != 0) { + fn(cumu); + } + cumu++; + if(cumu == this.bitCount) { + return; + } + } + } + } + }; + BitVector.prototype.union = function (b) { + this.firstBits |= b.firstBits; + if(this.restOfBits) { + for(var k = 0, len = this.restOfBits.length; k < len; k++) { + var myBits = this.restOfBits[k]; + var bBits = b.restOfBits[k]; + this.restOfBits[k] = myBits | bBits; + } + } + }; + BitVector.prototype.intersection = function (b) { + this.firstBits &= b.firstBits; + if(this.restOfBits) { + for(var k = 0, len = this.restOfBits.length; k < len; k++) { + var myBits = this.restOfBits[k]; + var bBits = b.restOfBits[k]; + this.restOfBits[k] = myBits & bBits; + } + } + }; + BitVector.prototype.notEq = function (b) { + if(this.firstBits != b.firstBits) { + return true; + } + if(this.restOfBits) { + for(var k = 0, len = this.restOfBits.length; k < len; k++) { + var myBits = this.restOfBits[k]; + var bBits = b.restOfBits[k]; + if(myBits != bBits) { + return true; + } + } + } + return false; + }; + BitVector.prototype.difference = function (b) { + var oldFirstBits = this.firstBits; + this.firstBits &= (~b.firstBits); + if(this.restOfBits) { + for(var k = 0, len = this.restOfBits.length; k < len; k++) { + var myBits = this.restOfBits[k]; + var bBits = b.restOfBits[k]; + this.restOfBits[k] &= (~bBits); + } + } + }; + return BitVector; + })(); + TypeScript.BitVector = BitVector; + var BasicBlock = (function () { + function BasicBlock() { + this.predecessors = new Array(); + this.index = -1; + this.markValue = 0; + this.successors = new Array(); + this.useDef = null; + this.content = new TypeScript.ASTList(); + } + BasicBlock.prototype.marked = function (markBase) { + return this.markValue > markBase; + }; + BasicBlock.prototype.mark = function () { + this.markValue++; + }; + BasicBlock.prototype.addSuccessor = function (successor) { + this.successors[this.successors.length] = successor; + successor.predecessors[successor.predecessors.length] = this; + }; + return BasicBlock; + })(); + TypeScript.BasicBlock = BasicBlock; + var ControlFlowContext = (function () { + function ControlFlowContext(current, exit) { + this.current = current; + this.exit = exit; + this.entry = null; + this.unreachable = null; + this.noContinuation = false; + this.statementStack = new Array(); + this.currentSwitch = new Array(); + this.markBase = 0; + this.linearBBs = new Array(); + this.entry = this.current; + } + ControlFlowContext.prototype.walk = function (ast, parent) { + return this.walker.walk(ast, parent); + }; + ControlFlowContext.prototype.pushSwitch = function (bb) { + this.currentSwitch.push(bb); + }; + ControlFlowContext.prototype.popSwitch = function () { + return this.currentSwitch.pop(); + }; + ControlFlowContext.prototype.reportUnreachable = function (er) { + if(this.unreachable && (this.unreachable.length > 0)) { + var len = this.unreachable.length; + for(var i = 0; i < len; i++) { + var unreachableAST = this.unreachable[i]; + if(unreachableAST.nodeType != TypeScript.NodeType.EndCode) { + er.simpleError(unreachableAST, "unreachable code"); + } + } + } + }; + ControlFlowContext.prototype.printAST = function (ast, outfile) { + var printContext = new TypeScript.PrintContext(outfile, null); + printContext.increaseIndent(); + TypeScript.getAstWalkerFactory().walk(ast, TypeScript.prePrintAST, TypeScript.postPrintAST, null, printContext); + printContext.decreaseIndent(); + }; + ControlFlowContext.prototype.printBlockContent = function (bb, outfile) { + var content = bb.content; + for(var i = 0, len = content.members.length; i < len; i++) { + var ast = content.members[i]; + this.printAST(ast, outfile); + } + }; + ControlFlowContext.prototype.bfs = function (nodeFunc, edgeFunc, preEdges, postEdges) { + var markValue = this.markBase++; + var q = new Array(); + q[q.length] = this.entry; + while(q.length > 0) { + var bb = q.pop(); + if(!(bb.marked(markValue))) { + bb.mark(); + if(nodeFunc) { + nodeFunc(bb); + } + var succLen = bb.successors.length; + if(succLen > 0) { + if(preEdges) { + preEdges(); + } + for(var j = succLen - 1; j >= 0; j--) { + var successor = bb.successors[j]; + if(!(successor.marked(this.markBase))) { + if(edgeFunc) { + edgeFunc(bb, successor); + } + q[q.length] = successor; + } + } + if(postEdges) { + postEdges(); + } + } + } + } + }; + ControlFlowContext.prototype.useDef = function (er, funcSym) { + var _this = this; + var useDefContext = new UseDefContext(); + useDefContext.func = funcSym; + var useDefInit = function (bb) { + bb.useDef = new BBUseDefInfo(bb); + bb.useDef.initialize(useDefContext); + _this.linearBBs[_this.linearBBs.length] = bb; + }; + this.bfs(useDefInit, null, null, null); + var i, bbLen; + for(i = 0 , bbLen = this.linearBBs.length; i < bbLen; i++) { + this.linearBBs[i].useDef.initializeGen(useDefContext); + this.linearBBs[i].useDef.initializeKill(useDefContext); + } + var changed = true; + while(changed) { + changed = false; + for(i = 0; i < bbLen; i++) { + changed = this.linearBBs[i].useDef.updateTop() || changed; + } + } + var top = this.entry.useDef.top; + top.map(function (index) { + var ast = useDefContext.uses[index]; + er.simpleError(ast, "use of variable '" + ast.actualText + "' that is not definitely assigned"); + }); + }; + ControlFlowContext.prototype.print = function (outfile) { + var _this = this; + var index = 0; + var node = function (bb) { + if(bb.index < 0) { + bb.index = index++; + } + if(bb == _this.exit) { + outfile.WriteLine("Exit block with index " + bb.index); + } else { + outfile.WriteLine("Basic block with index " + bb.index); + _this.printBlockContent(bb, outfile); + } + }; + function preEdges() { + outfile.Write(" Branches to "); + } + function postEdges() { + outfile.WriteLine(""); + } + function edge(node1, node2) { + if(node2.index < 0) { + node2.index = index++; + } + outfile.Write(node2.index + " "); + } + this.bfs(node, edge, preEdges, postEdges); + if(this.unreachable != null) { + for(var i = 0, len = this.unreachable.length; i < len; i++) { + outfile.WriteLine("Unreachable basic block ..."); + this.printAST(this.unreachable[i], outfile); + } + } + }; + ControlFlowContext.prototype.pushStatement = function (stmt, continueBB, breakBB) { + this.statementStack.push({ + stmt: stmt, + continueBB: continueBB, + breakBB: breakBB + }); + }; + ControlFlowContext.prototype.popStatement = function () { + return this.statementStack.pop(); + }; + ControlFlowContext.prototype.returnStmt = function () { + this.current.addSuccessor(this.exit); + this.setUnreachable(); + }; + ControlFlowContext.prototype.setUnreachable = function () { + this.current = null; + this.noContinuation = true; + }; + ControlFlowContext.prototype.addUnreachable = function (ast) { + if(this.unreachable === null) { + this.unreachable = new Array(); + } + this.unreachable[this.unreachable.length] = ast; + }; + ControlFlowContext.prototype.unconditionalBranch = function (target, isContinue) { + var targetBB = null; + for(var i = 0, len = this.statementStack.length; i < len; i++) { + var targetInfo = this.statementStack[i]; + if(targetInfo.stmt == target) { + if(isContinue) { + targetBB = targetInfo.continueBB; + } else { + targetBB = targetInfo.breakBB; + } + break; + } + } + if(targetBB) { + this.current.addSuccessor(targetBB); + } + this.setUnreachable(); + }; + ControlFlowContext.prototype.addContent = function (ast) { + if(this.current) { + this.current.content.append(ast); + } + }; + return ControlFlowContext; + })(); + TypeScript.ControlFlowContext = ControlFlowContext; + var ResolutionDataCache = (function () { + function ResolutionDataCache() { + this.cacheSize = 16; + this.rdCache = []; + this.nextUp = 0; + for(var i = 0; i < this.cacheSize; i++) { + this.rdCache[i] = { + actuals: new Array(), + exactCandidates: new Array(), + conversionCandidates: new Array(), + id: i + }; + } + } + ResolutionDataCache.prototype.getResolutionData = function () { + var rd = null; + if(this.nextUp < this.cacheSize) { + rd = this.rdCache[this.nextUp]; + } + if(rd == null) { + this.cacheSize++; + rd = { + actuals: new Array(), + exactCandidates: new Array(), + conversionCandidates: new Array(), + id: this.cacheSize + }; + this.rdCache[this.cacheSize] = rd; + } + this.nextUp++; + return rd; + }; + ResolutionDataCache.prototype.returnResolutionData = function (rd) { + rd.actuals.length = 0; + rd.exactCandidates.length = 0; + rd.conversionCandidates.length = 0; + this.nextUp = rd.id; + }; + return ResolutionDataCache; + })(); + TypeScript.ResolutionDataCache = ResolutionDataCache; + var TypeFlow = (function () { + function TypeFlow(logger, initScope, parser, checker) { + this.logger = logger; + this.initScope = initScope; + this.parser = parser; + this.checker = checker; + this.thisFnc = null; + this.thisClassNode = null; + this.enclosingFncIsMethod = false; + this.arrayInterfaceType = null; + this.stringInterfaceType = null; + this.objectInterfaceType = null; + this.functionInterfaceType = null; + this.numberInterfaceType = null; + this.booleanInterfaceType = null; + this.iargumentsInterfaceType = null; + this.currentScript = null; + this.inImportTypeCheck = false; + this.inTypeRefTypeCheck = false; + this.inArrayElementTypeCheck = false; + this.resolutionDataCache = new ResolutionDataCache(); + this.nestingLevel = 0; + this.inSuperCall = false; + this.checker.typeFlow = this; + this.scope = this.initScope; + this.globalScope = this.initScope; + this.doubleType = this.checker.numberType; + this.booleanType = this.checker.booleanType; + this.stringType = this.checker.stringType; + this.anyType = this.checker.anyType; + this.regexType = this.anyType; + this.nullType = this.checker.nullType; + this.voidType = this.checker.voidType; + this.arrayAnyType = this.checker.makeArrayType(this.anyType); + } + TypeFlow.prototype.initLibs = function () { + var arraySym = this.globalScope.find("Array", false, true); + if(arraySym && (arraySym.kind() == TypeScript.SymbolKind.Type)) { + this.arrayInterfaceType = (arraySym).type; + } + var stringSym = this.globalScope.find("String", false, true); + if(stringSym && (stringSym.kind() == TypeScript.SymbolKind.Type)) { + this.stringInterfaceType = (stringSym).type; + } + var objectSym = this.globalScope.find("Object", false, true); + if(objectSym && (objectSym.kind() == TypeScript.SymbolKind.Type)) { + this.objectInterfaceType = (objectSym).type; + } + var fnSym = this.globalScope.find("Function", false, true); + if(fnSym && (fnSym.kind() == TypeScript.SymbolKind.Type)) { + this.functionInterfaceType = (fnSym).type; + } + var numberSym = this.globalScope.find("Number", false, true); + if(numberSym && (numberSym.kind() == TypeScript.SymbolKind.Type)) { + this.numberInterfaceType = (numberSym).type; + } + var booleanSym = this.globalScope.find("Boolean", false, true); + if(booleanSym && (booleanSym.kind() == TypeScript.SymbolKind.Type)) { + this.booleanInterfaceType = (booleanSym).type; + } + var regexSym = this.globalScope.find("RegExp", false, true); + if(regexSym && (regexSym.kind() == TypeScript.SymbolKind.Type)) { + this.regexType = (regexSym).type; + } + }; + TypeFlow.prototype.cast = function (ast, type) { + return this.castWithCoercion(ast, type, true, false); + }; + TypeFlow.prototype.castWithCoercion = function (ast, type, applyCoercion, typeAssertion) { + var comparisonInfo = new TypeScript.TypeComparisonInfo(); + if(this.checker.sourceIsAssignableToTarget(ast.type, type, comparisonInfo) || (typeAssertion && this.checker.sourceIsAssignableToTarget(type, ast.type, comparisonInfo))) { + if(applyCoercion) { + if(type == null) { + ast.type = this.anyType; + } else if(type.isClass()) { + ast.type = type.instanceType; + } else { + ast.type = type; + } + } + return ast; + } else { + this.checker.errorReporter.incompatibleTypes(ast, ast.type, type, null, this.scope, comparisonInfo); + return ast; + } + }; + TypeFlow.prototype.inScopeTypeCheck = function (ast, enclosingScope) { + var prevScope = this.scope; + this.scope = enclosingScope; + var svThisFnc = this.thisFnc; + var svThisType = this.thisType; + var svThisClassNode = this.thisClassNode; + var svCurrentModDecl = this.checker.currentModDecl; + var prevMethodStatus = this.enclosingFncIsMethod; + var container = this.scope.container; + var fnc = null; + while(container) { + if(container.kind() == TypeScript.SymbolKind.Type) { + var typeSym = container; + var type = typeSym.type; + if(type.call) { + if(fnc == null) { + this.enclosingFncIsMethod = typeSym.isMethod; + fnc = container.declAST; + } + } + if(type.isClass()) { + this.thisType = type.instanceType; + if(typeSym.declAST && (typeSym.declAST.nodeType == TypeScript.NodeType.ClassDeclaration)) { + this.thisClassNode = typeSym.declAST; + } + break; + } + if(type.isModuleType()) { + this.checker.currentModDecl = typeSym.declAST; + break; + } + } + container = container.container; + } + this.thisFnc = fnc; + var updated = this.typeCheck(ast); + this.thisFnc = svThisFnc; + this.thisType = svThisType; + this.thisClassNode = svThisClassNode; + this.checker.currentModDecl = svCurrentModDecl; + this.enclosingFncIsMethod = prevMethodStatus; + this.scope = prevScope; + return updated; + }; + TypeFlow.prototype.typeCheck = function (ast) { + if(ast) { + return ast.typeCheck(this); + } else { + return null; + } + }; + TypeFlow.prototype.inScopeTypeCheckDecl = function (ast) { + if(ast.nodeType == TypeScript.NodeType.VarDecl || ast.nodeType == TypeScript.NodeType.ArgDecl) { + this.inScopeTypeCheckBoundDecl(ast); + } else if(ast.nodeType == TypeScript.NodeType.FuncDecl) { + var funcDecl = ast; + if(funcDecl.isAccessor()) { + this.typeCheckFunction(funcDecl); + } + } + }; + TypeFlow.prototype.inScopeTypeCheckBoundDecl = function (varDecl) { + var sym = varDecl.sym; + var svThisFnc = this.thisFnc; + var svThisType = this.thisType; + var prevMethodStatus = this.enclosingFncIsMethod; + var prevLocationInfo = this.checker.locationInfo; + if(sym && sym.container) { + var instanceScope = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.ClassConstructorProperty) ? sym.container.getType().constructorScope : sym.container.instanceScope(); + if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Property) && sym.container.declAST.nodeType == TypeScript.NodeType.FuncDecl) { + this.thisFnc = sym.container.declAST; + } + if(instanceScope) { + var prevScope = this.scope; + this.scope = instanceScope; + var container = sym.container; + var svCurrentModDecl = this.checker.currentModDecl; + if(this.checker.units && (sym.unitIndex >= 0) && (sym.unitIndex < this.checker.units.length)) { + this.checker.locationInfo = this.checker.units[sym.unitIndex]; + } else { + this.checker.locationInfo = TypeScript.unknownLocationInfo; + } + while(container) { + if(container.kind() == TypeScript.SymbolKind.Type) { + var typeSym = container; + var type = typeSym.type; + if(type.call) { + this.enclosingFncIsMethod = typeSym.isMethod; + } + if(type.isClass()) { + this.thisType = type.instanceType; + } + if(type.isModuleType()) { + this.checker.currentModDecl = container.declAST; + break; + } + } + container = container.container; + } + this.typeCheckBoundDecl(varDecl); + this.checker.currentModDecl = svCurrentModDecl; + this.scope = prevScope; + } + } + this.thisFnc = svThisFnc; + this.thisType = svThisType; + this.checker.locationInfo = prevLocationInfo; + this.enclosingFncIsMethod = prevMethodStatus; + }; + TypeFlow.prototype.resolveBoundDecl = function (varDecl) { + if(varDecl.typeExpr) { + if(varDecl.typeExpr.type == null || (varDecl.typeExpr.type && varDecl.typeExpr.type == this.anyType && this.scope) || varDecl.typeExpr.type.symbol == null || !this.checker.typeStatusIsFinished(varDecl.typeExpr.type.symbol.typeCheckStatus)) { + this.typeCheck(varDecl.typeExpr); + } + varDecl.type = varDecl.typeExpr.type; + if(varDecl.sym) { + varDecl.sym.setType(varDecl.type); + } + } else if(varDecl.init == null) { + if(this.checker.styleSettings.implicitAny) { + this.checker.errorReporter.styleError(varDecl, "type implicitly set to 'any'"); + } + varDecl.type = this.anyType; + if(varDecl.sym) { + if(varDecl.sym.isType()) { + var tsym = varDecl.sym; + if(tsym.isMethod) { + this.checker.errorReporter.simpleError(varDecl, "Cannot bind method group to variable. (Did you mean to use 'declare function' instead of 'declare var'?)"); + return; + } else { + this.checker.errorReporter.simpleError(varDecl, "Cannot bind type to variable"); + return; + } + } + varDecl.sym.setType(varDecl.type); + } + } + }; + TypeFlow.prototype.typeCheckBoundDecl = function (varDecl) { + var _this = this; + var infSym = varDecl.sym; + if(infSym == null) { + if(varDecl.init) { + varDecl.init = this.typeCheck(varDecl.init); + varDecl.type = this.checker.widenType(varDecl.init.type); + } else { + if(this.checker.styleSettings.implicitAny) { + this.checker.errorReporter.styleError(varDecl, "type implicitly set to 'any'"); + } + varDecl.type = this.anyType; + } + } else { + if(infSym.typeCheckStatus == TypeScript.TypeCheckStatus.Started) { + if(this.checker.styleSettings.implicitAny) { + this.checker.errorReporter.styleError(varDecl, "type implicitly set to 'any'"); + } + varDecl.type = this.anyType; + infSym.setType(this.anyType); + } else if(infSym.typeCheckStatus == TypeScript.TypeCheckStatus.NotStarted) { + infSym.typeCheckStatus = TypeScript.TypeCheckStatus.Started; + this.checker.addStartedPTO(infSym); + var resolved = false; + if(varDecl.type == null) { + if(varDecl.typeExpr) { + this.resolveBoundDecl(varDecl); + resolved = true; + varDecl.type = varDecl.typeExpr.type; + infSym.typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); + } + } + if(varDecl.init) { + var isLocalStatic = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.LocalStatic); + var prevScope = this.scope; + var applyTargetType = !varDecl.init.isParenthesized; + if(isLocalStatic) { + this.scope = varDecl.sym.container.getType().memberScope; + } + if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Property) && this.thisClassNode) { + TypeScript.getAstWalkerFactory().walk(varDecl.init, function (ast, parent, walker) { + if(ast && ast.nodeType == TypeScript.NodeType.FuncDecl) { + if(TypeScript.hasFlag((ast).fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { + (ast).fncFlags |= TypeScript.FncFlags.IsPropertyBound; + } + walker.options.goChildren = false; + } + return ast; + }); + } + this.checker.typeCheckWithContextualType(varDecl.type, this.checker.inProvisionalTypecheckMode(), applyTargetType, varDecl.init); + this.scope = prevScope; + if(varDecl.type) { + var preserveScope = false; + var preservedContainedScope = null; + if(varDecl.init.type) { + preservedContainedScope = varDecl.init.type.containedScope; + preserveScope = true; + if(varDecl.init.type == this.voidType) { + this.checker.errorReporter.simpleError(varDecl, "Cannot assign type 'void' to variable '" + varDecl.id.actualText + "'"); + } + } + varDecl.init = this.castWithCoercion(varDecl.init, varDecl.type, applyTargetType && !this.checker.inProvisionalTypecheckMode(), false); + if(preserveScope && varDecl.init.type.containedScope == null) { + varDecl.init.type.containedScope = preservedContainedScope; + } + } else { + varDecl.type = this.checker.widenType(varDecl.init.type); + if(varDecl.type == this.voidType) { + this.checker.errorReporter.simpleError(varDecl, "Cannot assign type 'void' to variable '" + varDecl.id.actualText + "'"); + varDecl.type = this.anyType; + } + } + infSym.setType(varDecl.type); + } else { + if(!resolved) { + this.resolveBoundDecl(varDecl); + } + } + infSym.typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); + } else if(this.checker.typeStatusIsFinished(infSym.typeCheckStatus) && (infSym.declAST != varDecl)) { + if(varDecl.init) { + varDecl.init = this.typeCheck(varDecl.init); + varDecl.type = infSym.getType(); + varDecl.init = this.cast(varDecl.init, varDecl.type); + } + } + } + if(varDecl.id && varDecl.sym) { + varDecl.id.sym = varDecl.sym; + } + if(varDecl.sym && varDecl.sym.container) { + this.checkTypePrivacy(varDecl.sym.getType(), varDecl.sym, function (typeName, isModuleName) { + return _this.varPrivacyErrorReporter(varDecl, typeName, isModuleName); + }); + } + return varDecl; + }; + TypeFlow.prototype.varPrivacyErrorReporter = function (varDecl, typeName, isModuleName) { + var typestring = ""; + if(isModuleName) { + var quotestring = ""; + if(!TypeScript.isQuoted(typeName)) { + quotestring = "'"; + } + typestring = " is using inaccessible module " + quotestring + typeName + quotestring; + } else { + typestring = " has or is using private type '" + typeName + "'"; + } + if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Public)) { + if(varDecl.sym.container.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) { + this.checker.errorReporter.simpleError(varDecl, "property '" + varDecl.sym.name + "' of exported interface" + typestring); + } else { + this.checker.errorReporter.simpleError(varDecl, "public member '" + varDecl.sym.name + "' of exported class" + typestring); + } + } else { + this.checker.errorReporter.simpleError(varDecl, "exported variable '" + varDecl.sym.name + "'" + typestring); + } + }; + TypeFlow.prototype.typeCheckSuper = function (ast) { + if(this.thisType && (this.enclosingFncIsMethod && !this.thisFnc.isStatic()) && this.thisType.baseClass()) { + ast.type = this.thisType.baseClass(); + } else { + if(!this.enclosingFncIsMethod && this.thisType && this.thisType.baseClass() && this.thisFnc && TypeScript.hasFlag(this.thisFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { + var enclosingFnc = this.thisFnc.enclosingFnc; + while(TypeScript.hasFlag(enclosingFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { + enclosingFnc = enclosingFnc.enclosingFnc; + } + if(enclosingFnc && (enclosingFnc.isMethod() || enclosingFnc.isConstructor) && !enclosingFnc.isStatic()) { + ast.type = this.thisType.baseClass(); + enclosingFnc.setHasSuperReferenceInFatArrowFunction(); + return ast; + } + } + ast.type = this.anyType; + this.checker.errorReporter.invalidSuperReference(ast); + } + return ast; + }; + TypeFlow.prototype.typeCheckThis = function (ast) { + ast.type = this.anyType; + var illegalThisRef = false; + if(this.thisFnc == null) { + if(this.thisType) { + if(this.thisClassNode && this.thisClassNode.nodeType == TypeScript.NodeType.ClassDeclaration) { + illegalThisRef = true; + } else { + ast.type = this.thisType; + } + } else if(this.checker.currentModDecl) { + this.checker.errorReporter.simpleError(ast, "'this' may not be referenced within module bodies"); + } + } else { + if(this.thisClassNode && (TypeScript.hasFlag(this.thisFnc.fncFlags, TypeScript.FncFlags.IsPropertyBound) || (this.inSuperCall && TypeScript.hasFlag((this.thisClassNode).varFlags, TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor)))) { + illegalThisRef = true; + } + if(this.thisFnc.isMethod() || this.thisFnc.isConstructor) { + if(this.thisType && !(this.thisFnc.fncFlags & TypeScript.FncFlags.Static)) { + ast.type = this.thisType; + } + } + } + if(!this.enclosingFncIsMethod && this.thisFnc && TypeScript.hasFlag(this.thisFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { + if(this.thisFnc.boundToProperty) { + var container = this.thisFnc.boundToProperty.sym.container; + if(container.declAST.nodeType == TypeScript.NodeType.FuncDecl) { + (container.declAST).setHasSelfReference(); + } + } else { + var encFnc = this.thisFnc.enclosingFnc; + var firstEncFnc = encFnc; + while(encFnc) { + if(this.thisClassNode && TypeScript.hasFlag(encFnc.fncFlags, TypeScript.FncFlags.IsPropertyBound)) { + illegalThisRef = true; + } + if(!TypeScript.hasFlag(encFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction) || encFnc.hasSelfReference()) { + encFnc.setHasSelfReference(); + break; + } + encFnc = encFnc.enclosingFnc; + } + if(!encFnc && firstEncFnc) { + encFnc = firstEncFnc; + encFnc.setHasSelfReference(); + } else if(!encFnc) { + if(this.thisClassNode) { + (this.thisClassNode).varFlags |= TypeScript.VarFlags.MustCaptureThis; + } else if(this.checker.currentModDecl) { + this.checker.currentModDecl.modFlags |= TypeScript.ModuleFlags.MustCaptureThis; + } else { + this.checker.mustCaptureGlobalThis = true; + } + } + if(encFnc && (encFnc.isMethod() || encFnc.isConstructor) && this.thisType && !TypeScript.hasFlag(encFnc.fncFlags, TypeScript.FncFlags.Static)) { + ast.type = this.thisType; + } + } + } + if(illegalThisRef) { + this.checker.errorReporter.simpleError(ast, "Keyword 'this' cannot be referenced in initializers in a class body, or in super constructor calls"); + } + return ast; + }; + TypeFlow.prototype.setTypeFromSymbol = function (ast, symbol) { + if(symbol.isVariable()) { + if(symbol.isInferenceSymbol()) { + var infSym = symbol; + if(infSym.declAST && !this.checker.typeStatusIsFinished(infSym.typeCheckStatus)) { + if(infSym.typeCheckStatus == TypeScript.TypeCheckStatus.Started) { + infSym.declAST.type = this.anyType; + infSym.setType(this.anyType); + } else { + this.inScopeTypeCheckDecl(infSym.declAST); + } + } + if(!this.checker.styleSettings.innerScopeDeclEscape) { + if(infSym.declAST && (infSym.declAST.nodeType == TypeScript.NodeType.VarDecl)) { + if(this.nestingLevel < (infSym.declAST).nestingLevel) { + this.checker.errorReporter.styleError(ast, "Illegal reference to a variable defined in more nested scope"); + } + } + } + } + ast.type = symbol.getType(); + if(!symbol.writeable()) { + ast.flags = ast.flags & (~(TypeScript.ASTFlags.Writeable)); + } + } else if(symbol.isType()) { + ast.type = symbol.getType(); + ast.flags = ast.flags & (~(TypeScript.ASTFlags.Writeable)); + } else { + ast.type = this.anyType; + this.checker.errorReporter.symbolDoesNotReferToAValue(ast, symbol.name); + } + }; + TypeFlow.prototype.typeCheckName = function (ast) { + var _this = this; + var identifier = ast; + if(this.checker.inWith) { + identifier.type = this.anyType; + } else { + var typespace = this.inTypeRefTypeCheck; + var idText = identifier.text; + var originalIdText = idText; + var isDynamicModuleName = TypeScript.isQuoted(identifier.text); + var symbol = this.scope.find(idText, false, typespace); + if(symbol == null && isDynamicModuleName) { + symbol = this.checker.findSymbolForDynamicModule(idText, this.currentScript.locationInfo.filename, function (id) { + return _this.scope.find(id, false, typespace); + }); + } + if(!symbol) { + if(!identifier.isMissing()) { + this.checker.errorReporter.unresolvedSymbol(identifier, identifier.text); + } + identifier.type = this.anyType; + } else { + if(TypeScript.optimizeModuleCodeGen && symbol && symbol.isType()) { + var symType = symbol.getType(); + if(symType && (symbol).aliasLink && (symbol).onlyReferencedAsTypeRef) { + var modDecl = symType.symbol.declAST; + if(modDecl && TypeScript.hasFlag(modDecl.modFlags, TypeScript.ModuleFlags.IsDynamic)) { + (symbol).onlyReferencedAsTypeRef = this.inTypeRefTypeCheck; + } + } + } + if(symbol.declAST && symbol.declAST.nodeType == TypeScript.NodeType.FuncDecl && !(symbol.declAST).returnTypeAnnotation && (symbol.declAST).signature.typeCheckStatus == TypeScript.TypeCheckStatus.Started) { + (symbol.declAST).type.symbol.flags |= TypeScript.SymbolFlags.RecursivelyReferenced; + (symbol.declAST).signature.returnType.type = this.anyType; + } + this.setTypeFromSymbol(ast, symbol); + identifier.sym = symbol; + if(this.thisFnc) { + if(this.thisFnc.type && symbol.container != this.thisFnc.type.symbol) { + this.thisFnc.freeVariables[this.thisFnc.freeVariables.length] = symbol; + } + } + } + } + return ast; + }; + TypeFlow.prototype.typeCheckScript = function (script) { + this.checker.locationInfo = script.locationInfo; + this.scope = this.checker.globalScope; + if(!script.topLevelMod) { + this.addLocalsFromScope(this.scope, this.checker.gloMod, script.vars, this.checker.globals, true); + } + this.currentScript = script; + script.bod = this.typeCheck(script.bod); + this.currentScript = null; + return script; + }; + TypeFlow.prototype.typeCheckBitNot = function (ast) { + var unex = ast; + unex.operand = this.typeCheck(unex.operand); + unex.type = this.doubleType; + return unex; + }; + TypeFlow.prototype.typeCheckUnaryNumberOperator = function (ast) { + var unex = ast; + unex.operand = this.typeCheck(unex.operand); + unex.type = this.doubleType; + return ast; + }; + TypeFlow.prototype.typeCheckLogNot = function (ast) { + var unex = ast; + unex.operand = this.typeCheck(unex.operand); + unex.type = this.booleanType; + return unex; + }; + TypeFlow.prototype.astIsWriteable = function (ast) { + return TypeScript.hasFlag(ast.flags, TypeScript.ASTFlags.Writeable); + }; + TypeFlow.prototype.typeCheckIncOrDec = function (ast) { + var unex = ast; + var lval = unex.operand; + if(!this.astIsWriteable(unex)) { + this.checker.errorReporter.valueCannotBeModified(unex); + unex.type = this.doubleType; + } else { + unex = this.typeCheckUnaryNumberOperator(ast); + if(unex.operand.type != this.checker.numberType && unex.operand.type != this.checker.anyType && !(unex.operand.type.typeFlags & TypeScript.TypeFlags.IsEnum)) { + this.checker.errorReporter.simpleError(ast, "'++' and '--' may only be applied to operands of type 'number' or 'any'"); + } + } + return unex; + }; + TypeFlow.prototype.typeCheckBitwiseOperator = function (ast, assignment) { + var binex = ast; + var resultType = null; + binex.operand1 = this.typeCheck(binex.operand1); + binex.operand2 = this.typeCheck(binex.operand2); + var leftType = binex.operand1.type; + var rightType = binex.operand2.type; + if(assignment && (!this.astIsWriteable(binex))) { + this.checker.errorReporter.valueCannotBeModified(binex); + } + if(this.checker.styleSettings.bitwise) { + this.checker.errorReporter.styleError(ast, "use of " + TypeScript.nodeTypeTable[binex.nodeType]); + } + if(this.checker.sourceIsSubtypeOfTarget(leftType, this.doubleType) && (this.checker.sourceIsSubtypeOfTarget(rightType, this.doubleType))) { + resultType = this.doubleType; + } else if((leftType == this.booleanType) && (rightType == this.booleanType)) { + resultType = this.booleanType; + } else if(leftType == this.anyType) { + if((rightType == this.anyType) || (rightType == this.doubleType) || (rightType == this.booleanType)) { + resultType = this.anyType; + } + } else if(rightType == this.anyType) { + if((leftType == this.anyType) || (leftType == this.doubleType) || (leftType == this.booleanType)) { + resultType = this.anyType; + } + } + if(resultType == null) { + resultType = this.anyType; + this.checker.errorReporter.incompatibleTypes(binex, leftType, rightType, binex.printLabel(), this.scope); + } + binex.type = resultType; + return binex; + }; + TypeFlow.prototype.typeCheckArithmeticOperator = function (ast, assignment) { + var binex = ast; + binex.operand1 = this.typeCheck(binex.operand1); + binex.operand2 = this.typeCheck(binex.operand2); + var leftType = binex.operand1.type; + var rightType = binex.operand2.type; + if(assignment && (!this.astIsWriteable(binex.operand1))) { + this.checker.errorReporter.valueCannotBeModified(binex); + } + if(this.checker.styleSettings.bitwise && ((binex.nodeType == TypeScript.NodeType.And) || (binex.nodeType == TypeScript.NodeType.Or) || (binex.nodeType == TypeScript.NodeType.AsgAnd) || (binex.nodeType == TypeScript.NodeType.AsgOr))) { + this.checker.errorReporter.styleError(ast, "use of " + TypeScript.nodeTypeTable[binex.nodeType]); + } + var nodeType = binex.nodeType; + if(this.checker.isNullOrUndefinedType(leftType)) { + leftType = rightType; + } + if(this.checker.isNullOrUndefinedType(rightType)) { + rightType = leftType; + } + leftType = this.checker.widenType(leftType); + rightType = this.checker.widenType(rightType); + if(nodeType == TypeScript.NodeType.Add || nodeType == TypeScript.NodeType.AsgAdd) { + if(leftType == this.checker.stringType || rightType == this.checker.stringType) { + binex.type = this.checker.stringType; + } else if(leftType == this.checker.numberType && rightType == this.checker.numberType) { + binex.type = this.checker.numberType; + } else if(this.checker.sourceIsSubtypeOfTarget(leftType, this.checker.numberType) && this.checker.sourceIsSubtypeOfTarget(rightType, this.checker.numberType)) { + binex.type = this.checker.numberType; + } else if(leftType == this.checker.anyType || rightType == this.checker.anyType) { + binex.type = this.checker.anyType; + } else { + binex.type = this.anyType; + this.checker.errorReporter.incompatibleTypes(binex, leftType, rightType, binex.printLabel(), this.scope); + } + } else { + if(leftType == this.checker.numberType && rightType == this.checker.numberType) { + binex.type = this.checker.numberType; + } else if(this.checker.sourceIsSubtypeOfTarget(leftType, this.checker.numberType) && this.checker.sourceIsSubtypeOfTarget(rightType, this.checker.numberType)) { + binex.type = this.checker.numberType; + } else if(leftType == this.checker.anyType || rightType == this.checker.anyType) { + binex.type = this.checker.numberType; + } else { + binex.type = this.anyType; + this.checker.errorReporter.incompatibleTypes(binex, leftType, rightType, binex.printLabel(), this.scope); + } + } + return binex; + }; + TypeFlow.prototype.typeCheckDotOperator = function (ast) { + var binex = ast; + var leftIsFnc = false; + binex.operand1 = this.typeCheck(binex.operand1); + var leftType = binex.operand1.type; + var leftScope = null; + if(leftType) { + if(leftType == this.anyType) { + binex.type = this.anyType; + return binex; + } else if(leftType == this.stringType) { + if(this.stringInterfaceType) { + leftScope = this.stringInterfaceType.memberScope; + } else { + binex.type = this.anyType; + return binex; + } + } else if(leftType == this.doubleType) { + if(this.numberInterfaceType) { + leftScope = this.numberInterfaceType.memberScope; + } else { + binex.type = this.anyType; + return binex; + } + } else if(leftType == this.booleanType) { + if(this.booleanInterfaceType) { + leftScope = this.booleanInterfaceType.memberScope; + } else { + binex.type = this.anyType; + return binex; + } + } else if((leftType.call || leftType.construct) && leftType.members == null) { + if(this.functionInterfaceType) { + leftScope = this.functionInterfaceType.memberScope; + } else { + binex.type = this.anyType; + return binex; + } + } else if(leftType.elementType) { + if(this.arrayInterfaceType) { + var arrInstType = leftType.elementType.getArrayBase(this.arrayInterfaceType, this.checker); + leftScope = arrInstType.memberScope; + } else { + binex.type = this.anyType; + return binex; + } + } else { + leftScope = leftType.memberScope; + } + } + if(leftScope == null) { + this.checker.errorReporter.expectedClassOrInterface(binex); + binex.type = this.anyType; + } else { + var propertyName = binex.operand2; + var lhsIsEnclosingType = (this.thisClassNode && binex.operand1.type == this.thisClassNode.type.instanceType) || this.inTypeRefTypeCheck; + var symbol = leftScope.find(propertyName.text, !lhsIsEnclosingType, this.inTypeRefTypeCheck); + if(!symbol) { + if(this.objectInterfaceType && leftType) { + if(leftType.isReferenceType()) { + symbol = this.objectInterfaceType.memberScope.find(propertyName.text, false, this.inTypeRefTypeCheck); + } + if(!symbol) { + if(this.functionInterfaceType && (leftType.call || leftType.construct)) { + symbol = this.functionInterfaceType.memberScope.find(propertyName.text, false, this.inTypeRefTypeCheck); + } + } + } + } + if(!symbol || (!symbol.visible(leftScope, this.checker))) { + binex.type = this.anyType; + if(symbol == null) { + this.checker.errorReporter.simpleError(propertyName, "The property '" + propertyName.actualText + "' does not exist on value of type '" + leftType.getScopedTypeName(this.scope) + "'"); + } else if(!this.inTypeRefTypeCheck) { + this.checker.errorReporter.simpleError(binex, "The property '" + propertyName.actualText + " on type '" + leftType.getScopedTypeName(this.scope) + "' is not visible"); + } + } else { + if(symbol.isVariable()) { + if(symbol.isInferenceSymbol()) { + var infSym = symbol; + if(infSym.declAST && !this.checker.typeStatusIsFinished(infSym.typeCheckStatus)) { + this.inScopeTypeCheckDecl(infSym.declAST); + } + } + } + propertyName.sym = symbol; + binex.type = symbol.getType(); + } + } + if(binex.type == null) { + binex.type = this.anyType; + } + return binex; + }; + TypeFlow.prototype.typeCheckBooleanOperator = function (ast) { + var binex = ast; + binex.operand1 = this.typeCheck(binex.operand1); + binex.operand2 = this.typeCheck(binex.operand2); + var leftType = binex.operand1.type; + var rightType = binex.operand2.type; + if((!(this.checker.sourceIsAssignableToTarget(leftType, rightType))) && (!(this.checker.sourceIsAssignableToTarget(rightType, leftType)))) { + this.checker.errorReporter.incompatibleTypes(binex, leftType, rightType, binex.printLabel(), this.scope); + } + binex.type = this.booleanType; + return binex; + }; + TypeFlow.prototype.typeCheckAsgOperator = function (ast) { + var binex = ast; + var applyTargetType = !binex.operand2.isParenthesized; + binex.operand1 = this.typeCheck(binex.operand1); + this.checker.typeCheckWithContextualType(binex.operand1.type, this.checker.inProvisionalTypecheckMode(), applyTargetType, binex.operand2); + var leftType = binex.operand1.type; + var rightType = binex.operand2.type; + if(!(this.astIsWriteable(binex.operand1))) { + this.checker.errorReporter.valueCannotBeModified(binex); + } + if(binex.operand1.nodeType == TypeScript.NodeType.Call) { + var callEx = binex.operand1; + } + var preserveScope = false; + var preservedContainedScope = null; + if(binex.operand2.type) { + preservedContainedScope = binex.operand2.type.containedScope; + preserveScope = true; + } + binex.operand2 = this.castWithCoercion(binex.operand2, leftType, applyTargetType && !this.checker.inProvisionalTypecheckMode(), false); + if(preserveScope && binex.operand2.type.containedScope == null) { + binex.operand2.type.containedScope = preservedContainedScope; + } + binex.type = rightType; + return binex; + }; + TypeFlow.prototype.typeCheckIndex = function (ast) { + var binex = ast; + binex.operand1 = this.typeCheck(binex.operand1); + binex.operand2 = this.typeCheck(binex.operand2); + if(!this.checker.styleSettings.literalSubscript) { + if(binex.operand2.nodeType == TypeScript.NodeType.QString) { + this.checker.errorReporter.styleError(ast, "use literal subscript ('.') notation instead)"); + } + } + var objExprType = binex.operand1.type; + var indexExprType = binex.operand2.type; + if(objExprType.elementType) { + if(indexExprType == this.checker.anyType || indexExprType == this.checker.numberType || TypeScript.hasFlag(indexExprType.typeFlags, TypeScript.TypeFlags.IsEnum)) { + binex.type = objExprType.elementType; + } else if(indexExprType == this.checker.stringType) { + binex.type = this.checker.anyType; + } else { + this.checker.errorReporter.simpleError(binex, "Illegal property access"); + binex.type = this.checker.anyType; + } + } else if(objExprType.index) { + if(indexExprType == this.checker.anyType || !((objExprType.index.flags & TypeScript.SignatureFlags.IsStringIndexer) || (objExprType.index.flags & TypeScript.SignatureFlags.IsNumberIndexer)) || ((objExprType.index.flags & TypeScript.SignatureFlags.IsStringIndexer) && indexExprType == this.checker.stringType) || ((objExprType.index.flags & TypeScript.SignatureFlags.IsNumberIndexer) && (indexExprType == this.checker.numberType || TypeScript.hasFlag(indexExprType.typeFlags, TypeScript.TypeFlags.IsEnum)))) { + var sig = this.resolveOverload(ast, objExprType.index); + if(sig) { + binex.type = sig.returnType.type; + } else { + binex.type = this.checker.anyType; + } + } else if(indexExprType == this.checker.stringType) { + binex.type = this.checker.anyType; + } else { + this.checker.errorReporter.simpleError(binex, "Illegal property access"); + binex.type = this.checker.anyType; + } + } else if((objExprType == this.checker.anyType || objExprType == this.checker.stringType || objExprType == this.checker.numberType || objExprType == this.checker.booleanType || objExprType.isReferenceType()) && (indexExprType == this.checker.anyType || indexExprType == this.checker.stringType || (indexExprType == this.checker.numberType || TypeScript.hasFlag(indexExprType.typeFlags, TypeScript.TypeFlags.IsEnum)))) { + binex.type = this.checker.anyType; + } else { + this.checker.errorReporter.simpleError(binex, "Illegal property access"); + binex.type = this.checker.anyType; + } + return binex; + }; + TypeFlow.prototype.typeCheckInOperator = function (binex) { + binex.operand1 = this.cast(this.typeCheck(binex.operand1), this.stringType); + binex.operand2 = this.typeCheck(binex.operand2); + if(!((binex.operand1.type == this.checker.anyType || binex.operand1.type == this.checker.stringType) && (binex.operand2.type == this.anyType || this.checker.sourceIsSubtypeOfTarget(binex.operand2.type, this.objectInterfaceType)))) { + this.checker.errorReporter.simpleError(binex, "The in operator requires the left operand to be of type Any or the String primitive type, and the right operand to be of type Any or an object type"); + } + binex.type = this.booleanType; + return binex; + }; + TypeFlow.prototype.typeCheckShift = function (binex, assignment) { + binex.operand1 = this.cast(this.typeCheck(binex.operand1), this.doubleType); + binex.operand2 = this.cast(this.typeCheck(binex.operand2), this.doubleType); + if(assignment && (!(this.astIsWriteable(binex.operand1)))) { + this.checker.errorReporter.valueCannotBeModified(binex); + } + binex.type = this.doubleType; + return binex; + }; + TypeFlow.prototype.typeCheckQMark = function (trinex) { + trinex.operand1 = this.typeCheck(trinex.operand1); + trinex.operand2 = this.typeCheck(trinex.operand2); + trinex.operand3 = this.typeCheck(trinex.operand3); + var leftType = trinex.operand2.type; + var rightType = trinex.operand3.type; + if(leftType == rightType) { + trinex.type = leftType; + } else { + if(this.checker.sourceIsSubtypeOfTarget(leftType, rightType)) { + trinex.type = rightType; + } else if(this.checker.sourceIsSubtypeOfTarget(rightType, leftType)) { + trinex.type = leftType; + } else { + trinex.type = this.anyType; + this.checker.errorReporter.incompatibleTypes(trinex, leftType, rightType, trinex.printLabel(), this.scope); + } + } + return trinex; + }; + TypeFlow.prototype.addFormals = function (container, signature, table) { + var len = signature.parameters.length; + for(var i = 0; i < len; i++) { + var symbol = signature.parameters[i]; + symbol.container = container; + table.add(symbol.name, symbol); + } + }; + TypeFlow.prototype.addLocalsFromScope = function (scope, container, vars, table, isModContainer) { + var len = vars.members.length; + var hasArgsDef = false; + for(var i = 0; i < len; i++) { + var local = vars.members[i]; + if(((local.sym == null) || (local.sym.kind() != TypeScript.SymbolKind.Field))) { + var result = null; + if((result = table.lookup(local.id.text)) == null) { + var localVar = new TypeScript.ValueLocation(); + localVar.typeLink = new TypeScript.TypeLink(); + var varSym = null; + if(TypeScript.hasFlag(local.varFlags, TypeScript.VarFlags.Static)) { + local.varFlags |= TypeScript.VarFlags.LocalStatic; + varSym = new TypeScript.FieldSymbol(local.id.text, local.minChar, this.checker.locationInfo.unitIndex, true, localVar); + } else { + varSym = new TypeScript.VariableSymbol(local.id.text, local.minChar, this.checker.locationInfo.unitIndex, localVar); + } + varSym.transferVarFlags(local.varFlags); + localVar.symbol = varSym; + varSym.declAST = local; + localVar.typeLink.ast = local.typeExpr; + this.checker.resolveTypeLink(scope, localVar.typeLink, false); + if((local.type == null) && (local.init == null)) { + local.type = this.anyType; + } + localVar.typeLink.type = local.type; + localVar.symbol.container = container; + local.sym = localVar.symbol; + table.add(local.id.text, varSym); + if(local.id.text == "arguments") { + hasArgsDef = true; + } + } else { + local.type = result.getType(); + local.sym = result; + } + } + } + if(!isModContainer) { + if(!hasArgsDef) { + var argLoc = new TypeScript.ValueLocation(); + argLoc.typeLink = new TypeScript.TypeLink(); + var theArgSym = new TypeScript.VariableSymbol("arguments", vars.minChar, this.checker.locationInfo.unitIndex, argLoc); + if(!this.iargumentsInterfaceType) { + var argumentsSym = scope.find("IArguments", false, true); + if(argumentsSym) { + argumentsSym.flags |= TypeScript.SymbolFlags.CompilerGenerated; + this.iargumentsInterfaceType = argumentsSym.getType(); + } else { + this.iargumentsInterfaceType = this.anyType; + } + } + argLoc.typeLink.type = this.iargumentsInterfaceType; + table.add("arguments", theArgSym); + } + } + }; + TypeFlow.prototype.addConstructorLocalArgs = function (constructorDecl, table, isClass) { + var container = constructorDecl.type.symbol; + var args = constructorDecl.arguments; + if(args) { + var len = args.members.length; + for(var i = 0; i < len; i++) { + var local = args.members[i]; + if((local.sym == null) || (isClass || (local.sym.kind() != TypeScript.SymbolKind.Field))) { + var result = null; + if((result = table.lookup(local.id.text)) == null) { + this.resolveBoundDecl(local); + var localVar = new TypeScript.ValueLocation(); + localVar.typeLink = new TypeScript.TypeLink(); + var varSym = new TypeScript.ParameterSymbol(local.id.text, local.minChar, this.checker.locationInfo.unitIndex, localVar); + varSym.funcDecl = constructorDecl; + varSym.declAST = local; + localVar.symbol = varSym; + localVar.typeLink.type = local.type; + localVar.symbol.container = container; + local.sym = localVar.symbol; + table.add(local.id.text, varSym); + } else { + local.type = result.getType(); + local.sym = result; + } + } + } + } + }; + TypeFlow.prototype.checkInitSelf = function (funcDecl) { + if(!funcDecl.isMethod()) { + var freeVars = funcDecl.freeVariables; + for(var k = 0, len = freeVars.length; k < len; k++) { + var sym = freeVars[k]; + if(sym.isInstanceProperty()) { + return true; + } + } + } + var fns = funcDecl.scopes; + var fnsLen = fns.members.length; + for(var j = 0; j < fnsLen; j++) { + var fn = fns.members[j]; + if(this.checkInitSelf(fn)) { + return true; + } + } + return false; + }; + TypeFlow.prototype.checkPromoteFreeVars = function (funcDecl, constructorSym) { + var freeVars = funcDecl.freeVariables; + for(var k = 0, len = freeVars.length; k < len; k++) { + var sym = freeVars[k]; + if((!sym.isInstanceProperty()) && (sym.container == constructorSym)) { + TypeScript.instanceFilter.reset(); + if(this.scope.search(TypeScript.instanceFilter, sym.name, false, false)) { + this.checker.errorReporter.simpleError(funcDecl, "Constructor-local variable shadows class property '" + sym.name + "'. To access the class property, use 'self." + sym.name + "'"); + } + this.checker.errorReporter.simpleError(funcDecl, "Constructor-local variables may not be accessed from instance method bodies. Consider changing local variable '" + sym.name + "' to a class property"); + } + } + }; + TypeFlow.prototype.allReturnsAreVoid = function (funcDecl) { + var allReturnsAreVoid = true; + if(funcDecl.signature.returnType.type == null) { + var preFindReturnExpressionTypes = function (ast, parent, walker) { + var go = true; + switch(ast.nodeType) { + case TypeScript.NodeType.FuncDecl: + go = false; + break; + case TypeScript.NodeType.Return: + var returnStmt = ast; + if(returnStmt.returnExpression) { + allReturnsAreVoid = false; + go = false; + } + default: + break; + } + walker.options.goChildren = go; + walker.options.goNextSibling = go; + return ast; + }; + TypeScript.getAstWalkerFactory().walk(funcDecl.bod, preFindReturnExpressionTypes); + } + return allReturnsAreVoid; + }; + TypeFlow.prototype.classConstructorHasSuperCall = function (funcDecl) { + var foundSuper = false; + var preFindSuperCall = function (ast, parent, walker) { + var go = true; + switch(ast.nodeType) { + case TypeScript.NodeType.FuncDecl: + go = false; + break; + case TypeScript.NodeType.Call: + var call = ast; + if(call.target.nodeType == TypeScript.NodeType.Super) { + go = false; + foundSuper = true; + break; + } + break; + default: + break; + } + walker.options.goChildren = go; + return ast; + }; + TypeScript.getAstWalkerFactory().walk(funcDecl.bod, preFindSuperCall); + return foundSuper; + }; + TypeFlow.prototype.baseListPrivacyErrorReporter = function (bases, i, declSymbol, extendsList, typeName, isModuleName) { + var baseSymbol = bases.members[i].type.symbol; + var declTypeString = (declSymbol.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) ? "interface" : "class"; + var baseListTypeString = extendsList ? "extends" : "implements"; + var baseTypeString = (baseSymbol.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) ? "interface" : "class"; + var typestring = ""; + if(isModuleName) { + var quotestring = ""; + if(!TypeScript.isQuoted(typeName)) { + quotestring = "'"; + } + typestring = " is using inaccessible module "; + baseTypeString = " " + baseTypeString + " from private module " + quotestring + typeName + quotestring; + } else { + baseTypeString = " private " + baseTypeString + " '" + typeName + "'"; + } + this.checker.errorReporter.simpleError(bases.members[i], "exported " + declTypeString + " '" + declSymbol.name + "' " + baseListTypeString + baseTypeString); + }; + TypeFlow.prototype.typeCheckBaseListPrivacy = function (bases, declSymbol, extendsList) { + var _this = this; + if(bases) { + var basesLen = bases.members.length; + for(var i = 0; i < basesLen; i++) { + if(!bases.members[i].type || bases.members[i].type == this.checker.anyType) { + continue; + } + this.checkSymbolPrivacy(bases.members[i].type.symbol, declSymbol, function (typeName, isModuleName) { + return _this.baseListPrivacyErrorReporter(bases, i, declSymbol, extendsList, typeName, isModuleName); + }); + } + } + }; + TypeFlow.prototype.checkSymbolPrivacy = function (typeSymbol, declSymbol, errorCallback) { + var externalModuleSymbol = null; + var declSymbolPath = null; + if(typeSymbol.isExternallyVisible(this.checker)) { + var typeSymbolPath = typeSymbol.pathToRoot(); + declSymbolPath = declSymbol.pathToRoot(); + var typeSymbolLength = typeSymbolPath.length; + var declSymbolPathLength = declSymbolPath.length; + if(typeSymbolLength > 0) { + if(typeSymbolPath[typeSymbolLength - 1].getType().isModuleType() && (typeSymbolPath[typeSymbolLength - 1]).isDynamic && typeSymbolPath[typeSymbolLength - 1] != declSymbolPath[declSymbolPathLength - 1]) { + externalModuleSymbol = typeSymbolPath[typeSymbolLength - 1]; + } else if(typeSymbolLength > 1) { + if(typeSymbolPath[typeSymbolLength - 2].getType().isModuleType() && (typeSymbolPath[typeSymbolLength - 2]).isDynamic && (declSymbolPathLength == 1 || typeSymbolPath[typeSymbolLength - 2] != declSymbolPath[declSymbolPathLength - 2])) { + externalModuleSymbol = typeSymbolPath[typeSymbolLength - 2]; + } + } + } + if(externalModuleSymbol == null) { + return; + } + } + var interfaceDecl = declSymbol.getInterfaceDeclFromSymbol(this.checker); + if(interfaceDecl && !TypeScript.hasFlag(interfaceDecl.varFlags, TypeScript.VarFlags.Exported)) { + return; + } + var checkVisibilitySymbol = declSymbol; + var varDecl = declSymbol.getVarDeclFromSymbol(); + if(varDecl) { + if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Private)) { + return; + } else if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Public)) { + checkVisibilitySymbol = declSymbol.container; + } + } + if(checkVisibilitySymbol.isExternallyVisible(this.checker)) { + var privateSymbolName = typeSymbol.name; + if(externalModuleSymbol != null) { + var prettyName = externalModuleSymbol.getPrettyNameOfDynamicModule(declSymbolPath); + if(prettyName != null) { + this.currentScript.AddExternallyVisibleImportedSymbol(prettyName.symbol, this.checker); + return; + } else { + privateSymbolName = externalModuleSymbol.prettyName; + } + } + errorCallback(privateSymbolName, typeSymbol.name != privateSymbolName); + } + }; + TypeFlow.prototype.checkTypePrivacy = function (type, declSymbol, errorCallback) { + var _this = this; + if(!(type && type.primitiveTypeClass == TypeScript.Primitive.None)) { + return; + } + if(type.isArray()) { + return this.checkTypePrivacy(type.elementType, declSymbol, errorCallback); + } + if(type.symbol && type.symbol.name && type.symbol.name != "_anonymous" && (((type.call == null) && (type.construct == null) && (type.index == null)) || (type.members && (!type.isClass())))) { + return this.checkSymbolPrivacy(type.symbol, declSymbol, errorCallback); + } + if(type.members) { + type.members.allMembers.map(function (key, s, unused) { + var sym = s; + if(!TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.BuiltIn)) { + _this.checkTypePrivacy(sym.getType(), declSymbol, errorCallback); + } + }, null); + } + this.checkSignatureGroupPrivacy(type.call, declSymbol, errorCallback); + this.checkSignatureGroupPrivacy(type.construct, declSymbol, errorCallback); + this.checkSignatureGroupPrivacy(type.index, declSymbol, errorCallback); + }; + TypeFlow.prototype.checkSignatureGroupPrivacy = function (sgroup, declSymbol, errorCallback) { + if(sgroup) { + var len = sgroup.signatures.length; + for(var i = 0; i < sgroup.signatures.length; i++) { + var signature = sgroup.signatures[i]; + if(len > 1 && signature == sgroup.definitionSignature) { + continue; + } + if(signature.returnType) { + this.checkTypePrivacy(signature.returnType.type, declSymbol, errorCallback); + } + var paramLen = signature.parameters.length; + for(var j = 0; j < paramLen; j++) { + var param = signature.parameters[j]; + this.checkTypePrivacy(param.getType(), declSymbol, errorCallback); + } + } + } + }; + TypeFlow.prototype.functionArgumentPrivacyErrorReporter = function (funcDecl, p, paramSymbol, typeName, isModuleName) { + var isGetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor); + var isSetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.SetAccessor); + var isPublicFunc = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Public); + var isContainerInterface = funcDecl.type.symbol.getInterfaceDeclFromSymbol(this.checker) != null; + var typestring = ""; + if(isModuleName) { + var quotestring = ""; + if(!TypeScript.isQuoted(typeName)) { + quotestring = "'"; + } + typestring = " is using inaccessible module " + quotestring + typeName + quotestring; + } else { + typestring = " has or is using private type '" + typeName + "'"; + } + if(!isContainerInterface) { + if(funcDecl.isConstructor) { + this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], "exported class's constructor parameter '" + paramSymbol.name + "'" + typestring); + } else if(isSetter) { + this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], (isPublicFunc ? "public" : "exported") + " setter parameter '" + paramSymbol.name + "'" + typestring); + } else if(!isGetter) { + this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], (isPublicFunc ? "public" : "exported") + " function parameter '" + paramSymbol.name + "'" + typestring); + } + } else { + if(funcDecl.isConstructMember()) { + this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], "exported interface's constructor parameter '" + paramSymbol.name + "'" + typestring); + } else if(funcDecl.isCallMember()) { + this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], "exported interface's call parameter '" + paramSymbol.name + "'" + typestring); + } else if(!funcDecl.isIndexerMember()) { + this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], "exported interface's function parameter '" + paramSymbol.name + "'" + typestring); + } + } + }; + TypeFlow.prototype.returnTypePrivacyError = function (astError, funcDecl, typeName, isModuleName) { + var isGetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor); + var isSetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.SetAccessor); + var isPublicFunc = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Public); + var isContainerInterface = funcDecl.type.symbol.getInterfaceDeclFromSymbol(this.checker) != null; + var typestring = ""; + if(isModuleName) { + var quotestring = ""; + if(!TypeScript.isQuoted(typeName)) { + quotestring = "'"; + } + typestring = " is using inaccessible module " + quotestring + typeName + quotestring; + } else { + typestring = " has or is using private type '" + typeName + "'"; + } + if(!isContainerInterface) { + if(isGetter) { + this.checker.errorReporter.simpleError(astError, (isPublicFunc ? "public" : "exported") + " getter return type" + typestring); + } else if(!isSetter) { + this.checker.errorReporter.simpleError(astError, (isPublicFunc ? "public" : "exported") + " function return type" + typestring); + } + } else { + if(funcDecl.isConstructMember()) { + this.checker.errorReporter.simpleError(astError, "exported interface's constructor return type" + typestring); + } else if(funcDecl.isCallMember()) { + this.checker.errorReporter.simpleError(astError, "exported interface's call return type" + typestring); + } else if(funcDecl.isIndexerMember()) { + this.checker.errorReporter.simpleError(astError, "exported interface's indexer return type" + typestring); + } else { + this.checker.errorReporter.simpleError(astError, "exported interface's function return type" + typestring); + } + } + }; + TypeFlow.prototype.functionReturnTypePrivacyErrorReporter = function (funcDecl, signature, typeName, isModuleName) { + var reportOnFuncDecl = false; + if(funcDecl.returnTypeAnnotation != null && funcDecl.returnTypeAnnotation.type == signature.returnType.type) { + this.returnTypePrivacyError(funcDecl.returnTypeAnnotation, funcDecl, typeName, isModuleName); + } + for(var i = 0; i < funcDecl.returnStatementsWithExpressions.length; i++) { + if(funcDecl.returnStatementsWithExpressions[i].type == signature.returnType.type) { + this.returnTypePrivacyError(funcDecl.returnStatementsWithExpressions[i], funcDecl, typeName, isModuleName); + } else { + reportOnFuncDecl = true; + } + } + if(reportOnFuncDecl) { + this.returnTypePrivacyError(funcDecl, funcDecl, typeName, isModuleName); + } + }; + TypeFlow.prototype.typeCheckFunction = function (funcDecl) { + var _this = this; + this.nestingLevel = 0; + var fnType = funcDecl.type; + var fgSym = fnType.symbol; + var signature = funcDecl.signature; + if(this.checker.typeStatusIsFinished(signature.typeCheckStatus)) { + return funcDecl; + } else if(signature.typeCheckStatus == TypeScript.TypeCheckStatus.Started) { + if(!funcDecl.returnTypeAnnotation && funcDecl.bod && !funcDecl.isSignature() && !(funcDecl.isConstructor) && this.allReturnsAreVoid(funcDecl)) { + signature.returnType.type = this.voidType; + return funcDecl; + } else { + if(funcDecl.returnTypeAnnotation == null) { + if(this.checker.styleSettings.implicitAny) { + this.checker.errorReporter.styleError(funcDecl, "type implicitly set to 'any'"); + } + signature.returnType.type = this.anyType; + fgSym.flags |= TypeScript.SymbolFlags.RecursivelyReferenced; + } + return funcDecl; + } + } + signature.typeCheckStatus = TypeScript.TypeCheckStatus.Started; + this.checker.addStartedPTO(signature); + var prevScope = this.scope; + var prevFnc = this.thisFnc; + var prevMethodStatus = this.enclosingFncIsMethod; + var prevClassNode = this.thisClassNode; + this.enclosingFncIsMethod = funcDecl.isMethod() || funcDecl.isConstructor; + this.thisFnc = funcDecl; + var container = funcDecl.type.symbol; + var prevThisType = this.thisType; + var prevLocationInfo = this.checker.locationInfo; + var funcTable = null; + var acceptedContextualType = false; + var targetParams = null; + var targetReturnType = null; + var isGetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor); + var isSetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.SetAccessor); + var accessorType = (isGetter || isSetter) && funcDecl.accessorSymbol ? funcDecl.accessorSymbol.getType() : null; + var prevModDecl = this.checker.currentModDecl; + if(funcDecl.isConstructor && !funcDecl.isOverload) { + if(fnType.instanceType == null) { + this.checker.errorReporter.simpleError(funcDecl, "Malformed function body (is this a class named the same as an existing interface?)"); + return funcDecl; + } + if(funcDecl.classDecl.type.construct == null) { + this.checker.errorReporter.simpleError(funcDecl, "Malformed constructor (is this a class named the same as an existing class?)"); + return funcDecl; + } + this.scope = fnType.instanceType.constructorScope; + var ssb = this.scope; + funcTable = ssb.valueMembers.allMembers; + } else if((funcDecl.isSpecialFn() && !(funcDecl.fncFlags & TypeScript.FncFlags.Signature)) || funcDecl.isOverload) { + funcTable = funcDecl.symbols; + if(!TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static) && fnType.containedScope) { + this.scope = fnType.containedScope; + } + } else { + if(funcDecl.bod) { + this.scope = fnType.containedScope; + } + var ssb = this.scope; + if(ssb && ssb.valueMembers) { + funcTable = ssb.valueMembers.allMembers; + } + } + if(funcDecl.isConstructor && funcDecl.bod && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { + var hasBaseType = TypeScript.hasFlag(funcDecl.classDecl.type.instanceType.typeFlags, TypeScript.TypeFlags.HasBaseType); + var noSuperCallAllowed = !hasBaseType || TypeScript.hasFlag(funcDecl.classDecl.type.instanceType.typeFlags, TypeScript.TypeFlags.HasBaseTypeOfObject); + var superCallMustBeFirst = TypeScript.hasFlag((funcDecl.classDecl).varFlags, TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor); + if(noSuperCallAllowed && this.classConstructorHasSuperCall(funcDecl)) { + this.checker.errorReporter.simpleError(funcDecl, "Calls to 'super' constructor are not allowed in classes that either inherit directly from 'Object' or have no base class"); + } else if(hasBaseType) { + if(superCallMustBeFirst) { + if(!funcDecl.bod || !funcDecl.bod.members.length || !((funcDecl.bod.members[0].nodeType == TypeScript.NodeType.Call && (funcDecl.bod.members[0]).target.nodeType == TypeScript.NodeType.Super) || (TypeScript.hasFlag(funcDecl.bod.flags, TypeScript.ASTFlags.StrictMode) && funcDecl.bod.members.length > 1 && funcDecl.bod.members[1].nodeType == TypeScript.NodeType.Call && (funcDecl.bod.members[1]).target.nodeType == TypeScript.NodeType.Super))) { + this.checker.errorReporter.simpleError(funcDecl, "If a derived class contains initialized properties or constructor parameter properties, the first statement in the constructor body must be a call to the super constructor"); + } + } else if(!this.classConstructorHasSuperCall(funcDecl)) { + this.checker.errorReporter.simpleError(funcDecl, "Constructors for derived classes must contain a call to the class's 'super' constructor"); + } + } + } + if(funcDecl.isMethod() && funcDecl.type.enclosingType) { + var enclosingClassNode = null; + if(funcDecl.type.enclosingType.symbol.declAST.nodeType == TypeScript.NodeType.FuncDecl) { + enclosingClassNode = (funcDecl.type.enclosingType.symbol.declAST).classDecl; + } else if(funcDecl.type.enclosingType.symbol.declAST.nodeType == TypeScript.NodeType.ClassDeclaration) { + enclosingClassNode = funcDecl.type.enclosingType.symbol.declAST; + } + if(enclosingClassNode) { + this.thisClassNode = enclosingClassNode; + } + } + if(fnType.enclosingType) { + ; + var enclosingSym = fnType.symbol.container; + if(enclosingSym && enclosingSym.isType() && enclosingSym.getType().isClass()) { + enclosingSym = enclosingSym.container; + } + if(enclosingSym && enclosingSym.declAST && enclosingSym.declAST.nodeType == TypeScript.NodeType.ModuleDeclaration) { + this.checker.currentModDecl = enclosingSym.declAST; + } + } + if(funcDecl.unitIndex > 0) { + if(this.checker.units && (funcDecl.unitIndex < this.checker.units.length)) { + this.checker.locationInfo = this.checker.units[funcDecl.unitIndex]; + } else { + this.checker.locationInfo = TypeScript.unknownLocationInfo; + } + } + if(fnType.enclosingType) { + this.thisType = fnType.enclosingType; + } else { + this.thisType = prevThisType; + } + var paramLen = signature.parameters.length; + if(!funcDecl.isConstructor && funcDecl.bod && !funcDecl.isSignature()) { + var tmpParamScope = this.scope; + var ssb = this.scope; + if(!funcDecl.isMethod() && funcDecl.returnTypeAnnotation == null) { + if(prevScope && funcDecl.name && !funcDecl.name.isMissing()) { + var considerSym = prevScope.findAmbient(funcDecl.name.text, false, false); + if(considerSym && considerSym.declAST && considerSym.declAST.type) { + this.checker.setContextualType(considerSym.declAST.type, false); + } + } + if(this.checker.hasTargetType()) { + var candidateTypeContext = this.checker.getTargetTypeContext(); + var candidateType = candidateTypeContext.contextualType; + if(this.checker.canContextuallyTypeFunction(candidateType, funcDecl, true)) { + var candidateSigs = candidateType.construct ? candidateType.construct : candidateType.call; + candidateTypeContext.targetSig = candidateSigs.signatures[0]; + var candidateParams = candidateTypeContext.targetSig.parameters; + targetParams = candidateParams; + targetReturnType = candidateTypeContext.targetSig.returnType.type; + fgSym.type = candidateTypeContext.contextualType; + acceptedContextualType = true; + } else if(candidateType && funcDecl.isAccessor()) { + accessorType = candidateType; + candidateTypeContext.targetAccessorType = accessorType; + } else { + this.checker.killCurrentContextualType(); + } + } + } + var paramTable = ssb.valueMembers; + this.scope = new TypeScript.SymbolScopeBuilder(paramTable, null, null, null, prevScope, container); + for(var p = 0; p < paramLen; p++) { + var symbol = signature.parameters[p]; + var ast = symbol.declAST; + if(this.checker.hasTargetType() && (targetParams && (this.checker.getTargetTypeContext().targetSig.hasVariableArgList || p < targetParams.length))) { + var candidateTypeContext = this.checker.getTargetTypeContext(); + var hasVarArgList = candidateTypeContext.targetSig.hasVariableArgList; + ast.type = hasVarArgList && p >= targetParams.length - 1 ? targetParams[targetParams.length - 1].getType().elementType : targetParams[p].getType(); + ast.sym.setType(ast.type); + (ast.sym).typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); + } else { + this.typeCheck(ast); + } + if(isSetter && accessorType) { + ast = this.cast(ast, accessorType); + } + symbol.container = container; + this.checkTypePrivacy(symbol.getType(), container, function (typeName, isModuleName) { + return _this.functionArgumentPrivacyErrorReporter(funcDecl, p, symbol, typeName, isModuleName); + }); + paramTable.publicMembers.add(symbol.name, symbol); + } + this.scope = tmpParamScope; + } else { + this.typeCheck(funcDecl.arguments); + for(var p = 0; p < paramLen; p++) { + signature.parameters[p].parameter.typeLink.type = funcDecl.arguments.members[p].type; + this.checkTypePrivacy(signature.parameters[p].getType(), container, function (typeName, isModuleName) { + return _this.functionArgumentPrivacyErrorReporter(funcDecl, p, signature.parameters[p], typeName, isModuleName); + }); + if((funcDecl.arguments.members[p]).parameterPropertySym) { + (funcDecl.arguments.members[p]).parameterPropertySym.setType(funcDecl.arguments.members[p].type); + } + } + if((funcDecl.fncFlags & TypeScript.FncFlags.IndexerMember)) { + if(!paramLen || paramLen > 1) { + this.checker.errorReporter.simpleError(funcDecl, "Index signatures may take one and only one parameter"); + } else if(funcDecl.arguments.members[0].type == this.checker.numberType) { + fnType.index.flags |= TypeScript.SignatureFlags.IsNumberIndexer; + } else if(funcDecl.arguments.members[0].type == this.checker.stringType) { + fnType.index.flags |= TypeScript.SignatureFlags.IsStringIndexer; + } else { + this.checker.errorReporter.simpleError(funcDecl.arguments.members[0], "Index signatures may only take 'string' or 'number' as their parameter"); + } + } + } + if(funcDecl.bod && (!funcDecl.isSignature())) { + if(!(funcDecl.isConstructor)) { + this.addFormals(container, signature, funcTable); + } else { + this.addConstructorLocalArgs(funcDecl, funcTable, TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)); + if(this.thisClassNode && this.thisClassNode.extendsList) { + var tmpScope = this.scope; + var funcMembers = new TypeScript.ScopedMembers(funcTable); + this.scope = new TypeScript.FilteredSymbolScopeBuilder(funcMembers, prevScope, funcDecl.type.symbol, function (sym) { + return sym.kind() == TypeScript.SymbolKind.Parameter; + }); + this.typeCheckBaseCalls(this.thisClassNode.extendsList); + this.scope = tmpScope; + } + } + var prevMod = this.checker.currentModDecl; + if(funcDecl.type && funcDecl.type.symbol && !funcDecl.isMethod() && funcDecl.type.symbol.declModule) { + this.checker.currentModDecl = funcDecl.type.symbol.declModule; + } + if(acceptedContextualType) { + this.checker.setContextualType(null, this.checker.inProvisionalTypecheckMode()); + } + this.typeCheck(funcDecl.bod); + if(acceptedContextualType) { + this.checker.unsetContextualType(); + } + this.checker.currentModDecl = prevMod; + if(this.checker.checkControlFlow) { + var cfg = funcDecl.buildControlFlow(); + if(this.checker.printControlFlowGraph) { + cfg.print(this.checker.errorReporter.outfile); + } + cfg.reportUnreachable(this.checker.errorReporter); + if(this.checker.checkControlFlowUseDef) { + cfg.useDef(this.checker.errorReporter, funcDecl.type.symbol); + } + } + if(funcDecl.isConstructor) { + var fns = funcDecl.scopes; + var fnsLen = fns.members.length; + var freeVars; + var sym; + var j = 0; + for(; j < fnsLen; j++) { + var fn = fns.members[j]; + if(!fn.isSignature()) { + if(TypeScript.hasFlag(fn.fncFlags, TypeScript.FncFlags.Method) && (!TypeScript.hasFlag(fn.fncFlags, TypeScript.FncFlags.Static))) { + this.checkPromoteFreeVars(fn, funcDecl.type.symbol); + } + } + } + } + } + this.scope = prevScope; + this.thisFnc = prevFnc; + this.thisClassNode = prevClassNode; + this.enclosingFncIsMethod = prevMethodStatus; + this.thisType = prevThisType; + this.checker.locationInfo = prevLocationInfo; + this.checker.currentModDecl = prevModDecl; + signature.typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); + if(funcDecl.returnTypeAnnotation) { + this.checkForVoidConstructor(funcDecl.returnTypeAnnotation.type, funcDecl.returnTypeAnnotation); + if(signature.returnType.type == null) { + this.checker.resolveTypeLink(this.scope, signature.returnType, false); + } + } else if(targetReturnType) { + signature.returnType.type = targetReturnType; + } + if(!(fgSym.flags & TypeScript.SymbolFlags.RecursivelyReferenced) && funcDecl.returnStatementsWithExpressions.length > 0) { + var collection = { + getLength: function () { + return funcDecl.returnStatementsWithExpressions.length; + }, + setTypeAtIndex: function (index, type) { + funcDecl.returnStatementsWithExpressions[index].type = type; + }, + getTypeAtIndex: function (index) { + return funcDecl.returnStatementsWithExpressions[index].type; + } + }; + var bestCommonReturnType = funcDecl.returnStatementsWithExpressions[0].type; + bestCommonReturnType = this.checker.findBestCommonType(bestCommonReturnType, null, collection, true); + if(bestCommonReturnType) { + signature.returnType.type = this.checker.widenType(bestCommonReturnType); + } else { + for(var i = 0; i < funcDecl.returnStatementsWithExpressions.length; i++) { + this.checker.errorReporter.simpleError(funcDecl.returnStatementsWithExpressions[i], "Incompatible return type"); + } + signature.returnType.type = this.anyType; + } + } + var onlyHasThrow = false; + if(signature.returnType.type == null) { + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.HasReturnExpression)) { + if(this.checker.styleSettings.implicitAny) { + this.checker.errorReporter.styleError(funcDecl, "type implicitly set to 'any'"); + } + signature.returnType.type = this.anyType; + } else { + signature.returnType.type = this.voidType; + } + } else if(signature.returnType.type == this.nullType || signature.returnType.type == this.checker.undefinedType) { + signature.returnType.type = this.anyType; + } else if((signature.returnType.type != this.voidType && signature.returnType.type != this.checker.undefinedType && signature.returnType.type != this.anyType)) { + if(!funcDecl.isSignature() && !funcDecl.isConstructor && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.HasReturnExpression) && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { + onlyHasThrow = (funcDecl.bod.members.length > 0) && (funcDecl.bod.members[0].nodeType == TypeScript.NodeType.Throw); + if(!onlyHasThrow) { + this.checker.errorReporter.simpleError(funcDecl.returnTypeAnnotation || funcDecl, "Function declared a non-void return type, but has no return expression"); + } + } + this.checkTypePrivacy(signature.returnType.type, container, function (typeName, isModuleName) { + return _this.functionReturnTypePrivacyErrorReporter(funcDecl, signature, typeName, isModuleName); + }); + } + if(funcDecl.accessorSymbol) { + var accessorType = funcDecl.accessorSymbol.getType(); + if(!onlyHasThrow && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor) && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.HasReturnExpression)) { + this.checker.errorReporter.simpleError(funcDecl, "Getters must return a value"); + } + if(accessorType) { + if((TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor) && accessorType != signature.returnType.type) || (funcDecl.arguments.members.length > 0 && accessorType != funcDecl.arguments.members[0].type)) { + this.checker.errorReporter.simpleError(funcDecl, "Getter and setter types do not agree"); + } + } else { + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { + funcDecl.accessorSymbol.setType(signature.returnType.type); + } else { + if(funcDecl.arguments.members.length != 1) { + this.checker.errorReporter.simpleError(funcDecl, "Setters may have one and only one argument"); + } else { + funcDecl.accessorSymbol.setType(funcDecl.arguments.members[0].type); + } + } + } + } + this.typeCheckOverloadSignatures(fnType, funcDecl); + return funcDecl; + }; + TypeFlow.prototype.typeCheckBases = function (type) { + var seenInterface = false; + var bases = type.extendsList; + var baseLinks = type.extendsTypeLinks; + if(bases) { + var len = bases.length; + if(len > 0) { + type.typeFlags |= TypeScript.TypeFlags.HasBaseType; + } + for(var i = 0; i < len; i++) { + if(bases[i] == this.checker.anyType) { + baseLinks[i].type = null; + var oldErrors = this.checker.errorReporter.getCapturedErrors(); + TypeScript.CompilerDiagnostics.assert(oldErrors.length == 0, "There shouldnt be any contextual errors when typechecking base type names"); + this.checker.errorReporter.pushToErrorSink = true; + bases[i] = this.checker.resolveBaseTypeLink(baseLinks[i], type.containedScope); + this.checker.errorReporter.pushToErrorSink = false; + this.checker.errorReporter.freeCapturedErrors(); + } + var base = bases[i]; + var baseRef = baseLinks[i].ast; + var baseTypeOfObject = base.symbol && base.symbol.name == "Object" && base.symbol.container == this.checker.gloMod; + if(baseTypeOfObject) { + type.typeFlags |= TypeScript.TypeFlags.HasBaseTypeOfObject; + } + if(base.isClassInstance()) { + if(!(type.isClassInstance())) { + this.checker.errorReporter.simpleError(baseRef, "Interface base type must be interface"); + } else { + if(seenInterface) { + this.checker.errorReporter.simpleError(baseRef, "Class may not follow interface as base type"); + } + } + } else if(base.isModuleType()) { + this.checker.errorReporter.simpleError(baseRef, "Types may not be derived from module types"); + } else if(base.members) { + if(!seenInterface) { + seenInterface = true; + } + } else { + if(!(type.isClassInstance())) { + this.checker.errorReporter.simpleError(baseRef, "Interface base type must be interface"); + } else { + this.checker.errorReporter.simpleError(baseRef, "Base type must be interface or class"); + } + break; + } + } + } + }; + TypeFlow.prototype.checkMembersImplementInterfaces = function (implementingType) { + var instanceType = implementingType.getInstanceType(); + if(instanceType.implementsList) { + var len = instanceType.implementsList.length; + for(var i = 0; i < len; i++) { + var interfaceType = instanceType.implementsList[i]; + var comparisonInfo = new TypeScript.TypeComparisonInfo(); + if(!this.checker.sourceIsSubtypeOfTarget(instanceType, interfaceType, comparisonInfo)) { + var emsg = "Class '" + instanceType.getTypeName() + "' declares interface '" + interfaceType.getTypeName() + "' but does not implement it"; + if(!comparisonInfo.message) { + this.checker.errorReporter.simpleErrorFromSym(instanceType.symbol, emsg); + } else { + this.checker.errorReporter.simpleErrorFromSym(instanceType.symbol, emsg + ": " + comparisonInfo.message); + } + } + } + } + }; + TypeFlow.prototype.typeCheckBaseCalls = function (bases) { + if(bases == null) { + return; + } + var basesLen = bases.members.length; + for(var i = 0; i < basesLen; i++) { + var baseExpr = bases.members[i]; + var baseSymbol = null; + if(baseExpr.nodeType == TypeScript.NodeType.Call) { + this.typeCheckNew(baseExpr); + } + } + }; + TypeFlow.prototype.assertUniqueNamesInBaseTypes = function (names, type, classDecl, checkUnique) { + var _this = this; + if(type) { + if(type.members) { + type.members.publicMembers.map(function (key, s, c) { + var sym = s; + var dup = names.lookup(sym.name); + if(dup) { + if(checkUnique) { + _this.checker.errorReporter.simpleError(classDecl, "duplicate member name in bases for " + classDecl.name.actualText + ": " + type.symbol.name + " and " + dup.container.name + " both contain member with name " + sym.name); + } + } else { + names.add(sym.name, sym); + } + }, null); + } + if(type.extendsList) { + var len = type.extendsList.length; + for(var i = 0; i < len; i++) { + if(!(type.extendsList[i].symbol.flags & TypeScript.SymbolFlags.RecursivelyReferenced)) { + this.assertUniqueNamesInBaseTypes(names, type.extendsList[i], classDecl, checkUnique); + } + } + } + } + }; + TypeFlow.prototype.checkBaseTypeMemberInheritance = function (derivedType, derivedTypeDecl) { + var _this = this; + var instanceType = derivedType.getInstanceType(); + if(instanceType.extendsList == null) { + return; + } + var len = instanceType.extendsList.length; + if(len > 0) { + var names = new TypeScript.StringHashTable(); + if(instanceType.isClassInstance()) { + for(var i = 0; i < len; i++) { + this.assertUniqueNamesInBaseTypes(names, instanceType.extendsList[i], derivedTypeDecl, i > 0); + } + } + if(instanceType.members) { + instanceType.members.publicMembers.map(function (key, s, c) { + var sym = s; + for(var j = 0; j < len; j++) { + var base = instanceType.extendsList[j]; + if(base.memberScope == null) { + _this.checker.errorReporter.simpleError(derivedTypeDecl, "Base type '" + base.symbol.name + "' lacks an implementation."); + } else { + var bSym = base.memberScope.find(sym.name, false, false); + if(bSym) { + var aType = sym.getType(); + var bType = bSym.getType(); + if(!(_this.checker.sourceIsSubtypeOfTarget(aType, bType))) { + _this.checker.errorReporter.simpleErrorFromSym(sym, "Type of overridden member '" + sym.name + "' is not subtype of original member defined by type '" + bSym.container.name + "'"); + } else if((sym.kind() == TypeScript.SymbolKind.Type) && (bSym.kind() == TypeScript.SymbolKind.Field)) { + _this.checker.errorReporter.simpleErrorFromSym(sym, "Cannot override field '" + sym.name + "' with method"); + } + } + } + } + }, null); + } + } + }; + TypeFlow.prototype.typeCheckClass = function (classDecl) { + var typeSymbol = classDecl.type.symbol; + if(typeSymbol.typeCheckStatus == TypeScript.TypeCheckStatus.Finished) { + return classDecl; + } else if(typeSymbol.typeCheckStatus == TypeScript.TypeCheckStatus.Started) { + return classDecl; + } else { + typeSymbol.typeCheckStatus = TypeScript.TypeCheckStatus.Started; + this.checker.addStartedPTO(typeSymbol); + } + var prevScope = this.scope; + var svClassNode = this.thisClassNode; + this.thisClassNode = classDecl; + var classType = classDecl.type; + this.typeCheckBases(classType.instanceType); + this.typeCheckBaseListPrivacy(classDecl.extendsList, typeSymbol, true); + this.typeCheckBaseListPrivacy(classDecl.implementsList, typeSymbol, false); + var prevThisType = this.thisType; + this.thisType = classType.instanceType; + this.scope = classType.instanceType.containedScope; + if(classDecl.constructorDecl) { + this.scope = classType.instanceType.constructorScope; + var ssb = this.scope; + var funcTable = ssb.valueMembers.allMembers; + this.addConstructorLocalArgs(classDecl.constructorDecl, funcTable, true); + } + this.typeCheck(classDecl.members); + typeSymbol.typeCheckStatus = TypeScript.TypeCheckStatus.Finished; + this.checkBaseTypeMemberInheritance(classType, classDecl); + this.checkMembersImplementInterfaces(classType); + this.typeCheckOverloadSignatures(classType, classDecl); + this.typeCheckOverloadSignatures(classType.instanceType, classDecl); + if(!classDecl.constructorDecl) { + if(classDecl.extendsList && classDecl.extendsList.members.length && classDecl.extendsList.members[0].type && classDecl.extendsList.members[0].type.symbol.type.isClass()) { + TypeScript.cloneParentConstructGroupForChildType(classDecl.type, classDecl.extendsList.members[0].type.symbol.type); + } + } + this.thisType = prevThisType; + this.thisClassNode = svClassNode; + this.scope = prevScope; + return classDecl; + }; + TypeFlow.prototype.typeCheckOverloadSignatures = function (type, ast) { + if(type.call) { + type.call.typeCheck(this.checker, ast, type.construct != null); + } + if(type.construct) { + type.construct.typeCheck(this.checker, ast, false); + } + if(type.index) { + type.index.typeCheck(this.checker, ast, false); + } + }; + TypeFlow.prototype.typeCheckInterface = function (interfaceDecl) { + this.typeCheckBases(interfaceDecl.type); + this.typeCheckBaseListPrivacy(interfaceDecl.extendsList, interfaceDecl.type.symbol, true); + this.typeCheck(interfaceDecl.members); + this.checkBaseTypeMemberInheritance(interfaceDecl.type, interfaceDecl); + if(interfaceDecl.extendsList) { + for(var i = 0; i < interfaceDecl.extendsList.members.length; i++) { + if(interfaceDecl.extendsList.members[i].type.call) { + if(interfaceDecl.type.call) { + interfaceDecl.type.call.signatures = interfaceDecl.type.call.signatures.concat(interfaceDecl.extendsList.members[i].type.call.signatures); + } else { + interfaceDecl.type.call = interfaceDecl.extendsList.members[i].type.call; + } + } + if(interfaceDecl.extendsList.members[i].type.construct) { + if(interfaceDecl.type.construct) { + interfaceDecl.type.construct.signatures = interfaceDecl.type.construct.signatures.concat(interfaceDecl.extendsList.members[i].type.construct.signatures); + } else { + interfaceDecl.type.construct = interfaceDecl.extendsList.members[i].type.construct; + } + } + if(interfaceDecl.extendsList.members[i].type.index) { + if(interfaceDecl.type.index) { + interfaceDecl.type.index.signatures = interfaceDecl.type.index.signatures.concat(interfaceDecl.extendsList.members[i].type.index.signatures); + } else { + interfaceDecl.type.index = interfaceDecl.extendsList.members[i].type.index; + } + } + } + } + return interfaceDecl; + }; + TypeFlow.prototype.typeCheckImportDecl = function (importDecl) { + var mod = importDecl.alias.type; + var sym = null; + var prevInImportTC = this.inImportTypeCheck; + this.inImportTypeCheck = true; + this.typeCheck(importDecl.alias); + mod = importDecl.alias.type; + if(mod == null) { + this.checker.errorReporter.simpleError(importDecl.alias, "Could not resolve module alias '" + importDecl.id.actualText + "'"); + mod = this.checker.anyType; + (importDecl.id.sym).type = mod; + } + importDecl.id.type = mod; + sym = mod.symbol; + if(!mod.isModuleType()) { + this.checker.errorReporter.simpleError(importDecl.alias, "A module cannot be aliased to a non-module type"); + } else { + sym.type = mod; + if(this.checker.typeFlow.currentScript && this.checker.typeFlow.currentScript.topLevelMod && this.checker.typeFlow.currentScript.topLevelMod.mod) { + this.checker.typeFlow.currentScript.topLevelMod.mod.importedModules.push(importDecl); + } + (importDecl.id.sym).type = mod; + if(mod.symbol && mod.symbol.declAST) { + (mod.symbol.declAST).modFlags &= ~TypeScript.ModuleFlags.ShouldEmitModuleDecl; + } + } + this.inImportTypeCheck = prevInImportTC; + return importDecl; + }; + TypeFlow.prototype.typeCheckModule = function (moduleDecl) { + if(!moduleDecl.mod) { + return moduleDecl; + } + if(this.currentScript) { + this.currentScript.requiresGlobal = true; + } + var mod = moduleDecl.mod; + var sym = null; + var prevScope = this.scope; + var prevThisType = this.thisType; + var prevCurrentModDecl = this.checker.currentModDecl; + this.checker.currentModDecl = moduleDecl; + this.thisType = null; + this.scope = mod.containedScope; + this.typeCheck(moduleDecl.members); + sym = mod.symbol; + this.checker.currentModDecl = prevCurrentModDecl; + this.thisType = prevThisType; + this.scope = prevScope; + moduleDecl.type = mod; + if(sym) { + sym.typeCheckStatus = TypeScript.TypeCheckStatus.Finished; + } + return moduleDecl; + }; + TypeFlow.prototype.typeCheckFor = function (forStmt) { + forStmt.init = this.typeCheck(forStmt.init); + this.nestingLevel++; + forStmt.cond = this.typeCheck(forStmt.cond); + this.typeCheckCondExpr(forStmt.cond); + forStmt.incr = this.typeCheck(forStmt.incr); + this.nestingLevel--; + forStmt.body = this.typeCheck(forStmt.body); + this.typeCheckCompoundStmtBlock(forStmt.body, "for statement"); + forStmt.type = this.voidType; + return forStmt; + }; + TypeFlow.prototype.typeCheckWith = function (withStmt) { + if(this.checker.errorsOnWith) { + this.checker.errorReporter.simpleError(withStmt.expr, "All symbols within a 'with' block will be typed as 'any'"); + } + withStmt.expr = this.typeCheck(withStmt.expr); + this.checker.inWith = true; + withStmt.body = this.typeCheck(withStmt.body); + this.typeCheckCompoundStmtBlock(withStmt.body, "with statement"); + this.checker.inWith = false; + return withStmt; + }; + TypeFlow.prototype.typeCheckForIn = function (forInStmt) { + forInStmt.obj = this.typeCheck(forInStmt.obj); + forInStmt.lval = this.cast(this.typeCheck(forInStmt.lval), this.checker.stringType); + if(forInStmt.lval.nodeType == TypeScript.NodeType.VarDecl) { + var varDecl = forInStmt.lval; + if(varDecl.typeExpr) { + this.checker.errorReporter.simpleError(varDecl, "Variable declarations for for/in expressions may not contain a type annotation"); + } + if(varDecl.sym) { + varDecl.sym.setType(this.checker.stringType); + } + } + forInStmt.body = this.typeCheck(forInStmt.body); + this.typeCheckCompoundStmtBlock(forInStmt.body, "for in statement"); + return forInStmt; + }; + TypeFlow.prototype.typeCheckWhile = function (whileStmt) { + whileStmt.cond = this.typeCheck(whileStmt.cond); + this.typeCheckCondExpr(whileStmt.cond); + whileStmt.body = this.typeCheck(whileStmt.body); + this.typeCheckCompoundStmtBlock(whileStmt.body, "while statement"); + whileStmt.type = this.voidType; + return whileStmt; + }; + TypeFlow.prototype.typeCheckDoWhile = function (doWhileStmt) { + doWhileStmt.cond = this.typeCheck(doWhileStmt.cond); + this.typeCheckCondExpr(doWhileStmt.cond); + doWhileStmt.body = this.typeCheck(doWhileStmt.body); + this.typeCheckCompoundStmtBlock(doWhileStmt.body, "do while statement"); + doWhileStmt.type = this.voidType; + return doWhileStmt; + }; + TypeFlow.prototype.typeCheckCondExpr = function (cond) { + if(this.checker.styleSettings.assignmentInCond) { + if((cond !== null) && (cond.nodeType >= TypeScript.NodeType.Asg) && (cond.nodeType <= TypeScript.NodeType.LastAsg)) { + this.checker.errorReporter.simpleError(cond, "top-level assignment statement in conditional expression"); + } + } + }; + TypeFlow.prototype.typeCheckCompoundStmtBlock = function (stmts, stmtType) { + if(this.checker.styleSettings.blockInCompoundStmt && stmts) { + if(stmts.nodeType != TypeScript.NodeType.Block) { + this.checker.errorReporter.styleError(stmts, stmtType + " requires a block"); + } + } + }; + TypeFlow.prototype.typeCheckIf = function (ifStmt) { + ifStmt.cond = this.typeCheck(ifStmt.cond); + this.typeCheckCondExpr(ifStmt.cond); + ifStmt.thenBod = this.typeCheck(ifStmt.thenBod); + ifStmt.elseBod = this.typeCheck(ifStmt.elseBod); + this.typeCheckCompoundStmtBlock(ifStmt.thenBod, "if statement"); + this.typeCheckCompoundStmtBlock(ifStmt.elseBod, "if statement"); + ifStmt.type = this.voidType; + return ifStmt; + }; + TypeFlow.prototype.typeFromAccessorFuncDecl = function (funcDecl) { + if(!funcDecl.isAccessor()) { + return null; + } + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { + return funcDecl.type.call.signatures[0].returnType.type; + } else { + return funcDecl.type.call.signatures[0].parameters[0].getType(); + } + }; + TypeFlow.prototype.typeCheckObjectLit = function (objectLit) { + var resultType = new TypeScript.Type(); + resultType.symbol = new TypeScript.TypeSymbol(this.checker.anon, objectLit.minChar, objectLit.limChar - objectLit.minChar, this.checker.locationInfo.unitIndex, resultType); + resultType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + resultType.memberScope = new TypeScript.SymbolTableScope(resultType.members, null, null, null, null); + var aggScope = new TypeScript.SymbolAggregateScope(resultType.symbol); + aggScope.addParentScope(resultType.memberScope); + aggScope.addParentScope(this.scope); + resultType.containedScope = aggScope; + var memberDecls = objectLit.operand; + var prevThisType = this.thisType; + var acceptTargetType = false; + var targetType = null; + if(this.checker.hasTargetType()) { + targetType = this.checker.getTargetTypeContext().contextualType; + if(targetType && targetType.symbol && !this.checker.typeStatusIsFinished(targetType.symbol.typeCheckStatus)) { + if(targetType.symbol.declAST) { + this.typeCheck(targetType.symbol.declAST); + } + } + acceptTargetType = true; + } + if(memberDecls) { + for(var i = 0, len = memberDecls.members.length; i < len; i++) { + var binex = memberDecls.members[i]; + var id = binex.operand1; + var text; + var targetMember = null; + var fieldSymbol = null; + if(id.nodeType == TypeScript.NodeType.Name) { + text = (id).text; + } else if(id.nodeType == TypeScript.NodeType.QString) { + var idText = (id).text; + text = idText.substring(1, idText.length - 1); + } else { + this.checker.errorReporter.simpleError(objectLit, "malformed object literal"); + resultType = this.anyType; + break; + } + if(acceptTargetType && targetType.memberScope) { + targetMember = targetType.memberScope.find(text, false, false); + } + if(binex.operand2.nodeType == TypeScript.NodeType.FuncDecl && (binex.operand2).isAccessor()) { + var funcDecl = binex.operand2; + var accessorSym = resultType.members.publicMembers.lookup(text); + accessorSym = this.checker.createAccessorSymbol(funcDecl, accessorSym, resultType, true, false, resultType.memberScope, null); + funcDecl.accessorSymbol = accessorSym; + fieldSymbol = accessorSym; + if(id.nodeType == TypeScript.NodeType.Name) { + (id).sym = accessorSym; + } + } + this.checker.typeCheckWithContextualType(acceptTargetType && targetMember ? targetMember.getType() : null, false, acceptTargetType, binex.operand2); + if(acceptTargetType && targetMember) { + if((binex.operand2.type == this.anyType || this.checker.sourceIsAssignableToTarget(binex.operand2.type, targetMember.getType())) || (binex.operand2.nodeType == TypeScript.NodeType.FuncDecl && (binex.operand2).isAccessor() && this.typeFromAccessorFuncDecl(binex.operand2) == targetMember.getType())) { + binex.operand1.type = targetMember.getType(); + } + } else { + binex.operand2.type = binex.operand2.type == this.checker.undefinedType ? this.anyType : binex.operand2.type; + } + if(fieldSymbol == null) { + var memberType = binex.operand2.type; + var field = new TypeScript.ValueLocation(); + fieldSymbol = new TypeScript.FieldSymbol(text, id.minChar, this.checker.locationInfo.unitIndex, true, field); + fieldSymbol.flags |= TypeScript.SymbolFlags.Property; + field.symbol = fieldSymbol; + fieldSymbol.typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); + field.typeLink = new TypeScript.TypeLink(); + field.typeLink.type = memberType; + resultType.members.publicMembers.add(text, fieldSymbol); + } + fieldSymbol.isObjectLitField = true; + } + } + this.thisType = prevThisType; + objectLit.type = resultType; + if(targetType) { + objectLit.targetType = targetType; + } + }; + TypeFlow.prototype.typeCheckArrayLit = function (arrayLit) { + var elements = arrayLit.operand; + var elementType = this.anyType; + var targetElementType = null; + var comparisonInfo = new TypeScript.TypeComparisonInfo(); + comparisonInfo.onlyCaptureFirstError = true; + if(this.checker.hasTargetType()) { + var targetType = this.checker.getTargetTypeContext().contextualType; + if(targetType.elementType) { + targetElementType = targetType.elementType; + } + } + if(elements) { + var prevInArrayElemTypeCheck = this.inArrayElementTypeCheck; + this.inArrayElementTypeCheck = true; + this.checker.typeCheckWithContextualType(targetElementType, this.checker.inProvisionalTypecheckMode(), targetElementType != null, elements); + this.inArrayElementTypeCheck = prevInArrayElemTypeCheck; + elementType = elements.members[0].type; + var collection = { + getLength: function () { + return elements.members.length; + }, + setTypeAtIndex: function (index, type) { + elements.members[index].type = type; + }, + getTypeAtIndex: function (index) { + return elements.members[index].type; + } + }; + elementType = this.checker.findBestCommonType(elementType, targetElementType, collection, false, comparisonInfo); + if(elementType == this.checker.undefinedType || (!prevInArrayElemTypeCheck && elementType == this.nullType)) { + elementType = this.anyType; + } + } + if(!elementType) { + var emsg = "Incompatible types in array literal expression"; + if(!comparisonInfo.message) { + this.checker.errorReporter.simpleError(arrayLit, emsg); + } else { + this.checker.errorReporter.simpleError(arrayLit, emsg + ": " + comparisonInfo.message); + } + elementType = this.anyType; + } else if(targetElementType) { + if(this.checker.sourceIsAssignableToTarget(elementType, targetElementType)) { + elementType = targetElementType; + } + } + arrayLit.type = this.checker.makeArrayType(elementType); + }; + TypeFlow.prototype.checkForVoidConstructor = function (type, ast) { + if(type && type.construct && type.construct.signatures.length > 0) { + for(var i = 0; i < type.construct.signatures.length; i++) { + if(type.construct.signatures[i].returnType.type == this.checker.voidType) { + this.checker.errorReporter.simpleError(ast, "Constructors may not have a return type of 'void'"); + break; + } + } + } + }; + TypeFlow.prototype.typeCheckReturn = function (returnStmt) { + if(this.thisFnc) { + var targetType = null; + if(this.checker.hasTargetType()) { + var tcContext = this.checker.getTargetTypeContext(); + var accessorType = tcContext.targetAccessorType; + if(accessorType) { + targetType = accessorType; + } else { + var targetSig = this.checker.getTargetTypeContext().targetSig; + if(targetSig && targetSig.returnType.type != this.voidType) { + targetType = targetSig.returnType.type; + } + } + } + if(returnStmt.returnExpression) { + this.thisFnc.fncFlags |= TypeScript.FncFlags.HasReturnExpression; + if(targetType == null && this.thisFnc.returnTypeAnnotation && this.thisFnc.returnTypeAnnotation.type && this.thisFnc.returnTypeAnnotation.type != this.voidType) { + targetType = this.thisFnc.returnTypeAnnotation.type; + } + this.checker.typeCheckWithContextualType(targetType, this.checker.inProvisionalTypecheckMode(), targetType != null, returnStmt.returnExpression); + var expectedReturnType = (this.thisFnc.returnTypeAnnotation && this.thisFnc.returnTypeAnnotation.type) ? this.thisFnc.returnTypeAnnotation.type : targetType; + if(expectedReturnType) { + if(expectedReturnType == this.voidType && returnStmt.returnExpression.type != this.voidType) { + this.checker.errorReporter.simpleError(returnStmt, "Return with value expression in void function"); + returnStmt.type = returnStmt.returnExpression.type; + } else { + returnStmt.returnExpression = this.cast(returnStmt.returnExpression, expectedReturnType); + returnStmt.type = expectedReturnType; + } + } else { + if(targetType) { + if(returnStmt.returnExpression.type != this.voidType) { + returnStmt.returnExpression = this.cast(returnStmt.returnExpression, targetType); + } else { + returnStmt.returnExpression.type = targetType; + } + } + returnStmt.type = returnStmt.returnExpression.type; + } + this.thisFnc.returnStatementsWithExpressions[this.thisFnc.returnStatementsWithExpressions.length] = returnStmt; + } else { + returnStmt.type = targetType == null ? this.checker.voidType : targetType; + } + } + return returnStmt; + }; + TypeFlow.prototype.typeCheckInstOf = function (ast) { + var binex = ast; + binex.operand1 = this.typeCheck(binex.operand1); + binex.operand2 = this.typeCheck(binex.operand2); + if(!((binex.operand1.type == this.checker.anyType || this.checker.sourceIsSubtypeOfTarget(binex.operand1.type, this.objectInterfaceType)) && (binex.operand2.type == this.anyType || this.checker.sourceIsSubtypeOfTarget(binex.operand2.type, this.functionInterfaceType)))) { + this.checker.errorReporter.simpleError(ast, "The instanceof operator requires the left operand to be of type Any or an object type, and the right operand to be of type Any or a subtype of the Function interface type"); + } + binex.type = this.booleanType; + return binex; + }; + TypeFlow.prototype.typeCheckCommaOperator = function (ast) { + var binex = ast; + binex.operand1 = this.typeCheck(binex.operand1); + binex.operand2 = this.typeCheck(binex.operand2); + binex.type = binex.operand2.type; + return binex; + }; + TypeFlow.prototype.typeCheckLogOr = function (binex) { + binex.operand1 = this.typeCheck(binex.operand1); + binex.operand2 = this.typeCheck(binex.operand2); + var leftType = binex.operand1.type; + var rightType = binex.operand2.type; + if(leftType == this.checker.anyType || rightType == this.checker.anyType) { + binex.type = this.checker.anyType; + } else if(leftType == this.checker.booleanType) { + if(rightType == this.checker.booleanType) { + binex.type = this.checker.booleanType; + } else { + binex.type = this.checker.anyType; + } + } else if(leftType == this.checker.numberType) { + if(rightType == this.checker.numberType) { + binex.type = this.checker.numberType; + } else { + binex.type = this.checker.anyType; + } + } else if(leftType == this.checker.stringType) { + if(rightType == this.checker.stringType) { + binex.type = this.checker.stringType; + } else { + binex.type = this.checker.anyType; + } + } else { + if(this.checker.sourceIsSubtypeOfTarget(leftType, rightType)) { + binex.type = rightType; + } else if(this.checker.sourceIsSubtypeOfTarget(rightType, leftType)) { + binex.type = leftType; + } else { + binex.type = this.checker.anyType; + } + } + return binex; + }; + TypeFlow.prototype.typeCheckLogAnd = function (binex) { + binex.operand1 = this.typeCheck(binex.operand1); + binex.operand2 = this.typeCheck(binex.operand2); + binex.type = binex.operand2.type; + return binex; + }; + TypeFlow.prototype.tryAddCandidates = function (signature, actuals, exactCandidates, conversionCandidates, comparisonInfo) { + var lowerBound = signature.nonOptionalParameterCount; + var upperBound = signature.parameters.length; + var formalLen = lowerBound; + var acceptable = false; + if((actuals.length >= lowerBound) && (signature.hasVariableArgList || actuals.length <= upperBound)) { + formalLen = (signature.hasVariableArgList ? signature.parameters.length : actuals.length); + acceptable = true; + } + var repeatType = null; + if(acceptable || signature.hasVariableArgList) { + if(signature.hasVariableArgList) { + formalLen -= 1; + repeatType = (signature.parameters[formalLen]).parameter.typeLink.type; + repeatType = repeatType.elementType; + acceptable = actuals.length >= formalLen; + } + var len = actuals.length; + var exact = acceptable; + var convert = acceptable; + for(var i = 0; i < len; i++) { + var typeA; + if(i < formalLen) { + typeA = (signature.parameters[i]).parameter.typeLink.type; + } else { + typeA = repeatType; + } + var typeB = actuals[i]; + if(!typeA || !typeB || !(this.checker.typesAreIdentical(typeA, typeB))) { + exact = false; + } + if(!this.checker.sourceIsAssignableToTarget(typeB, typeA, comparisonInfo)) { + convert = false; + } + if(!(exact || convert)) { + break; + } + } + if(exact) { + exactCandidates[exactCandidates.length] = signature; + } else if(convert && (exactCandidates.length == 0)) { + conversionCandidates[conversionCandidates.length] = signature; + } + } + }; + TypeFlow.prototype.resolveOverload = function (application, group) { + var rd = this.resolutionDataCache.getResolutionData(); + var actuals = rd.actuals; + var exactCandidates = rd.exactCandidates; + var conversionCandidates = rd.conversionCandidates; + var candidate = null; + var hasOverloads = group.signatures.length > 1; + var comparisonInfo = new TypeScript.TypeComparisonInfo(); + var args = null; + var target = null; + if(application.nodeType == TypeScript.NodeType.Call || application.nodeType == TypeScript.NodeType.New) { + var callEx = application; + args = callEx.arguments; + target = callEx.target; + if(callEx.arguments) { + var len = callEx.arguments.members.length; + for(var i = 0; i < len; i++) { + actuals[i] = callEx.arguments.members[i].type; + } + } + } else if(application.nodeType == TypeScript.NodeType.Index) { + var binExp = application; + target = binExp.operand1; + args = new TypeScript.ASTList(); + args.members[0] = binExp.operand2; + actuals[0] = binExp.operand2.type; + } + for(var j = 0, groupLen = group.signatures.length; j < groupLen; j++) { + var signature = group.signatures[j]; + if(hasOverloads && signature == group.definitionSignature && !this.checker.canCallDefinitionSignature) { + continue; + } + if(!signature.returnType.type && signature.declAST && (signature.typeCheckStatus != TypeScript.TypeCheckStatus.Finished)) { + this.typeCheckFunction(signature.declAST); + } + this.tryAddCandidates(signature, actuals, exactCandidates, conversionCandidates, comparisonInfo); + } + var apparentTarget = target.nodeType == TypeScript.NodeType.Dot ? (target).operand2 : target; + if(exactCandidates.length == 0) { + var applicableCandidates = this.checker.getApplicableSignatures(conversionCandidates, args, comparisonInfo); + if(applicableCandidates.length > 0) { + var candidateInfo = this.checker.findMostApplicableSignature(applicableCandidates, args); + if(candidateInfo.ambiguous) { + this.checker.errorReporter.simpleError(apparentTarget, "Ambiguous call expression - could not choose overload"); + } + candidate = candidateInfo.sig; + } else { + var emsg = "Supplied parameters do not match any signature of call target"; + if(comparisonInfo.message) { + this.checker.errorReporter.simpleError(apparentTarget, emsg + ":\n\t" + comparisonInfo.message); + } else { + this.checker.errorReporter.simpleError(apparentTarget, emsg); + } + } + } else { + if(exactCandidates.length > 1) { + var applicableSigs = []; + for(var i = 0; i < exactCandidates.length; i++) { + applicableSigs[i] = { + signature: exactCandidates[i], + hadProvisionalErrors: false + }; + } + var candidateInfo = this.checker.findMostApplicableSignature(applicableSigs, args); + if(candidateInfo.ambiguous) { + this.checker.errorReporter.simpleError(apparentTarget, "Ambiguous call expression - could not choose overload"); + } + candidate = candidateInfo.sig; + } else { + candidate = exactCandidates[0]; + } + } + this.resolutionDataCache.returnResolutionData(rd); + return candidate; + }; + TypeFlow.prototype.typeCheckNew = function (ast) { + var callEx = ast; + callEx.target = this.typeCheck(callEx.target); + var target = callEx.target; + if(target.type.construct || target.type.call) { + this.preTypeCheckCallArgs(callEx.arguments); + } else { + callEx.arguments = this.typeCheck(callEx.arguments); + } + if(target.type == this.anyType) { + callEx.type = this.anyType; + callEx.arguments = this.typeCheck(callEx.arguments); + } else { + if(target.type.construct) { + var signature = this.resolveOverload(callEx, target.type.construct); + if(signature == null) { + callEx.type = this.anyType; + } else if(signature.returnType.type == this.voidType) { + callEx.type = this.anyType; + callEx.signature = signature; + } else { + callEx.type = signature.returnType.type; + callEx.signature = signature; + } + } else if(target.type.call) { + var signature = this.resolveOverload(callEx, target.type.call); + if(signature == null) { + callEx.type = this.anyType; + } else if((signature.returnType.type == this.voidType) || (signature.returnType.type == this.anyType)) { + callEx.type = this.anyType; + callEx.signature = signature; + } else { + this.checker.errorReporter.simpleError(callEx.target, "new expression only valid on constructors"); + } + } else if(target.type.elementType) { + callEx.type = target.type; + } else { + this.checker.errorReporter.invalidCall(callEx, callEx.nodeType, this.scope); + callEx.type = this.anyType; + } + } + this.postTypeCheckCallArgs(callEx); + return callEx; + }; + TypeFlow.prototype.preTypeCheckCallArgs = function (args) { + if(!args) { + return; + } + for(var i = 0; i < args.members.length; i++) { + switch(args.members[i].nodeType) { + case TypeScript.NodeType.FuncDecl: + case TypeScript.NodeType.ObjectLit: + case TypeScript.NodeType.ArrayLit: + continue; + default: + this.typeCheck(args.members[i]); + break; + } + } + }; + TypeFlow.prototype.postTypeCheckCallArgs = function (callEx) { + var acceptedTargetType = false; + var i = 0; + if(callEx.target && callEx.target.type && callEx.signature && callEx.arguments) { + var sig = callEx.signature; + if(sig && callEx.arguments.members.length >= sig.nonOptionalParameterCount) { + acceptedTargetType = true; + var targetType = null; + var nonVarArgFormalParamLength = sig.hasVariableArgList ? sig.parameters.length - 1 : sig.parameters.length; + var nonVarArgActualParamLength = callEx.arguments.members.length < nonVarArgFormalParamLength ? callEx.arguments.members.length : nonVarArgFormalParamLength; + for(i = 0; i < nonVarArgActualParamLength; i++) { + targetType = sig.parameters[i].getType(); + switch(callEx.arguments.members[i].nodeType) { + case TypeScript.NodeType.FuncDecl: + case TypeScript.NodeType.ObjectLit: + case TypeScript.NodeType.ArrayLit: + this.checker.typeCheckWithContextualType(targetType, this.checker.inProvisionalTypecheckMode(), !sig.parameters[i].declAST.isParenthesized, callEx.arguments.members[i]); + break; + } + } + if(sig.hasVariableArgList) { + var varArgParamIndex = sig.nonOptionalParameterCount - 1; + targetType = sig.parameters[varArgParamIndex].getType(); + if(targetType) { + targetType = targetType.elementType; + } + var isParenthesized = !sig.parameters[varArgParamIndex].declAST.isParenthesized; + for(i = nonVarArgActualParamLength; i < callEx.arguments.members.length; i++) { + switch(callEx.arguments.members[i].nodeType) { + case TypeScript.NodeType.FuncDecl: + case TypeScript.NodeType.ObjectLit: + case TypeScript.NodeType.ArrayLit: + this.checker.typeCheckWithContextualType(targetType, this.checker.inProvisionalTypecheckMode(), isParenthesized, callEx.arguments.members[i]); + break; + } + } + } + } + } + if(!acceptedTargetType && callEx.arguments) { + this.checker.killCurrentContextualType(); + for(i = 0; i < callEx.arguments.members.length; i++) { + switch(callEx.arguments.members[i].nodeType) { + case TypeScript.NodeType.FuncDecl: + case TypeScript.NodeType.ObjectLit: + case TypeScript.NodeType.ArrayLit: + this.typeCheck(callEx.arguments.members[i]); + break; + default: + continue; + } + } + } + }; + TypeFlow.prototype.typeCheckCall = function (ast) { + var callEx = ast; + if(this.checker.styleSettings.newMustBeUsed && (ast.nodeType == TypeScript.NodeType.New)) { + if(TypeScript.hasFlag(ast.flags, TypeScript.ASTFlags.IsStatement)) { + this.checker.errorReporter.styleError(ast, "use of new expression as a statement"); + } + } else if((!this.checker.styleSettings.evalOK) && (ast.nodeType == TypeScript.NodeType.Call)) { + if((callEx.target.nodeType == TypeScript.NodeType.Name) && ((callEx.target).text == "eval")) { + this.checker.errorReporter.styleError(callEx, "eval not permitted"); + } + } + if(callEx.target.nodeType == TypeScript.NodeType.FuncDecl) { + (callEx.target).isInlineCallLiteral = true; + } + var prevInSuperCall = this.inSuperCall; + if(callEx.target.nodeType == TypeScript.NodeType.Super) { + this.inSuperCall = true; + } + callEx.target = this.typeCheck(callEx.target); + this.preTypeCheckCallArgs(callEx.arguments); + var target = callEx.target; + if((target.type == null) || (target.type == this.anyType) || (this.functionInterfaceType && target.type == this.functionInterfaceType)) { + callEx.type = this.anyType; + } else { + var fnType = target.type; + if(fnType.call) { + var signature = this.resolveOverload(callEx, fnType.call); + if(signature == null) { + callEx.type = this.anyType; + } else { + callEx.type = signature.returnType.type; + callEx.signature = signature; + } + } else { + if(callEx.target.nodeType == TypeScript.NodeType.Super && this.thisFnc && this.thisFnc.isConstructor && TypeScript.hasFlag(this.thisFnc.fncFlags, TypeScript.FncFlags.ClassMethod)) { + var signature = fnType.symbol.type.construct ? this.resolveOverload(callEx, fnType.symbol.type.construct) : null; + if(signature == null) { + callEx.type = this.anyType; + } else { + callEx.flags |= TypeScript.ASTFlags.ClassBaseConstructorCall; + callEx.type = signature.returnType.type; + callEx.signature = signature; + } + } else { + callEx.type = this.anyType; + this.checker.errorReporter.invalidCall(callEx, callEx.nodeType, this.scope); + } + } + } + this.postTypeCheckCallArgs(callEx); + this.inSuperCall = prevInSuperCall; + return callEx; + }; + TypeFlow.prototype.assignScopes = function (ast) { + var script = ast; + this.checker.locationInfo = script.locationInfo; + var globalChain = new ScopeChain(this.checker.gloMod, null, this.globalScope); + var context = new TypeScript.AssignScopeContext(globalChain, this, [ + this.checker.currentModDecl + ]); + TypeScript.getAstWalkerFactory().walk(ast, TypeScript.preAssignScopes, TypeScript.postAssignScopes, null, context); + }; + TypeFlow.prototype.findMemberScope = function (enclosingScopeContext, matchFlag) { + var enclosingScope = enclosingScopeContext.getScope(); + var pos = enclosingScopeContext.pos - enclosingScopeContext.getScriptFragmentPosition(); + var scriptFragment = enclosingScopeContext.getScriptFragment(); + var memContext = new TypeScript.MemberScopeContext(this, pos, matchFlag); + memContext.scope = enclosingScope; + if(scriptFragment.nodeType == TypeScript.NodeType.Name) { + return scriptFragment.type.getMemberScope(this); + } else { + TypeScript.getAstWalkerFactory().walk(scriptFragment, TypeScript.preFindMemberScope, null, null, memContext); + if(memContext.ast && enclosingScopeContext.enclosingClassDecl && memContext.ast.type == enclosingScopeContext.enclosingClassDecl.type.instanceType) { + enclosingScopeContext.publicsOnly = false; + } + if(memContext.type) { + return memContext.type.getMemberScope(this); + } else { + return null; + } + } + }; + TypeFlow.prototype.findMemberScopeAt = function (enclosingScopeContext) { + return this.findMemberScope(enclosingScopeContext, TypeScript.ASTFlags.DotLHS); + }; + TypeFlow.prototype.findMemberScopeAtFullAst = function (enclosingScopeContext) { + var matchFlag = TypeScript.ASTFlags.DotLHS; + var pos = enclosingScopeContext.pos; + var astResult = null; + var preFindMemberScopeFullAst = function (ast, parent, walker) { + if(TypeScript.isValidAstNode(ast)) { + if(TypeScript.hasFlag(ast.flags, matchFlag) && (pos == ast.limChar || (pos - 1) == ast.limChar)) { + astResult = ast; + walker.options.stopWalk(); + } + walker.options.goChildren = (ast.minChar <= pos) && (pos <= ast.limChar); + } + return ast; + }; + var preFindMemberScopeFullAstFuzy = function (ast, parent, walker) { + if(TypeScript.isValidAstNode(ast)) { + if(TypeScript.hasFlag(ast.flags, matchFlag) && ((ast.minChar < pos) && (pos <= ast.limChar))) { + astResult = ast; + } + walker.options.goChildren = (ast.minChar <= pos) && (pos <= ast.limChar); + } + return ast; + }; + TypeScript.getAstWalkerFactory().walk(enclosingScopeContext.script, preFindMemberScopeFullAst); + if(astResult == null) { + TypeScript.getAstWalkerFactory().walk(enclosingScopeContext.script, preFindMemberScopeFullAstFuzy); + } + if(astResult && enclosingScopeContext.enclosingClassDecl && astResult.type == enclosingScopeContext.enclosingClassDecl.type.instanceType) { + enclosingScopeContext.publicsOnly = false; + } + if(astResult && astResult.type) { + return astResult.type.getMemberScope(this); + } else { + return null; + } + }; + return TypeFlow; + })(); + TypeScript.TypeFlow = TypeFlow; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Primitive) { + Primitive._map = []; + Primitive.None = 0; + Primitive.Void = 1; + Primitive.Double = 2; + Primitive.String = 4; + Primitive.Boolean = 8; + Primitive.Any = 16; + Primitive.Null = 32; + Primitive.Undefined = 64; + })(TypeScript.Primitive || (TypeScript.Primitive = {})); + var Primitive = TypeScript.Primitive; + var MemberName = (function () { + function MemberName() { + this.prefix = ""; + this.suffix = ""; + } + MemberName.prototype.isString = function () { + return false; + }; + MemberName.prototype.isArray = function () { + return false; + }; + MemberName.prototype.toString = function () { + return MemberName.memberNameToString(this); + }; + MemberName.memberNameToString = function memberNameToString(memberName) { + var result = memberName.prefix; + if(memberName.isString()) { + result += (memberName).text; + } else { + var ar = memberName; + for(var index = 0; index < ar.entries.length; index++) { + result += MemberName.memberNameToString(ar.entries[index]); + result += ar.delim; + } + } + result += memberName.suffix; + return result; + }; + MemberName.create = function create(arg1, arg2, arg3) { + if(typeof arg1 == "string") { + return new MemberNameString(arg1); + } else { + var result = new MemberNameArray(); + if(arg2) { + result.prefix = arg2; + } + if(arg3) { + result.suffix = arg3; + } + result.entries.push(arg1); + return result; + } + }; + return MemberName; + })(); + TypeScript.MemberName = MemberName; + var MemberNameString = (function (_super) { + __extends(MemberNameString, _super); + function MemberNameString(text) { + _super.call(this); + this.text = text; + } + MemberNameString.prototype.isString = function () { + return true; + }; + return MemberNameString; + })(MemberName); + TypeScript.MemberNameString = MemberNameString; + var MemberNameArray = (function (_super) { + __extends(MemberNameArray, _super); + function MemberNameArray() { + _super.apply(this, arguments); + + this.delim = ""; + this.entries = []; + } + MemberNameArray.prototype.isArray = function () { + return true; + }; + MemberNameArray.prototype.add = function (entry) { + this.entries.push(entry); + }; + MemberNameArray.prototype.addAll = function (entries) { + for(var i = 0; i < entries.length; i++) { + this.entries.push(entries[i]); + } + }; + return MemberNameArray; + })(MemberName); + TypeScript.MemberNameArray = MemberNameArray; + var currentTypeID = -1; + var Type = (function () { + function Type() { + this.typeID = currentTypeID++; + this.construct = null; + this.call = null; + this.index = null; + this.passTypeCreated = TypeScript.CompilerDiagnostics.analysisPass; + this.primitiveTypeClass = Primitive.None; + this.typeFlags = TypeScript.TypeFlags.None; + } + Type.prototype.baseClass = function () { + if(this.extendsList && (this.extendsList.length > 0)) { + return this.extendsList[0]; + } else { + return null; + } + }; + Type.prototype.getArrayBase = function (arrInstType, checker) { + return this.arrayCache.specialize(arrInstType, checker); + }; + Type.prototype.isClass = function () { + return this.instanceType != null; + }; + Type.prototype.isArray = function () { + return this.elementType != null; + }; + Type.prototype.isClassInstance = function () { + return this.symbol && !this.elementType && (this.symbol).type.isClass(); + }; + Type.prototype.getInstanceType = function () { + if(this.isClass()) { + return this.instanceType; + } else { + return this; + } + }; + Type.prototype.hasImplementation = function () { + return TypeScript.hasFlag(this.typeFlags, TypeScript.TypeFlags.HasImplementation); + }; + Type.prototype.setHasImplementation = function () { + this.typeFlags |= TypeScript.TypeFlags.HasImplementation; + }; + Type.prototype.isDouble = function () { + return TypeScript.hasFlag(this.primitiveTypeClass, Primitive.Double); + }; + Type.prototype.isString = function () { + return TypeScript.hasFlag(this.primitiveTypeClass, Primitive.String); + }; + Type.prototype.isBoolean = function () { + return TypeScript.hasFlag(this.primitiveTypeClass, Primitive.Boolean); + }; + Type.prototype.isNull = function () { + return TypeScript.hasFlag(this.primitiveTypeClass, Primitive.Null); + }; + Type.prototype.getTypeName = function () { + return this.getMemberTypeName("", true, false, null); + }; + Type.prototype.getScopedTypeName = function (scope, getPrettyTypeName) { + return this.getMemberTypeName("", true, false, scope, getPrettyTypeName); + }; + Type.prototype.getScopedTypeNameEx = function (scope, getPrettyTypeName) { + return this.getMemberTypeNameEx("", true, false, scope, getPrettyTypeName); + }; + Type.prototype.callCount = function () { + var total = 0; + if(this.call) { + total += this.call.signatures.length; + } + if(this.construct) { + total += this.construct.signatures.length; + } + if(this.index) { + total += this.index.signatures.length; + } + return total; + }; + Type.prototype.getMemberTypeName = function (prefix, topLevel, isElementType, scope, getPrettyTypeName) { + var memberName = this.getMemberTypeNameEx(prefix, topLevel, isElementType, scope, getPrettyTypeName); + return memberName.toString(); + }; + Type.prototype.getMemberTypeNameEx = function (prefix, topLevel, isElementType, scope, getPrettyTypeName) { + if(this.elementType) { + return MemberName.create(this.elementType.getMemberTypeNameEx(prefix, false, true, scope), "", "[]"); + } else if(this.symbol && this.symbol.name && this.symbol.name != "_anonymous" && (((this.call == null) && (this.construct == null) && (this.index == null)) || (TypeScript.hasFlag(this.typeFlags, TypeScript.TypeFlags.BuildingName)) || (this.members && (!this.isClass())))) { + var tn = this.symbol.scopeRelativeName(scope); + return MemberName.create(tn == "null" ? "any" : tn); + } else { + if(this.members || this.call || this.construct) { + if(TypeScript.hasFlag(this.typeFlags, TypeScript.TypeFlags.BuildingName)) { + return MemberName.create("this"); + } + this.typeFlags |= TypeScript.TypeFlags.BuildingName; + var builder = ""; + var allMemberNames = new MemberNameArray(); + var curlies = isElementType || this.index != null; + var memCount = 0; + var delim = "; "; + if(this.members) { + this.members.allMembers.map(function (key, s, unused) { + var sym = s; + if(!TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.BuiltIn)) { + var typeNameMember = sym.getTypeNameEx(scope); + if(typeNameMember.isArray() && (typeNameMember).delim == delim) { + allMemberNames.addAll((typeNameMember).entries); + } else { + allMemberNames.add(typeNameMember); + } + memCount++; + curlies = true; + } + }, null); + } + var signatureCount = this.callCount(); + var j; + var len = 0; + var getPrettyFunctionOverload = getPrettyTypeName && !curlies && this.call && this.call.signatures.length > 1 && !this.members && !this.construct; + var shortform = !curlies && (signatureCount == 1 || getPrettyFunctionOverload) && topLevel; + if(this.call) { + allMemberNames.addAll(this.call.toStrings(prefix, shortform, scope, getPrettyFunctionOverload)); + } + if(this.construct) { + allMemberNames.addAll(this.construct.toStrings("new", shortform, scope)); + } + if(this.index) { + allMemberNames.addAll(this.index.toStrings("", shortform, scope)); + } + if((curlies) || (!getPrettyFunctionOverload && (signatureCount > 1) && topLevel)) { + allMemberNames.prefix = "{ "; + allMemberNames.suffix = "}"; + allMemberNames.delim = delim; + } else if(allMemberNames.entries.length > 1) { + allMemberNames.delim = delim; + } + this.typeFlags &= (~TypeScript.TypeFlags.BuildingName); + if((signatureCount == 0) && (memCount == 0)) { + return MemberName.create("{}"); + } else { + return allMemberNames; + } + } else { + return MemberName.create("{}"); + } + } + }; + Type.prototype.checkDecl = function (checker) { + if(this.isClassInstance() || this.isClass()) { + if(this.symbol.declAST) { + checker.typeFlow.inScopeTypeCheckDecl(this.symbol.declAST); + } + } + }; + Type.prototype.getMemberScope = function (flow) { + if(this == flow.anyType) { + return null; + } else if(this.isDouble()) { + if(flow.numberInterfaceType) { + return flow.numberInterfaceType.memberScope; + } else { + return null; + } + } else if(this.isBoolean()) { + if(flow.booleanInterfaceType) { + return flow.booleanInterfaceType.memberScope; + } else { + return null; + } + } else if(this == flow.stringType) { + if(flow.stringInterfaceType) { + return flow.stringInterfaceType.memberScope; + } else { + return null; + } + } else if(this.elementType) { + if(flow.arrayInterfaceType) { + var arrInstType = this.elementType.getArrayBase(flow.arrayInterfaceType, flow.checker); + return arrInstType.memberScope; + } else { + return null; + } + } else { + return this.memberScope; + } + }; + Type.prototype.isReferenceType = function () { + return this.members || this.extendsList || this.construct || this.call || this.index || this.elementType; + }; + Type.prototype.specializeType = function (pattern, replacement, checker, membersOnly) { + if(pattern == this) { + return replacement; + } + var result = this; + if(membersOnly) { + if(this.isReferenceType()) { + result = new Type(); + if(this.members) { + result.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + this.members.publicMembers.map(function (key, s, unused) { + var sym = s; + var bSym = sym.specializeType(pattern, replacement, checker); + result.members.addPublicMember(bSym.name, bSym); + }, null); + this.members.privateMembers.map(function (key, s, unused) { + var sym = s; + var bSym = sym.specializeType(pattern, replacement, checker); + result.members.addPrivateMember(bSym.name, bSym); + }, null); + } + if(this.ambientMembers) { + result.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + this.ambientMembers.publicMembers.map(function (key, s, unused) { + var sym = s; + var bSym = sym.specializeType(pattern, replacement, checker); + result.ambientMembers.addPublicMember(bSym.name, bSym); + }, null); + this.ambientMembers.privateMembers.map(function (key, s, unused) { + var sym = s; + var bSym = sym.specializeType(pattern, replacement, checker); + result.ambientMembers.addPrivateMember(bSym.name, bSym); + }, null); + } + result.containedScope = checker.scopeOf(result); + result.memberScope = result.containedScope; + } + } else { + if(this.elementType) { + if(this.elementType == pattern) { + result = checker.makeArrayType(replacement); + } else { + if(this.elementType.elementType == pattern) { + result = checker.makeArrayType(checker.makeArrayType(replacement)); + } + } + } else if(this.call) { + result = new Type(); + result.call = this.call.specializeType(pattern, replacement, checker); + } + } + return result; + }; + Type.prototype.hasBase = function (baseType) { + if(baseType == this) { + return true; + } else { + if(this.extendsList) { + for(var i = 0, len = this.extendsList.length; i < len; i++) { + if(this.extendsList[i].hasBase(baseType)) { + return true; + } + } + } + } + return false; + }; + Type.prototype.mergeOrdered = function (b, checker, acceptVoid, comparisonInfo) { + if((this == checker.anyType) || (b == checker.anyType)) { + return checker.anyType; + } else if(this == b) { + return this; + } else if((b == checker.nullType) && this != checker.nullType) { + return this; + } else if((this == checker.nullType) && (b != checker.nullType)) { + return b; + } else if(acceptVoid && (b == checker.voidType) && this != checker.voidType) { + return this; + } else if(acceptVoid && (this == checker.voidType) && (b != checker.voidType)) { + return b; + } else if((b == checker.undefinedType) && this != checker.undefinedType) { + return this; + } else if((this == checker.undefinedType) && (b != checker.undefinedType)) { + return b; + } else if(this.elementType && b.elementType) { + if(this.elementType == b.elementType) { + return this; + } else { + var mergedET = this.elementType.mergeOrdered(b.elementType, checker, acceptVoid, comparisonInfo); + if(mergedET == null) { + return checker.makeArrayType(checker.anyType); + } else { + return checker.makeArrayType(mergedET); + } + } + } else if(checker.sourceIsSubtypeOfTarget(this, b, comparisonInfo)) { + return b; + } else if(checker.sourceIsSubtypeOfTarget(b, this, comparisonInfo)) { + return this; + } else { + return null; + } + }; + Type.prototype.isModuleType = function () { + return false; + }; + Type.prototype.hasMembers = function () { + return this.members != null; + }; + Type.prototype.getAllEnclosedTypes = function () { + return null; + }; + Type.prototype.getAllAmbientEnclosedTypes = function () { + return null; + }; + Type.prototype.getPublicEnclosedTypes = function () { + return null; + }; + Type.prototype.getpublicAmbientEnclosedTypes = function () { + return null; + }; + Type.prototype.getDocComments = function () { + if(this.elementType || !this.symbol) { + return []; + } + if(this.isClassInstance() || this.isClass()) { + if(this.symbol.declAST.nodeType == TypeScript.NodeType.FuncDecl) { + return (this.symbol.declAST).classDecl.getDocComments(); + } else { + return this.symbol.getDocComments(); + } + } + if(this.symbol.name && this.symbol.name != "_anonymous" && (((this.call == null) && (this.construct == null) && (this.index == null)) || this.members)) { + return this.symbol.getDocComments(); + } + return []; + }; + return Type; + })(); + TypeScript.Type = Type; + var ModuleType = (function (_super) { + __extends(ModuleType, _super); + function ModuleType(enclosedTypes, ambientEnclosedTypes) { + _super.call(this); + this.enclosedTypes = enclosedTypes; + this.ambientEnclosedTypes = ambientEnclosedTypes; + this.importedModules = []; + } + ModuleType.prototype.isModuleType = function () { + return true; + }; + ModuleType.prototype.hasMembers = function () { + return this.members != null || this.enclosedTypes != null; + }; + ModuleType.prototype.getAllEnclosedTypes = function () { + return this.enclosedTypes; + }; + ModuleType.prototype.getAllAmbientEnclosedTypes = function () { + return this.ambientEnclosedTypes; + }; + ModuleType.prototype.getPublicEnclosedTypes = function () { + return null; + }; + ModuleType.prototype.getpublicAmbientEnclosedTypes = function () { + return null; + }; + ModuleType.findDynamicModuleNameInHashTable = function findDynamicModuleNameInHashTable(moduleType, members) { + var moduleName = null; + members.map(function (key, s, c) { + if(moduleName == null && !TypeScript.isQuoted(key)) { + var symbol = s; + var type = symbol.getType(); + if(type == moduleType) { + moduleName = { + name: key, + symbol: symbol + }; + } + } + }, null); + return moduleName; + }; + ModuleType.prototype.findDynamicModuleName = function (moduleType) { + var moduleName = null; + moduleName = ModuleType.findDynamicModuleNameInHashTable(moduleType, this.members.allMembers); + if(moduleName == null) { + moduleName = ModuleType.findDynamicModuleNameInHashTable(moduleType, this.ambientMembers.allMembers); + } + return moduleName; + }; + return ModuleType; + })(Type); + TypeScript.ModuleType = ModuleType; + var TypeLink = (function () { + function TypeLink() { + this.type = null; + this.ast = null; + } + return TypeLink; + })(); + TypeScript.TypeLink = TypeLink; + function getTypeLink(ast, checker, autoVar) { + var result = new TypeLink(); + result.ast = ast; + if((ast == null) && (autoVar)) { + result.type = checker.anyType; + } else { + result.type = null; + } + return result; + } + TypeScript.getTypeLink = getTypeLink; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + function stripQuotes(str) { + return str.replace("\"", "").replace("'", "").replace("'", "").replace("\"", ""); + } + TypeScript.stripQuotes = stripQuotes; + function isSingleQuoted(str) { + return str.indexOf("'") != -1; + } + TypeScript.isSingleQuoted = isSingleQuoted; + function isQuoted(str) { + return str.indexOf("\"") != -1 || isSingleQuoted(str); + } + TypeScript.isQuoted = isQuoted; + function quoteStr(str) { + return "\"" + str + "\""; + } + TypeScript.quoteStr = quoteStr; + function swapQuotes(str) { + if(str.indexOf("\"") != -1) { + str = str.replace("\"", "'"); + str = str.replace("\"", "'"); + } else { + str = str.replace("'", "\""); + str = str.replace("'", "\""); + } + return str; + } + TypeScript.swapQuotes = swapQuotes; + function changeToSingleQuote(str) { + if(str.indexOf("\"") != -1) { + str = str.replace("\"", "'"); + str = str.replace("\"", "'"); + } + return str; + } + TypeScript.changeToSingleQuote = changeToSingleQuote; + function switchToForwardSlashes(path) { + return path.replace(/\\/g, "/"); + } + TypeScript.switchToForwardSlashes = switchToForwardSlashes; + function trimModName(modName) { + if(modName.length > 6 && modName.substring(modName.length - 6, modName.length) == ".d.str") { + return modName.substring(0, modName.length - 6); + } + if(modName.length > 4 && modName.substring(modName.length - 4, modName.length) == ".str") { + return modName.substring(0, modName.length - 4); + } + if(modName.length > 5 && modName.substring(modName.length - 5, modName.length) == ".d.ts") { + return modName.substring(0, modName.length - 5); + } + if(modName.length > 3 && modName.substring(modName.length - 3, modName.length) == ".ts") { + return modName.substring(0, modName.length - 3); + } + if(modName.length > 3 && modName.substring(modName.length - 3, modName.length) == ".js") { + return modName.substring(0, modName.length - 3); + } + return modName; + } + TypeScript.trimModName = trimModName; + function getDeclareFilePath(fname) { + return isSTRFile(fname) ? changePathToDSTR(fname) : isTSFile(fname) ? changePathToDTS(fname) : changePathToDTS(fname); + } + TypeScript.getDeclareFilePath = getDeclareFilePath; + function isFileOfExtension(fname, ext) { + var invariantFname = fname.toLocaleUpperCase(); + var invariantExt = ext.toLocaleUpperCase(); + var extLength = invariantExt.length; + return invariantFname.length > extLength && invariantFname.substring(invariantFname.length - extLength, invariantFname.length) == invariantExt; + } + function isJSFile(fname) { + return isFileOfExtension(fname, ".js"); + } + TypeScript.isJSFile = isJSFile; + function isSTRFile(fname) { + return isFileOfExtension(fname, ".str"); + } + TypeScript.isSTRFile = isSTRFile; + function isTSFile(fname) { + return isFileOfExtension(fname, ".ts"); + } + TypeScript.isTSFile = isTSFile; + function isDSTRFile(fname) { + return isFileOfExtension(fname, ".d.str"); + } + TypeScript.isDSTRFile = isDSTRFile; + function isDTSFile(fname) { + return isFileOfExtension(fname, ".d.ts"); + } + TypeScript.isDTSFile = isDTSFile; + function getPrettyName(modPath, quote, treatAsFileName) { + if (typeof quote === "undefined") { quote = true; } + if (typeof treatAsFileName === "undefined") { treatAsFileName = false; } + var modName = treatAsFileName ? switchToForwardSlashes(modPath) : trimModName(stripQuotes(modPath)); + var components = this.getPathComponents(modName); + return components.length ? (quote ? quoteStr(components[components.length - 1]) : components[components.length - 1]) : modPath; + } + TypeScript.getPrettyName = getPrettyName; + function getPathComponents(path) { + return path.split("/"); + } + TypeScript.getPathComponents = getPathComponents; + function getRelativePathToFixedPath(fixedModFilePath, absoluteModPath) { + absoluteModPath = switchToForwardSlashes(absoluteModPath); + var modComponents = this.getPathComponents(absoluteModPath); + var fixedModComponents = this.getPathComponents(fixedModFilePath); + var joinStartIndex = 0; + for(; joinStartIndex < modComponents.length && joinStartIndex < fixedModComponents.length; joinStartIndex++) { + if(fixedModComponents[joinStartIndex] != modComponents[joinStartIndex]) { + break; + } + } + if(joinStartIndex != 0) { + var relativePath = ""; + var relativePathComponents = modComponents.slice(joinStartIndex, modComponents.length); + for(; joinStartIndex < fixedModComponents.length; joinStartIndex++) { + if(fixedModComponents[joinStartIndex] != "") { + relativePath = relativePath + "../"; + } + } + return relativePath + relativePathComponents.join("/"); + } + return absoluteModPath; + } + TypeScript.getRelativePathToFixedPath = getRelativePathToFixedPath; + function quoteBaseName(modPath) { + var modName = trimModName(stripQuotes(modPath)); + var path = getRootFilePath(modName); + if(path == "") { + return modPath; + } else { + var components = modName.split(path); + var fileIndex = components.length > 1 ? 1 : 0; + return quoteStr(components[fileIndex]); + } + } + TypeScript.quoteBaseName = quoteBaseName; + function changePathToSTR(modPath) { + return trimModName(stripQuotes(modPath)) + ".str"; + } + TypeScript.changePathToSTR = changePathToSTR; + function changePathToDSTR(modPath) { + return trimModName(stripQuotes(modPath)) + ".d.str"; + } + TypeScript.changePathToDSTR = changePathToDSTR; + function changePathToTS(modPath) { + return trimModName(stripQuotes(modPath)) + ".ts"; + } + TypeScript.changePathToTS = changePathToTS; + function changePathToDTS(modPath) { + return trimModName(stripQuotes(modPath)) + ".d.ts"; + } + TypeScript.changePathToDTS = changePathToDTS; + function isRelative(path) { + return path.charAt(0) == "."; + } + TypeScript.isRelative = isRelative; + function isRooted(path) { + return path.charAt(0) == "\\" || path.charAt(0) == "/" || (path.indexOf(":\\") != -1) || (path.indexOf(":/") != -1); + } + TypeScript.isRooted = isRooted; + function getRootFilePath(outFname) { + if(outFname == "") { + return outFname; + } else { + var isPath = outFname.indexOf("/") != -1; + return isPath ? filePath(outFname) : ""; + } + } + TypeScript.getRootFilePath = getRootFilePath; + function filePathComponents(fullPath) { + fullPath = switchToForwardSlashes(fullPath); + var components = getPathComponents(fullPath); + return components.slice(0, components.length - 1); + } + TypeScript.filePathComponents = filePathComponents; + function filePath(fullPath) { + var path = filePathComponents(fullPath); + return path.join("/") + "/"; + } + TypeScript.filePath = filePath; + function normalizeURL(url) { + var hostDomainAndPortRegex = /^(https?:\/\/[\-\w\.]+(:\d+)?\/)(.*)$/i; + var matches = hostDomainAndPortRegex.exec(url); + if(matches) { + var hostDomainAndPort = matches[1]; + var actualPath = matches[3]; + return hostDomainAndPort + normalizePath(actualPath); + } + return normalizePath(url); + } + TypeScript.normalizeURL = normalizeURL; + TypeScript.pathNormalizeRegExp = /\//g; + function normalizePath(path) { + path = switchToForwardSlashes(path); + var startedWithSep = path.charAt(0) === "/"; + var parts = this.getPathComponents(path); + for(var i = 0; i < parts.length; i++) { + if(parts[i] === "." || parts[i] === "") { + parts.splice(i, 1); + i--; + } + if(i > 0 && parts[i] === ".." && parts[i - 1] !== "..") { + parts.splice(i - 1, 2); + i -= 2; + } + } + return (startedWithSep ? "/" : "") + parts.join("/"); + } + TypeScript.normalizePath = normalizePath; + function normalizeImportPath(path) { + return normalizePath(path); + } + TypeScript.normalizeImportPath = normalizeImportPath; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SourceUnit = (function () { + function SourceUnit(path, content) { + this.path = path; + this.content = content; + this.referencedFiles = null; + } + SourceUnit.prototype.getText = function (start, end) { + return this.content.substring(start, end); + }; + SourceUnit.prototype.getLength = function () { + return this.content.length; + }; + return SourceUnit; + })(); + TypeScript.SourceUnit = SourceUnit; + var CompilationEnvironment = (function () { + function CompilationEnvironment(compilationSettings, ioHost) { + this.compilationSettings = compilationSettings; + this.ioHost = ioHost; + this.residentCode = []; + this.code = []; + this.inputOutputMap = []; + } + return CompilationEnvironment; + })(); + TypeScript.CompilationEnvironment = CompilationEnvironment; + var CodeResolver = (function () { + function CodeResolver(environment) { + this.environment = environment; + this.visited = { + }; + } + CodeResolver.prototype.resolveCode = function (referencePath, parentPath, performSearch, resolutionDispatcher) { + var resolvedFile = { + content: null, + path: referencePath + }; + var ioHost = this.environment.ioHost; + var isRelativePath = TypeScript.isRelative(referencePath); + var isRootedPath = isRelativePath ? false : TypeScript.isRooted(referencePath); + var normalizedPath = isRelativePath ? ioHost.resolvePath(parentPath + "/" + referencePath) : (isRootedPath || !parentPath || performSearch ? referencePath : parentPath + "/" + referencePath); + if(!TypeScript.isSTRFile(normalizedPath) && !TypeScript.isTSFile(normalizedPath)) { + normalizedPath += ".ts"; + } + normalizedPath = TypeScript.switchToForwardSlashes(TypeScript.stripQuotes(normalizedPath)); + var absoluteModuleID = this.environment.compilationSettings.useCaseSensitiveFileResolution ? normalizedPath : normalizedPath.toLocaleUpperCase(); + if(!this.visited[absoluteModuleID]) { + if(isRelativePath || isRootedPath || !performSearch) { + try { + TypeScript.CompilerDiagnostics.debugPrint(" Reading code from " + normalizedPath); + try { + resolvedFile.content = ioHost.readFile(normalizedPath); + } catch (err) { + try { + if(TypeScript.isSTRFile(normalizedPath)) { + normalizedPath = TypeScript.changePathToTS(normalizedPath); + } else if(TypeScript.isTSFile(normalizedPath)) { + normalizedPath = TypeScript.changePathToSTR(normalizedPath); + } + TypeScript.CompilerDiagnostics.debugPrint(" Reading code from " + normalizedPath); + resolvedFile.content = ioHost.readFile(normalizedPath); + } catch (err) { + normalizedPath = TypeScript.changePathToDSTR(normalizedPath); + TypeScript.CompilerDiagnostics.debugPrint(" Reading code from " + normalizedPath); + try { + resolvedFile.content = ioHost.readFile(normalizedPath); + } catch (err) { + normalizedPath = TypeScript.changePathToDTS(normalizedPath); + TypeScript.CompilerDiagnostics.debugPrint(" Reading code from " + normalizedPath); + resolvedFile.content = ioHost.readFile(normalizedPath); + } + } + } + TypeScript.CompilerDiagnostics.debugPrint(" Found code at " + normalizedPath); + resolvedFile.path = normalizedPath; + this.visited[absoluteModuleID] = true; + } catch (err) { + TypeScript.CompilerDiagnostics.debugPrint(" Did not find code for " + referencePath); + return false; + } + } else { + resolvedFile = ioHost.findFile(parentPath, normalizedPath); + if(!resolvedFile) { + if(TypeScript.isSTRFile(normalizedPath)) { + normalizedPath = TypeScript.changePathToTS(normalizedPath); + } else if(TypeScript.isTSFile(normalizedPath)) { + normalizedPath = TypeScript.changePathToSTR(normalizedPath); + } + resolvedFile = ioHost.findFile(parentPath, normalizedPath); + } + if(!resolvedFile) { + normalizedPath = TypeScript.changePathToDTS(normalizedPath); + resolvedFile = ioHost.findFile(parentPath, normalizedPath); + if(!resolvedFile) { + normalizedPath = TypeScript.changePathToDSTR(normalizedPath); + resolvedFile = ioHost.findFile(parentPath, normalizedPath); + } + } + if(resolvedFile) { + resolvedFile.path = TypeScript.switchToForwardSlashes(TypeScript.stripQuotes(resolvedFile.path)); + TypeScript.CompilerDiagnostics.debugPrint(referencePath + " resolved to: " + resolvedFile.path); + resolvedFile.content = resolvedFile.content; + this.visited[absoluteModuleID] = true; + } else { + TypeScript.CompilerDiagnostics.debugPrint("Could not find " + referencePath); + } + } + if(resolvedFile && resolvedFile.content != null) { + var rootDir = ioHost.dirName(resolvedFile.path); + var sourceUnit = new SourceUnit(resolvedFile.path, resolvedFile.content); + var preProcessedFileInfo = TypeScript.preProcessFile(sourceUnit, this.environment.compilationSettings); + var resolvedFilePath = ioHost.resolvePath(resolvedFile.path); + sourceUnit.referencedFiles = preProcessedFileInfo.referencedFiles; + for(var i = 0; i < preProcessedFileInfo.referencedFiles.length; i++) { + var fileReference = preProcessedFileInfo.referencedFiles[i]; + var normalizedPath = TypeScript.isRooted(fileReference.path) ? fileReference.path : rootDir + "/" + fileReference.path; + normalizedPath = ioHost.resolvePath(normalizedPath); + if(resolvedFilePath == normalizedPath) { + resolutionDispatcher.postResolutionError(normalizedPath, fileReference.startLine, fileReference.startCol, "Incorrect reference: File contains reference to itself."); + continue; + } + var resolutionResult = this.resolveCode(fileReference.path, rootDir, false, resolutionDispatcher); + if(!resolutionResult) { + resolutionDispatcher.postResolutionError(resolvedFilePath, fileReference.startLine, fileReference.startCol, "Incorrect reference: referenced file: \"" + fileReference.path + "\" cannot be resolved."); + } + } + for(var i = 0; i < preProcessedFileInfo.importedFiles.length; i++) { + var fileImport = preProcessedFileInfo.importedFiles[i]; + var resolutionResult = this.resolveCode(fileImport.path, rootDir, true, resolutionDispatcher); + if(!resolutionResult) { + resolutionDispatcher.postResolutionError(resolvedFilePath, fileImport.startLine, fileImport.startCol, "Incorrect reference: imported file: \"" + fileImport.path + "\" cannot be resolved."); + } + } + resolutionDispatcher.postResolution(sourceUnit.path, sourceUnit); + } + } + return true; + }; + return CodeResolver; + })(); + TypeScript.CodeResolver = CodeResolver; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var StyleSettings = (function () { + function StyleSettings() { + this.bitwise = false; + this.blockInCompoundStmt = false; + this.eqeqeq = false; + this.forin = false; + this.emptyBlocks = true; + this.newMustBeUsed = false; + this.requireSemi = false; + this.assignmentInCond = false; + this.eqnull = false; + this.evalOK = true; + this.innerScopeDeclEscape = true; + this.funcInLoop = true; + this.reDeclareLocal = true; + this.literalSubscript = true; + this.implicitAny = false; + } + StyleSettings.prototype.setOption = function (opt, val) { + var optExists = this[opt]; + if(optExists !== undefined) { + this[opt] = val; + return true; + } else { + return false; + } + }; + StyleSettings.prototype.parseOptions = function (str) { + var opts = str.split(";"); + for(var i = 0, len = opts.length; i < len; i++) { + var opt = opts[i]; + var val = true; + var colonIndex = opt.lastIndexOf(":"); + if(colonIndex >= 0) { + var valStr = opt.substring(colonIndex + 1); + opt = opt.substring(0, colonIndex); + if(valStr == "off") { + val = false; + } + } + if(!this.setOption(opt, val)) { + return false; + } + } + return true; + }; + return StyleSettings; + })(); + TypeScript.StyleSettings = StyleSettings; + var CompilationSettings = (function () { + function CompilationSettings() { + this.styleSettings = new StyleSettings(); + this.propagateConstants = false; + this.minWhitespace = false; + this.parseOnly = false; + this.errorRecovery = false; + this.emitComments = false; + this.watch = false; + this.exec = false; + this.resolve = true; + this.controlFlow = false; + this.printControlFlow = false; + this.controlFlowUseDef = false; + this.errorOnWith = true; + this.preprocess = true; + this.canCallDefinitionSignature = false; + this.inferPropertiesFromThisAssignment = false; + this.useDefaultLib = true; + this.codeGenTarget = TypeScript.CodeGenTarget.ES3; + this.moduleGenTarget = TypeScript.ModuleGenTarget.Synchronous; + this.outputOption = ""; + this.mapSourceFiles = false; + this.emitFullSourceMapPath = false; + this.generateDeclarationFiles = false; + this.useCaseSensitiveFileResolution = false; + } + CompilationSettings.prototype.setStyleOptions = function (str) { + this.styleSettings.parseOptions(str); + }; + return CompilationSettings; + })(); + TypeScript.CompilationSettings = CompilationSettings; + function getFileReferenceFromReferencePath(comment) { + var referencesRegEx = /^(\/\/\/\s*/gim; + var match = referencesRegEx.exec(comment); + if(match) { + var path = TypeScript.normalizePath(match[3]); + var adjustedPath = TypeScript.normalizePath(path); + var isResident = match.length >= 7 && match[6] == "true"; + if(isResident) { + TypeScript.CompilerDiagnostics.debugPrint(path + " is resident"); + } + return { + minChar: 0, + limChar: 0, + startLine: 0, + startCol: 0, + path: TypeScript.switchToForwardSlashes(adjustedPath), + isResident: isResident + }; + } else { + return null; + } + } + function getAdditionalDependencyPath(comment) { + var amdDependencyRegEx = /^(\/\/\/\s*/gim; + var match = amdDependencyRegEx.exec(comment); + if(match) { + var path = match[3]; + return path; + } else { + return null; + } + } + TypeScript.getAdditionalDependencyPath = getAdditionalDependencyPath; + function getImplicitImport(comment) { + var implicitImportRegEx = /^(\/\/\/\s*/gim; + var match = implicitImportRegEx.exec(comment); + if(match) { + return true; + } + return false; + } + TypeScript.getImplicitImport = getImplicitImport; + function getStyleSettings(comment, styleSettings) { + var styleRegEx = /^(\/\/\/\s*/gim; + var settings = styleRegEx.exec(comment); + if(settings) { + var settingsRegEx = /^([a-zA-Z]+=['"]on['|"])/gim; + settings = settingsRegEx.exec(settings[2]); + if(settings) { + for(var i = 0; i < settings.length; i++) { + var setting = (settings[i]).split("="); + var on = "\"on\""; + switch(setting[0]) { + case "blockInCompoundStmt": + styleSettings.blockInCompoundStmt = setting[1] == on; + break; + case "eqeqeq": + styleSettings.eqeqeq = setting[1] == on; + break; + case "forin": + styleSettings.forin = setting[1] == on; + break; + case "emptyBlocks": + styleSettings.emptyBlocks = setting[1] == on; + break; + case "newMustBeUsed": + styleSettings.newMustBeUsed = setting[1] == on; + break; + case "requireSemi": + styleSettings.requireSemi = setting[1] == on; + break; + case "assignmentInCond": + styleSettings.assignmentInCond = setting[1] == on; + break; + case "eqnull": + styleSettings.eqnull = setting[1] == on; + break; + case "evalOK": + styleSettings.evalOK = setting[1] == on; + break; + case "innerScopeDeclEscape": + styleSettings.innerScopeDeclEscape = setting[1] == on; + break; + case "funcInLoop": + styleSettings.funcInLoop = setting[1] == on; + break; + case "reDeclareLocal": + styleSettings.reDeclareLocal = setting[1] == on; + break; + case "literalSubscript": + styleSettings.literalSubscript = setting[1] == on; + break; + case "implicitAny": + styleSettings.implicitAny = setting[1] == on; + break; + } + } + } + } + } + TypeScript.getStyleSettings = getStyleSettings; + function getReferencedFiles(sourceText) { + var preProcessInfo = preProcessFile(sourceText, null, false); + return preProcessInfo.referencedFiles; + } + TypeScript.getReferencedFiles = getReferencedFiles; + function preProcessFile(sourceText, options, readImportFiles) { + if (typeof options === "undefined") { options = new CompilationSettings(); } + if (typeof readImportFiles === "undefined") { readImportFiles = true; } + var scanner = new TypeScript.Scanner(); + scanner.resetComments(); + scanner.setSourceText(sourceText, TypeScript.LexMode.File); + var tok = scanner.scan(); + var comments = []; + var comment = null; + var leftCurlies = []; + var settings = options; + var referencedFiles = []; + var importedFiles = []; + var isLibFile = false; + while(tok.tokenId != TypeScript.TokenID.EndOfFile) { + if(readImportFiles && tok.tokenId == TypeScript.TokenID.Import) { + tok = scanner.scan(); + if(tok.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToID(tok, false)) { + tok = scanner.scan(); + if(tok.tokenId == TypeScript.TokenID.Equals) { + tok = scanner.scan(); + if(tok.tokenId == TypeScript.TokenID.Module) { + tok = scanner.scan(); + if(tok.tokenId == TypeScript.TokenID.OpenParen) { + tok = scanner.scan(); + if(tok.tokenId == TypeScript.TokenID.StringLiteral) { + var ref = { + minChar: scanner.startPos, + limChar: scanner.pos, + startLine: scanner.line, + startCol: scanner.col, + path: TypeScript.stripQuotes(TypeScript.switchToForwardSlashes(tok.getText())), + isResident: false + }; + importedFiles.push(ref); + } + } + } + } + } + } + if(tok.tokenId == TypeScript.TokenID.OpenBrace) { + leftCurlies.push(tok); + } + if(tok.tokenId == TypeScript.TokenID.CloseBrace) { + leftCurlies.pop(); + } + tok = scanner.scan(); + } + comments = scanner.getComments(); + for(var iComment = 0; iComment < comments.length; iComment++) { + comment = comments[iComment]; + if(!comment.isBlock) { + var referencedCode = getFileReferenceFromReferencePath(comment.getText()); + if(referencedCode) { + referencedCode.minChar = comment.startPos; + referencedCode.limChar = referencedCode.minChar + comment.value.length; + var result = { + line: -1, + col: -1 + }; + TypeScript.getSourceLineColFromMap(result, comment.startPos, scanner.lineMap); + if(result.col >= 0) { + result.col++; + } + referencedCode.startLine = result.line; + referencedCode.startCol = result.col; + referencedFiles.push(referencedCode); + } + if(settings) { + getStyleSettings(comment.getText(), settings.styleSettings); + var isNoLibRegex = /^(\/\/\/\s*/gim; + var isNoLibMatch = isNoLibRegex.exec(comment.getText()); + if(isNoLibMatch) { + isLibFile = (isNoLibMatch[3] == "true"); + } + } + } + } + return { + settings: settings, + referencedFiles: referencedFiles, + importedFiles: importedFiles, + isLibFile: isLibFile + }; + } + TypeScript.preProcessFile = preProcessFile; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var IncrementalParser = (function () { + function IncrementalParser(logger) { + this.logger = logger; + this.astLogger = new TypeScript.AstLogger(this.logger); + } + IncrementalParser.prototype.getEnclosingScopeContextIfSingleScopeEdit = function (previousScript, scriptId, newSourceText, editRange) { + this.logger.log("checkEditsInsideSingleScope(\"" + scriptId + "\")"); + if(editRange === null) { + throw new Error("editRange should be valid"); + } + if(editRange.isUnknown()) { + this.logger.log(" Bailing out because edit range is unknown"); + return null; + } + var scope1 = TypeScript.findEnclosingScopeAt(this.logger, previousScript, newSourceText, editRange.minChar, false); + var scope2 = TypeScript.findEnclosingScopeAt(this.logger, previousScript, newSourceText, editRange.limChar, false); + if(scope1 == null || scope2 == null) { + this.logger.log(" Bailing out because containing scopes cannot be determined"); + return null; + } + if(scope1.scopeStartAST !== scope2.scopeStartAST) { + this.logger.log(" Bailing out because edit overlaps 2 disctint scopes"); + return null; + } + var newScopeLength = scope1.scopeStartAST.limChar - scope1.scopeStartAST.minChar + editRange.delta; + if(newScopeLength <= 0) { + this.logger.log(" Bailing out because scope has been entirely removed from new source text"); + return null; + } + return scope1; + }; + IncrementalParser.prototype.attemptIncrementalUpdateUnit = function (previousScript, scriptId, newSourceText, editRange) { + this.logger.log("attemptIncrementalUpdateUnit(\"" + scriptId + "\")"); + if(editRange === null) { + throw new Error("editRange should be valid"); + } + var scope1 = this.getEnclosingScopeContextIfSingleScopeEdit(previousScript, scriptId, newSourceText, editRange); + if(scope1 === null) { + return null; + } + var newScopeLength = scope1.scopeStartAST.limChar - scope1.scopeStartAST.minChar + editRange.delta; + if(newScopeLength >= newSourceText.getLength() / 2) { + this.logger.log(" Bailing out because range of scope to reparse (" + newScopeLength + " characters) is greater than half the size of the source text"); + return null; + } + var parseErrors = []; + var errorCapture = function (minChar, charLen, message, unitIndex) { + parseErrors.push(new TypeScript.ErrorEntry(unitIndex, minChar, minChar + charLen, message)); + }; + var quickParseResult = TypeScript.quickParse(this.logger, scope1.scopeStartAST, newSourceText, scope1.scopeStartAST.minChar, scope1.scopeStartAST.minChar + newScopeLength, errorCapture); + if(quickParseResult.endLexState != TypeScript.LexState.Start) { + this.logger.log(" Bailing out because scope contains unterminated comment"); + return null; + } + var scriptFragment = quickParseResult.Script; + if(scriptFragment.vars.members.length !== 0) { + this.logger.log(" Bailing out because new source text defines variables"); + return null; + } + if(scriptFragment.bod.members.length !== 1) { + this.logger.log(" Bailing out because new source text defines more than one scope (or none)"); + return null; + } + var oldScope = scope1.scopeStartAST; + var newScope = scriptFragment.bod.members[0]; + if(oldScope.nodeType != newScope.nodeType) { + this.logger.log(" Bailing out because new source text does not define the same scope type as the existing scope"); + return null; + } + if(!(oldScope).leftCurlyCount || !(oldScope).rightCurlyCount) { + this.logger.log(" Bailing out because sopce doesn't have left/right curly count"); + return null; + } + if((oldScope).leftCurlyCount !== (newScope).leftCurlyCount) { + this.logger.log(" Bailing out because new source text contains more (or fewer) left curly braces"); + return null; + } + if((oldScope).rightCurlyCount !== (newScope).rightCurlyCount) { + this.logger.log(" Bailing out because new source text contains more (or fewer) right curly braces"); + return null; + } + if(newScope.minChar !== 0) { + this.logger.log(" Bailing out because new function declaration does not start at position 0"); + return null; + } + if(newScope.limChar !== newScopeLength) { + this.logger.log(" Bailing out because new function declaration does not end at the new end position"); + return null; + } + return TypeScript.UpdateUnitResult.singleScopeEdits(previousScript, scriptFragment, oldScope, newScope, editRange, parseErrors); + }; + IncrementalParser.prototype.mergeTrees = function (updateResult) { + var _this = this; + TypeScript.timeFunction(this.logger, "mergeTrees()", function () { + var editRange = new TypeScript.ScriptEditRange(updateResult.scope1.minChar, updateResult.scope1.limChar, updateResult.editRange.delta); + _this.applyDeltaPosition(updateResult.script1, editRange.limChar, editRange.delta); + _this.applyDeltaPosition(updateResult.script2, 0, editRange.minChar); + _this.mergeLocationInfo(updateResult.script1, updateResult.script2, editRange); + _this.replaceAST(updateResult.script1, updateResult.scope1, updateResult.scope2); + }); + }; + IncrementalParser.prototype.replaceAST = function (script, oldAst, newAst) { + var _this = this; + var pre = function (cur, parent, walker) { + if(cur === oldAst) { + newAst.preComments = cur.preComments; + newAst.postComments = cur.postComments; + _this.logger.log("replaced old AST node with new one in script AST"); + walker.options.stopWalk(); + return newAst; + } + if(TypeScript.isValidAstNode(cur)) { + if(cur.limChar < oldAst.minChar || cur.minChar > oldAst.limChar) { + walker.options.goChildren = false; + } + } + return cur; + }; + TypeScript.getAstWalkerFactory().walk(script, pre); + }; + IncrementalParser.prototype.mergeLocationInfo = function (script, partial, editRange) { + var lineMap1 = script.locationInfo.lineMap; + var lineMap2 = partial.locationInfo.lineMap; + if(this.logger.information()) { + this.logger.log("lineMap1 (before):"); + this.astLogger.logLinemap(lineMap1); + this.logger.log("lineMap2 (quick parse):"); + this.astLogger.logLinemap(lineMap2); + this.logger.log("EditRange=" + editRange); + } + var i1 = 2; + var i2 = 2; + var len1 = lineMap1.length; + var len2 = lineMap2.length; + while(i1 < len1) { + if(lineMap1[i1] <= editRange.minChar) { + i1++; + } else if(lineMap1[i1] >= editRange.limChar) { + lineMap1[i1] += editRange.delta; + i1++; + } else { + if(i2 < len2) { + lineMap1.splice(i1, 0, lineMap2[i2] + editRange.minChar); + i1++; + len1++; + i2++; + } else { + lineMap1.splice(i1, 1); + len1--; + } + } + } + if(i2 < len2) { + if(lineMap1[len1 - 1] >= (lineMap2[i2] + editRange.minChar)) { + i1 = 2; + while(i1 < len1 && i2 < len2) { + if(lineMap1[i1] < (lineMap2[i2] + editRange.minChar)) { + i1++; + } else { + lineMap1.splice(i1, 0, lineMap2[i2] + editRange.minChar); + i1++; + len1++; + i2++; + } + } + } + for(; i2 < len2; i2++) { + lineMap1.push(lineMap2[i2] + editRange.minChar); + } + } + if(this.logger.information()) { + this.logger.log("lineMap1 (after merge):"); + this.astLogger.logLinemap(lineMap1); + } + }; + IncrementalParser.prototype.applyDeltaPosition = function (ast, start, delta) { + var applyDelta = function (ast) { + if(ast.minChar !== -1 && ast.minChar >= start) { + ast.minChar += delta; + } + if(ast.limChar !== -1 && ast.limChar >= start) { + ast.limChar += delta; + } + }; + var applyDeltaToComments = function (comments) { + if(comments && comments.length > 0) { + for(var i = 0; i < comments.length; i++) { + applyDelta(comments[i]); + } + } + }; + var pre = function (cur, parent, walker) { + if(cur.limChar !== -1 && cur.limChar < start) { + walker.options.goChildren = false; + } + applyDelta(cur); + applyDeltaToComments(cur.preComments); + applyDeltaToComments(cur.postComments); + return cur; + }; + TypeScript.getAstWalkerFactory().walk(ast, pre); + }; + return IncrementalParser; + })(); + TypeScript.IncrementalParser = IncrementalParser; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var DeclFileWriter = (function () { + function DeclFileWriter(declFile) { + this.declFile = declFile; + this.onNewLine = true; + } + DeclFileWriter.prototype.Write = function (s) { + this.declFile.Write(s); + this.onNewLine = false; + }; + DeclFileWriter.prototype.WriteLine = function (s) { + this.declFile.WriteLine(s); + this.onNewLine = true; + }; + DeclFileWriter.prototype.Close = function () { + this.declFile.Close(); + }; + return DeclFileWriter; + })(); + TypeScript.DeclFileWriter = DeclFileWriter; + var DeclarationEmitter = (function () { + function DeclarationEmitter(checker, emitOptions, errorReporter) { + this.checker = checker; + this.emitOptions = emitOptions; + this.errorReporter = errorReporter; + this.declFile = null; + this.indenter = new TypeScript.Indenter(); + this.declarationContainerStack = []; + this.isDottedModuleName = []; + this.ignoreCallbackAst = null; + this.singleDeclFile = null; + this.varListCount = 0; + } + DeclarationEmitter.prototype.getAstDeclarationContainer = function () { + return this.declarationContainerStack[this.declarationContainerStack.length - 1]; + }; + DeclarationEmitter.prototype.emitDottedModuleName = function () { + return (this.isDottedModuleName.length == 0) ? false : this.isDottedModuleName[this.isDottedModuleName.length - 1]; + }; + DeclarationEmitter.prototype.setDeclarationFile = function (file) { + this.declFile = new DeclFileWriter(file); + }; + DeclarationEmitter.prototype.Close = function () { + try { + this.declFile.Close(); + } catch (ex) { + this.errorReporter.emitterError(null, ex.message); + } + }; + DeclarationEmitter.prototype.emitDeclarations = function (script) { + TypeScript.AstWalkerWithDetailCallback.walk(script, this); + }; + DeclarationEmitter.prototype.getIndentString = function (declIndent) { + if (typeof declIndent === "undefined") { declIndent = false; } + if(this.emitOptions.minWhitespace) { + return ""; + } else { + return this.indenter.getIndent(); + } + }; + DeclarationEmitter.prototype.emitIndent = function () { + this.declFile.Write(this.getIndentString()); + }; + DeclarationEmitter.prototype.canEmitSignature = function (declFlags, canEmitGlobalAmbientDecl, useDeclarationContainerTop) { + if (typeof canEmitGlobalAmbientDecl === "undefined") { canEmitGlobalAmbientDecl = true; } + if (typeof useDeclarationContainerTop === "undefined") { useDeclarationContainerTop = true; } + var container; + if(useDeclarationContainerTop) { + container = this.getAstDeclarationContainer(); + } else { + container = this.declarationContainerStack[this.declarationContainerStack.length - 2]; + } + if(container.nodeType == TypeScript.NodeType.ModuleDeclaration && !TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Exported)) { + return false; + } + if(!canEmitGlobalAmbientDecl && container.nodeType == TypeScript.NodeType.Script && TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Ambient)) { + return false; + } + return true; + }; + DeclarationEmitter.prototype.canEmitPrePostAstSignature = function (declFlags, astWithPrePostCallback, preCallback) { + if(this.ignoreCallbackAst) { + TypeScript.CompilerDiagnostics.assert(this.ignoreCallbackAst != astWithPrePostCallback, "Ignore Callback AST mismatch"); + this.ignoreCallbackAst = null; + return false; + } else if(preCallback && !this.canEmitSignature(declFlags, true, preCallback)) { + this.ignoreCallbackAst = astWithPrePostCallback; + return false; + } + return true; + }; + DeclarationEmitter.prototype.getDeclFlagsString = function (declFlags, typeString) { + var result = this.getIndentString(); + var accessorString = ""; + if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.GetAccessor)) { + accessorString = "get "; + } else if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.SetAccessor)) { + accessorString = "set "; + } + var container = this.getAstDeclarationContainer(); + if(container.nodeType == TypeScript.NodeType.ModuleDeclaration && TypeScript.hasFlag((container).modFlags, TypeScript.ModuleFlags.IsWholeFile) && TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Exported)) { + result += "export "; + } + if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.LocalStatic) || TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Static)) { + if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Private)) { + result += "private "; + } + result += "static " + accessorString; + } else { + if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Private)) { + result += "private " + accessorString; + } else if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Public)) { + result += "public " + accessorString; + } else { + if(accessorString == "") { + result += typeString + " "; + } else { + result += accessorString; + } + } + } + return result; + }; + DeclarationEmitter.prototype.emitDeclFlags = function (declFlags, typeString) { + this.declFile.Write(this.getDeclFlagsString(declFlags, typeString)); + }; + DeclarationEmitter.prototype.canEmitTypeAnnotationSignature = function (declFlag) { + if (typeof declFlag === "undefined") { declFlag = TypeScript.DeclFlags.None; } + return !TypeScript.hasFlag(declFlag, TypeScript.DeclFlags.Private); + }; + DeclarationEmitter.prototype.pushDeclarationContainer = function (ast) { + this.declarationContainerStack.push(ast); + }; + DeclarationEmitter.prototype.popDeclarationContainer = function (ast) { + TypeScript.CompilerDiagnostics.assert(ast != this.getAstDeclarationContainer(), 'Declaration container mismatch'); + this.declarationContainerStack.pop(); + }; + DeclarationEmitter.prototype.emitTypeNamesMember = function (memberName, emitIndent) { + if (typeof emitIndent === "undefined") { emitIndent = false; } + if(memberName.prefix == "{ ") { + if(emitIndent) { + this.emitIndent(); + } + this.declFile.WriteLine("{"); + this.indenter.increaseIndent(); + emitIndent = true; + } else if(memberName.prefix != "") { + if(emitIndent) { + this.emitIndent(); + } + this.declFile.Write(memberName.prefix); + emitIndent = false; + } + if(memberName.isString()) { + if(emitIndent) { + this.emitIndent(); + } + this.declFile.Write((memberName).text); + } else { + var ar = memberName; + for(var index = 0; index < ar.entries.length; index++) { + this.emitTypeNamesMember(ar.entries[index], emitIndent); + if(ar.delim == "; ") { + this.declFile.WriteLine(";"); + } + } + } + if(memberName.suffix == "}") { + this.indenter.decreaseIndent(); + this.emitIndent(); + this.declFile.Write(memberName.suffix); + } else { + this.declFile.Write(memberName.suffix); + } + }; + DeclarationEmitter.prototype.emitTypeSignature = function (type) { + var containingScope = null; + var declarationContainerAst = this.getAstDeclarationContainer(); + switch(declarationContainerAst.nodeType) { + case TypeScript.NodeType.ModuleDeclaration: + case TypeScript.NodeType.InterfaceDeclaration: + case TypeScript.NodeType.FuncDecl: + if(declarationContainerAst.type) { + containingScope = declarationContainerAst.type.containedScope; + } + break; + case TypeScript.NodeType.Script: + var script = declarationContainerAst; + if(script.bod) { + containingScope = script.bod.enclosingScope; + } + break; + case TypeScript.NodeType.ClassDeclaration: + if(declarationContainerAst.type) { + containingScope = declarationContainerAst.type.instanceType.containedScope; + } + break; + default: + TypeScript.CompilerDiagnostics.debugPrint("Unknown containing scope"); + } + var typeNameMembers = type.getScopedTypeNameEx(containingScope); + this.emitTypeNamesMember(typeNameMembers); + }; + DeclarationEmitter.prototype.emitComment = function (comment) { + var text = comment.getText(); + if(this.declFile.onNewLine) { + this.emitIndent(); + } else if(!comment.isBlockComment) { + this.declFile.WriteLine(""); + this.emitIndent(); + } + this.declFile.Write(text[0]); + for(var i = 1; i < text.length; i++) { + this.declFile.WriteLine(""); + this.emitIndent(); + this.declFile.Write(text[i]); + } + if(comment.endsLine || !comment.isBlockComment) { + this.declFile.WriteLine(""); + } else { + this.declFile.Write(" "); + } + }; + DeclarationEmitter.prototype.emitDeclarationComments = function (astOrSymbol, endLine) { + if (typeof endLine === "undefined") { endLine = true; } + if(!this.emitOptions.emitComments) { + return; + } + var declComments = astOrSymbol.getDocComments(); + if(declComments.length > 0) { + for(var i = 0; i < declComments.length; i++) { + this.emitComment(declComments[i]); + } + if(endLine) { + if(!this.declFile.onNewLine) { + this.declFile.WriteLine(""); + } + } else { + if(this.declFile.onNewLine) { + this.emitIndent(); + } + } + } + }; + DeclarationEmitter.prototype.VarDeclCallback = function (pre, varDecl) { + if(pre && this.canEmitSignature(TypeScript.ToDeclFlags(varDecl.varFlags), false)) { + var interfaceMember = (this.getAstDeclarationContainer().nodeType == TypeScript.NodeType.InterfaceDeclaration); + this.emitDeclarationComments(varDecl); + if(!interfaceMember) { + if(this.varListCount >= 0) { + this.emitDeclFlags(TypeScript.ToDeclFlags(varDecl.varFlags), "var"); + this.varListCount = -this.varListCount; + } + this.declFile.Write(varDecl.id.text); + } else { + this.emitIndent(); + this.declFile.Write(varDecl.id.text); + if(TypeScript.hasFlag(varDecl.id.flags, TypeScript.ASTFlags.OptionalName)) { + this.declFile.Write("?"); + } + } + var type = null; + if(varDecl.typeExpr && varDecl.typeExpr.type) { + type = varDecl.typeExpr.type; + } else if(varDecl.sym) { + type = (varDecl.sym).getType(); + if(type == this.checker.anyType) { + type = null; + } + } + if(type && this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(varDecl.varFlags))) { + this.declFile.Write(": "); + this.emitTypeSignature(type); + } + if(this.varListCount > 0) { + this.varListCount--; + } else if(this.varListCount < 0) { + this.varListCount++; + } + if(this.varListCount < 0) { + this.declFile.Write(", "); + } else { + this.declFile.WriteLine(";"); + } + } + return false; + }; + DeclarationEmitter.prototype.BlockCallback = function (pre, block) { + if(!block.isStatementBlock) { + if(pre) { + this.varListCount = block.statements.members.length; + } else { + this.varListCount = 0; + } + return true; + } + return false; + }; + DeclarationEmitter.prototype.emitArgDecl = function (argDecl, funcDecl) { + this.emitDeclarationComments(argDecl, false); + this.declFile.Write(argDecl.id.text); + if(argDecl.isOptionalArg()) { + this.declFile.Write("?"); + } + if((argDecl.typeExpr || argDecl.type != this.checker.anyType) && this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(funcDecl.fncFlags))) { + this.declFile.Write(": "); + this.emitTypeSignature(argDecl.type); + } + }; + DeclarationEmitter.prototype.FuncDeclCallback = function (pre, funcDecl) { + if(!pre) { + return false; + } + if(funcDecl.isAccessor()) { + return this.emitPropertyAccessorSignature(funcDecl); + } + var isInterfaceMember = (this.getAstDeclarationContainer().nodeType == TypeScript.NodeType.InterfaceDeclaration); + if(funcDecl.bod) { + if(funcDecl.isConstructor) { + if(funcDecl.type.construct && funcDecl.type.construct.signatures.length > 1) { + return false; + } + } else { + if(funcDecl.type.call && funcDecl.type.call.signatures.length > 1) { + return false; + } + } + } else if(!isInterfaceMember && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Private) && funcDecl.type.call && funcDecl.type.call.signatures.length > 1) { + var signatures = funcDecl.type.call.signatures; + var firstSignature = signatures[0].declAST; + if(firstSignature.bod) { + firstSignature = signatures[1].declAST; + } + if(firstSignature != funcDecl) { + return false; + } + } + if(!this.canEmitSignature(TypeScript.ToDeclFlags(funcDecl.fncFlags), false)) { + return false; + } + this.emitDeclarationComments(funcDecl); + if(funcDecl.isConstructor) { + this.emitIndent(); + this.declFile.Write("constructor"); + } else { + var id = funcDecl.getNameText(); + if(!isInterfaceMember) { + this.emitDeclFlags(TypeScript.ToDeclFlags(funcDecl.fncFlags), "function"); + if(id != "__missing" || !funcDecl.name || !funcDecl.name.isMissing()) { + this.declFile.Write(id); + } else if(funcDecl.isConstructMember()) { + this.declFile.Write("new"); + } + } else { + this.emitIndent(); + if(funcDecl.isConstructMember()) { + this.declFile.Write("new"); + } else if(!funcDecl.isCallMember() && !funcDecl.isIndexerMember()) { + this.declFile.Write(id); + if(TypeScript.hasFlag(funcDecl.name.flags, TypeScript.ASTFlags.OptionalName)) { + this.declFile.Write("? "); + } + } + } + } + if(!funcDecl.isIndexerMember()) { + this.declFile.Write("("); + } else { + this.declFile.Write("["); + } + this.indenter.increaseIndent(); + if(funcDecl.arguments) { + var argsLen = funcDecl.arguments.members.length; + if(funcDecl.variableArgList) { + argsLen--; + } + for(var i = 0; i < argsLen; i++) { + var argDecl = funcDecl.arguments.members[i]; + this.emitArgDecl(argDecl, funcDecl); + if(i < (argsLen - 1)) { + this.declFile.Write(", "); + } + } + } + if(funcDecl.variableArgList) { + var lastArg = funcDecl.arguments.members[funcDecl.arguments.members.length - 1]; + if(funcDecl.arguments.members.length > 1) { + this.declFile.Write(", ..."); + } else { + this.declFile.Write("..."); + } + this.emitArgDecl(lastArg, funcDecl); + } + this.indenter.decreaseIndent(); + if(!funcDecl.isIndexerMember()) { + this.declFile.Write(")"); + } else { + this.declFile.Write("]"); + } + if(!funcDecl.isConstructor && (funcDecl.returnTypeAnnotation || funcDecl.signature.returnType.type != this.checker.anyType) && this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(funcDecl.fncFlags))) { + this.declFile.Write(": "); + this.emitTypeSignature(funcDecl.signature.returnType.type); + } + this.declFile.WriteLine(";"); + return false; + }; + DeclarationEmitter.prototype.emitBaseList = function (bases, qual) { + if(bases && (bases.members.length > 0)) { + this.declFile.Write(" " + qual + " "); + var basesLen = bases.members.length; + for(var i = 0; i < basesLen; i++) { + var baseExpr = bases.members[i]; + var baseSymbol = baseExpr.type.symbol; + var baseType = baseExpr.type; + if(i > 0) { + this.declFile.Write(", "); + } + this.emitTypeSignature(baseType); + } + } + }; + DeclarationEmitter.prototype.emitPropertyAccessorSignature = function (funcDecl) { + var accessorSymbol = funcDecl.accessorSymbol; + if(accessorSymbol.getter && accessorSymbol.getter.declAST != funcDecl) { + return false; + } + this.emitDeclarationComments(accessorSymbol); + this.emitDeclFlags(TypeScript.ToDeclFlags(accessorSymbol.flags), "var"); + this.declFile.Write(funcDecl.name.text); + var propertyType = accessorSymbol.getType(); + if(this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(accessorSymbol.flags))) { + this.declFile.Write(" : "); + this.emitTypeSignature(propertyType); + } + this.declFile.WriteLine(";"); + return false; + }; + DeclarationEmitter.prototype.emitClassMembersFromConstructorDefinition = function (funcDecl) { + if(funcDecl.arguments) { + var argsLen = funcDecl.arguments.members.length; + if(funcDecl.variableArgList) { + argsLen--; + } + for(var i = 0; i < argsLen; i++) { + var argDecl = funcDecl.arguments.members[i]; + if(TypeScript.hasFlag(argDecl.varFlags, TypeScript.VarFlags.Property)) { + this.emitDeclarationComments(argDecl); + this.emitDeclFlags(TypeScript.ToDeclFlags(argDecl.varFlags), "var"); + this.declFile.Write(argDecl.id.text); + if(argDecl.typeExpr && this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(argDecl.varFlags))) { + this.declFile.Write(": "); + this.emitTypeSignature(argDecl.type); + } + this.declFile.WriteLine(";"); + } + } + } + }; + DeclarationEmitter.prototype.ClassDeclarationCallback = function (pre, classDecl) { + if(!this.canEmitPrePostAstSignature(TypeScript.ToDeclFlags(classDecl.varFlags), classDecl, pre)) { + return false; + } + if(pre) { + var className = classDecl.name.text; + this.emitDeclarationComments(classDecl); + this.emitDeclFlags(TypeScript.ToDeclFlags(classDecl.varFlags), "class"); + this.declFile.Write(className); + this.emitBaseList(classDecl.extendsList, "extends"); + this.emitBaseList(classDecl.implementsList, "implements"); + this.declFile.WriteLine(" {"); + this.pushDeclarationContainer(classDecl); + this.indenter.increaseIndent(); + if(classDecl.constructorDecl) { + this.emitClassMembersFromConstructorDefinition(classDecl.constructorDecl); + } + } else { + this.indenter.decreaseIndent(); + this.popDeclarationContainer(classDecl); + this.emitIndent(); + this.declFile.WriteLine("}"); + } + return true; + }; + DeclarationEmitter.prototype.InterfaceDeclarationCallback = function (pre, interfaceDecl) { + if(!this.canEmitPrePostAstSignature(TypeScript.ToDeclFlags(interfaceDecl.varFlags), interfaceDecl, pre)) { + return false; + } + if(pre) { + var interfaceName = interfaceDecl.name.text; + this.emitDeclarationComments(interfaceDecl); + this.emitDeclFlags(TypeScript.ToDeclFlags(interfaceDecl.varFlags), "interface"); + this.declFile.Write(interfaceName); + this.emitBaseList(interfaceDecl.extendsList, "extends"); + this.declFile.WriteLine(" {"); + this.indenter.increaseIndent(); + this.pushDeclarationContainer(interfaceDecl); + } else { + this.indenter.decreaseIndent(); + this.popDeclarationContainer(interfaceDecl); + this.emitIndent(); + this.declFile.WriteLine("}"); + } + return true; + }; + DeclarationEmitter.prototype.ImportDeclarationCallback = function (pre, importDecl) { + if(pre) { + if((this.declarationContainerStack[0]).isExternallyVisibleSymbol(importDecl.id.sym)) { + this.emitDeclarationComments(importDecl); + this.emitIndent(); + this.declFile.Write("import "); + this.declFile.Write(importDecl.id.text + " = "); + if(importDecl.isDynamicImport) { + this.declFile.WriteLine("module (" + importDecl.getAliasName() + ");"); + } else { + this.declFile.WriteLine(importDecl.getAliasName() + ";"); + } + } + } + return false; + }; + DeclarationEmitter.prototype.emitEnumSignature = function (moduleDecl) { + if(!this.canEmitSignature(TypeScript.ToDeclFlags(moduleDecl.modFlags))) { + return false; + } + this.emitDeclarationComments(moduleDecl); + this.emitDeclFlags(TypeScript.ToDeclFlags(moduleDecl.modFlags), "enum"); + this.declFile.WriteLine(moduleDecl.name.text + " {"); + this.indenter.increaseIndent(); + var membersLen = moduleDecl.members.members.length; + for(var j = 1; j < membersLen; j++) { + var memberDecl = moduleDecl.members.members[j]; + if(memberDecl.nodeType == TypeScript.NodeType.VarDecl) { + this.emitDeclarationComments(memberDecl); + this.emitIndent(); + this.declFile.WriteLine((memberDecl).id.text + ","); + } else { + TypeScript.CompilerDiagnostics.assert(memberDecl.nodeType != TypeScript.NodeType.Asg, "We want to catch this"); + } + } + this.indenter.decreaseIndent(); + this.emitIndent(); + this.declFile.WriteLine("}"); + return false; + }; + DeclarationEmitter.prototype.ModuleDeclarationCallback = function (pre, moduleDecl) { + if(TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsWholeFile)) { + if(TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsDynamic)) { + if(pre) { + if(!this.emitOptions.outputMany) { + this.singleDeclFile = this.declFile; + TypeScript.CompilerDiagnostics.assert(this.indenter.indentAmt == 0, "Indent has to be 0 when outputing new file"); + var declareFileName = this.emitOptions.mapOutputFileName(TypeScript.stripQuotes(moduleDecl.name.sym.name), TypeScript.TypeScriptCompiler.mapToDTSFileName); + var useUTF8InOutputfile = moduleDecl.containsUnicodeChar || (this.emitOptions.emitComments && moduleDecl.containsUnicodeCharInComment); + try { + this.declFile = new DeclFileWriter(this.emitOptions.ioHost.createFile(declareFileName, useUTF8InOutputfile)); + } catch (ex) { + this.errorReporter.emitterError(null, ex.message); + } + } + this.pushDeclarationContainer(moduleDecl); + } else { + if(!this.emitOptions.outputMany) { + TypeScript.CompilerDiagnostics.assert(this.singleDeclFile != this.declFile, "singleDeclFile cannot be null as we are going to revert back to it"); + TypeScript.CompilerDiagnostics.assert(this.indenter.indentAmt == 0, "Indent has to be 0 when outputing new file"); + try { + this.declFile.Close(); + } catch (ex) { + this.errorReporter.emitterError(null, ex.message); + } + this.declFile = this.singleDeclFile; + } + this.popDeclarationContainer(moduleDecl); + } + } + return true; + } + if(moduleDecl.isEnum()) { + if(pre) { + this.emitEnumSignature(moduleDecl); + } + return false; + } + if(!this.canEmitPrePostAstSignature(TypeScript.ToDeclFlags(moduleDecl.modFlags), moduleDecl, pre)) { + return false; + } + if(pre) { + if(this.emitDottedModuleName()) { + this.dottedModuleEmit += "."; + } else { + this.dottedModuleEmit = this.getDeclFlagsString(TypeScript.ToDeclFlags(moduleDecl.modFlags), "module"); + } + this.dottedModuleEmit += moduleDecl.name.text; + var isCurrentModuleDotted = (moduleDecl.members.members.length == 1 && moduleDecl.members.members[0].nodeType == TypeScript.NodeType.ModuleDeclaration && !(moduleDecl.members.members[0]).isEnum() && TypeScript.hasFlag((moduleDecl.members.members[0]).modFlags, TypeScript.ModuleFlags.Exported)); + var moduleDeclComments = moduleDecl.getDocComments(); + isCurrentModuleDotted = isCurrentModuleDotted && (moduleDeclComments == null || moduleDeclComments.length == 0); + this.isDottedModuleName.push(isCurrentModuleDotted); + this.pushDeclarationContainer(moduleDecl); + if(!isCurrentModuleDotted) { + this.emitDeclarationComments(moduleDecl); + this.declFile.Write(this.dottedModuleEmit); + this.declFile.WriteLine(" {"); + this.indenter.increaseIndent(); + } + } else { + if(!this.emitDottedModuleName()) { + this.indenter.decreaseIndent(); + this.emitIndent(); + this.declFile.WriteLine("}"); + } + this.popDeclarationContainer(moduleDecl); + this.isDottedModuleName.pop(); + } + return true; + }; + DeclarationEmitter.prototype.ScriptCallback = function (pre, script) { + if(pre) { + if(this.emitOptions.outputMany) { + for(var i = 0; i < script.referencedFiles.length; i++) { + var referencePath = script.referencedFiles[i].path; + var declareFileName; + if(TypeScript.isRooted(referencePath)) { + declareFileName = this.emitOptions.mapOutputFileName(referencePath, TypeScript.TypeScriptCompiler.mapToDTSFileName); + } else { + declareFileName = TypeScript.getDeclareFilePath(script.referencedFiles[i].path); + } + this.declFile.WriteLine('/// '); + } + } + this.pushDeclarationContainer(script); + } else { + this.popDeclarationContainer(script); + } + return true; + }; + DeclarationEmitter.prototype.DefaultCallback = function (pre, ast) { + return !TypeScript.hasFlag(ast.flags, TypeScript.ASTFlags.IsStatement); + }; + return DeclarationEmitter; + })(); + TypeScript.DeclarationEmitter = DeclarationEmitter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (UpdateUnitKind) { + UpdateUnitKind._map = []; + UpdateUnitKind._map[0] = "Unknown"; + UpdateUnitKind.Unknown = 0; + UpdateUnitKind._map[1] = "NoEdits"; + UpdateUnitKind.NoEdits = 1; + UpdateUnitKind._map[2] = "EditsInsideSingleScope"; + UpdateUnitKind.EditsInsideSingleScope = 2; + })(TypeScript.UpdateUnitKind || (TypeScript.UpdateUnitKind = {})); + var UpdateUnitKind = TypeScript.UpdateUnitKind; + var ScriptEditRange = (function () { + function ScriptEditRange(minChar, limChar, delta) { + this.minChar = minChar; + this.limChar = limChar; + this.delta = delta; + } + ScriptEditRange.unknown = function unknown() { + return new ScriptEditRange(-1, -1, -1); + }; + ScriptEditRange.prototype.isUnknown = function () { + return this.minChar === -1 && this.limChar === -1 && this.delta === -1; + }; + ScriptEditRange.prototype.containsPosition = function (pos) { + return (this.minChar <= pos && pos < this.limChar) || (this.minChar <= pos && pos < this.limChar + this.delta); + }; + ScriptEditRange.prototype.toString = function () { + return "editRange(minChar=" + this.minChar + ", limChar=" + this.limChar + ", delta=" + this.delta + ")"; + }; + return ScriptEditRange; + })(); + TypeScript.ScriptEditRange = ScriptEditRange; + var UpdateUnitResult = (function () { + function UpdateUnitResult(kind, unitIndex, script1, script2) { + this.kind = kind; + this.unitIndex = unitIndex; + this.script1 = script1; + this.script2 = script2; + this.scope1 = null; + this.scope2 = null; + this.editRange = null; + this.parseErrors = []; + } + UpdateUnitResult.noEdits = function noEdits(unitIndex) { + return new UpdateUnitResult(UpdateUnitKind.NoEdits, unitIndex, null, null); + }; + UpdateUnitResult.unknownEdits = function unknownEdits(script1, script2, parseErrors) { + var result = new UpdateUnitResult(UpdateUnitKind.Unknown, script1.locationInfo.unitIndex, script1, script2); + result.parseErrors = parseErrors; + return result; + }; + UpdateUnitResult.singleScopeEdits = function singleScopeEdits(script1, script2, scope1, scope2, editRange, parseErrors) { + var result = new UpdateUnitResult(UpdateUnitKind.EditsInsideSingleScope, script1.locationInfo.unitIndex, script1, script2); + result.scope1 = scope1; + result.scope2 = scope2; + result.editRange = editRange; + result.parseErrors = parseErrors; + return result; + }; + return UpdateUnitResult; + })(); + TypeScript.UpdateUnitResult = UpdateUnitResult; + var ErrorEntry = (function () { + function ErrorEntry(unitIndex, minChar, limChar, message) { + this.unitIndex = unitIndex; + this.minChar = minChar; + this.limChar = limChar; + this.message = message; + } + return ErrorEntry; + })(); + TypeScript.ErrorEntry = ErrorEntry; + TypeScript.defaultSettings = new TypeScript.CompilationSettings(); + var TypeScriptCompiler = (function () { + function TypeScriptCompiler(errorOutput, logger, settings) { + if (typeof logger === "undefined") { logger = new TypeScript.NullLogger(); } + if (typeof settings === "undefined") { settings = TypeScript.defaultSettings; } + this.errorOutput = errorOutput; + this.logger = logger; + this.settings = settings; + this.parser = new TypeScript.Parser(); + this.typeFlow = null; + this.scripts = new TypeScript.ASTList(); + this.units = new Array(); + this.errorReporter = new TypeScript.ErrorReporter(this.errorOutput); + this.persistentTypeState = new TypeScript.PersistentGlobalTypeState(this.errorReporter); + this.errorReporter.parser = this.parser; + this.initTypeChecker(this.errorOutput); + this.parser.style_requireSemi = this.settings.styleSettings.requireSemi; + this.parser.style_funcInLoop = this.settings.styleSettings.funcInLoop; + this.parser.inferPropertiesFromThisAssignment = this.settings.inferPropertiesFromThisAssignment; + this.emitSettings = new TypeScript.EmitOptions(this.settings); + TypeScript.codeGenTarget = settings.codeGenTarget; + } + TypeScriptCompiler.prototype.timeFunction = function (funcDescription, func) { + return TypeScript.timeFunction(this.logger, funcDescription, func); + }; + TypeScriptCompiler.prototype.initTypeChecker = function (errorOutput) { + this.persistentTypeState.refreshPersistentState(); + this.typeChecker = new TypeScript.TypeChecker(this.persistentTypeState); + this.typeChecker.errorReporter = this.errorReporter; + this.typeChecker.checkControlFlow = this.settings.controlFlow; + this.typeChecker.checkControlFlowUseDef = this.settings.controlFlowUseDef; + this.typeChecker.printControlFlowGraph = this.settings.printControlFlow; + this.typeChecker.errorsOnWith = this.settings.errorOnWith; + this.typeChecker.styleSettings = this.settings.styleSettings; + this.typeChecker.canCallDefinitionSignature = this.settings.canCallDefinitionSignature; + this.errorReporter.checker = this.typeChecker; + this.setErrorOutput(this.errorOutput); + }; + TypeScriptCompiler.prototype.setErrorOutput = function (outerr) { + this.errorOutput = outerr; + this.errorReporter.setErrOut(outerr); + this.parser.outfile = outerr; + }; + TypeScriptCompiler.prototype.emitCommentsToOutput = function () { + this.emitSettings = new TypeScript.EmitOptions(this.settings); + }; + TypeScriptCompiler.prototype.setErrorCallback = function (fn) { + this.parser.errorCallback = fn; + }; + TypeScriptCompiler.prototype.updateUnit = function (prog, filename, setRecovery) { + return this.updateSourceUnit(new TypeScript.StringSourceText(prog), filename, setRecovery); + }; + TypeScriptCompiler.prototype.updateSourceUnit = function (sourceText, filename, setRecovery) { + var _this = this; + return this.timeFunction("updateSourceUnit(" + filename + ")", function () { + var updateResult = _this.partialUpdateUnit(sourceText, filename, setRecovery); + return _this.applyUpdateResult(updateResult); + }); + }; + TypeScriptCompiler.prototype.applyUpdateResult = function (updateResult) { + switch(updateResult.kind) { + case UpdateUnitKind.NoEdits: + return false; + case UpdateUnitKind.Unknown: + this.scripts.members[updateResult.unitIndex] = updateResult.script2; + this.units[updateResult.unitIndex] = updateResult.script2.locationInfo; + for(var i = 0, len = updateResult.parseErrors.length; i < len; i++) { + var e = updateResult.parseErrors[i]; + if(this.parser.errorCallback) { + this.parser.errorCallback(e.minChar, e.limChar - e.minChar, e.message, e.unitIndex); + } + } + return true; + case UpdateUnitKind.EditsInsideSingleScope: + new TypeScript.IncrementalParser(this.logger).mergeTrees(updateResult); + return true; + } + }; + TypeScriptCompiler.prototype.partialUpdateUnit = function (sourceText, filename, setRecovery) { + var _this = this; + return this.timeFunction("partialUpdateUnit(" + filename + ")", function () { + for(var i = 0, len = _this.units.length; i < len; i++) { + if(_this.units[i].filename == filename) { + if((_this.scripts.members[i]).isResident) { + return UpdateUnitResult.noEdits(i); + } + if(setRecovery) { + _this.parser.setErrorRecovery(null); + } + var updateResult; + var parseErrors = []; + var errorCapture = function (minChar, charLen, message, unitIndex) { + parseErrors.push(new ErrorEntry(unitIndex, minChar, minChar + charLen, message)); + }; + var svErrorCallback = _this.parser.errorCallback; + if(svErrorCallback) { + _this.parser.errorCallback = errorCapture; + } + var oldScript = _this.scripts.members[i]; + var newScript = _this.parser.parse(sourceText, filename, i); + if(svErrorCallback) { + _this.parser.errorCallback = svErrorCallback; + } + updateResult = UpdateUnitResult.unknownEdits(oldScript, newScript, parseErrors); + return updateResult; + } + } + throw new Error("Unknown file \"" + filename + "\""); + }); + }; + TypeScriptCompiler.prototype.addUnit = function (prog, filename, keepResident, referencedFiles) { + if (typeof keepResident === "undefined") { keepResident = false; } + if (typeof referencedFiles === "undefined") { referencedFiles = []; } + return this.addSourceUnit(new TypeScript.StringSourceText(prog), filename, keepResident, referencedFiles); + }; + TypeScriptCompiler.prototype.addSourceUnit = function (sourceText, filename, keepResident, referencedFiles) { + if (typeof referencedFiles === "undefined") { referencedFiles = []; } + var _this = this; + return this.timeFunction("addSourceUnit(" + filename + ", " + keepResident + ")", function () { + var script = _this.parser.parse(sourceText, filename, _this.units.length, TypeScript.AllowedElements.Global); + script.referencedFiles = referencedFiles; + script.isResident = keepResident; + _this.persistentTypeState.setCollectionMode(keepResident ? TypeScript.TypeCheckCollectionMode.Resident : TypeScript.TypeCheckCollectionMode.Transient); + var index = _this.units.length; + _this.units[index] = script.locationInfo; + _this.typeChecker.collectTypes(script); + _this.scripts.append(script); + return script; + }); + }; + TypeScriptCompiler.prototype.parseUnit = function (prog, filename) { + return this.parseSourceUnit(new TypeScript.StringSourceText(prog), filename); + }; + TypeScriptCompiler.prototype.parseSourceUnit = function (sourceText, filename) { + this.parser.setErrorRecovery(this.errorOutput); + var script = this.parser.parse(sourceText, filename, 0); + var index = this.units.length; + this.units[index] = script.locationInfo; + this.typeChecker.collectTypes(script); + this.scripts.append(script); + }; + TypeScriptCompiler.prototype.typeCheck = function () { + var _this = this; + return this.timeFunction("typeCheck()", function () { + var binder = new TypeScript.Binder(_this.typeChecker); + _this.typeChecker.units = _this.units; + binder.bind(_this.typeChecker.globalScope, _this.typeChecker.globals); + binder.bind(_this.typeChecker.globalScope, _this.typeChecker.ambientGlobals); + binder.bind(_this.typeChecker.globalScope, _this.typeChecker.globalTypes); + binder.bind(_this.typeChecker.globalScope, _this.typeChecker.ambientGlobalTypes); + _this.typeFlow = new TypeScript.TypeFlow(_this.logger, _this.typeChecker.globalScope, _this.parser, _this.typeChecker); + var i = 0; + var script = null; + var len = _this.scripts.members.length; + _this.persistentTypeState.setCollectionMode(TypeScript.TypeCheckCollectionMode.Resident); + for(i = 0; i < len; i++) { + script = _this.scripts.members[i]; + if(!script.isResident || script.hasBeenTypeChecked) { + continue; + } + _this.typeFlow.assignScopes(script); + _this.typeFlow.initLibs(); + } + for(i = 0; i < len; i++) { + script = _this.scripts.members[i]; + if(!script.isResident || script.hasBeenTypeChecked) { + continue; + } + _this.typeFlow.typeCheck(script); + script.hasBeenTypeChecked = true; + } + _this.persistentTypeState.setCollectionMode(TypeScript.TypeCheckCollectionMode.Transient); + len = _this.scripts.members.length; + for(i = 0; i < len; i++) { + script = _this.scripts.members[i]; + if(script.isResident) { + continue; + } + _this.typeFlow.assignScopes(script); + _this.typeFlow.initLibs(); + } + for(i = 0; i < len; i++) { + script = _this.scripts.members[i]; + if(script.isResident) { + continue; + } + _this.typeFlow.typeCheck(script); + } + return null; + }); + }; + TypeScriptCompiler.prototype.cleanASTTypesForReTypeCheck = function (ast) { + function cleanASTType(ast, parent) { + ast.type = null; + if(ast.nodeType == TypeScript.NodeType.VarDecl) { + var vardecl = ast; + vardecl.sym = null; + } else if(ast.nodeType == TypeScript.NodeType.ArgDecl) { + var argdecl = ast; + argdecl.sym = null; + } else if(ast.nodeType == TypeScript.NodeType.Name) { + var name = ast; + name.sym = null; + } else if(ast.nodeType == TypeScript.NodeType.FuncDecl) { + var funcdecl = ast; + funcdecl.signature = null; + funcdecl.freeVariables = new Array(); + funcdecl.symbols = null; + funcdecl.accessorSymbol = null; + funcdecl.scopeType = null; + } else if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { + var modDecl = ast; + modDecl.mod = null; + } else if(ast.nodeType == TypeScript.NodeType.With) { + (ast).withSym = null; + } else if(ast.nodeType == TypeScript.NodeType.Catch) { + (ast).containedScope = null; + } else if(ast.nodeType === TypeScript.NodeType.Script) { + (ast).externallyVisibleImportedSymbols = []; + } + return ast; + } + TypeScript.getAstWalkerFactory().walk(ast, cleanASTType); + }; + TypeScriptCompiler.prototype.cleanTypesForReTypeCheck = function () { + var _this = this; + return this.timeFunction("cleanTypesForReTypeCheck()", function () { + for(var i = 0, len = _this.scripts.members.length; i < len; i++) { + var script = _this.scripts.members[i]; + if((script).isResident) { + continue; + } + _this.cleanASTTypesForReTypeCheck(script); + _this.typeChecker.collectTypes(script); + } + return null; + }); + }; + TypeScriptCompiler.prototype.attemptIncrementalTypeCheck = function (updateResult) { + return this.timeFunction("attemptIncrementalTypeCheck()", function () { + return false; + }); + }; + TypeScriptCompiler.prototype.reTypeCheck = function () { + var _this = this; + return this.timeFunction("reTypeCheck()", function () { + TypeScript.CompilerDiagnostics.analysisPass++; + _this.initTypeChecker(_this.errorOutput); + _this.persistentTypeState.setCollectionMode(TypeScript.TypeCheckCollectionMode.Transient); + _this.cleanTypesForReTypeCheck(); + return _this.typeCheck(); + }); + }; + TypeScriptCompiler.prototype.isDynamicModuleCompilation = function () { + for(var i = 0, len = this.scripts.members.length; i < len; i++) { + var script = this.scripts.members[i]; + if(!script.isDeclareFile && script.topLevelMod != null) { + return true; + } + } + return false; + }; + TypeScriptCompiler.prototype.updateCommonDirectoryPath = function () { + var commonComponents = []; + var commonComponentsLength = -1; + for(var i = 0, len = this.scripts.members.length; i < len; i++) { + var script = this.scripts.members[i]; + if(script.emitRequired(this.emitSettings)) { + var fileName = script.locationInfo.filename; + var fileComponents = TypeScript.filePathComponents(fileName); + if(commonComponentsLength == -1) { + commonComponents = fileComponents; + commonComponentsLength = commonComponents.length; + } else { + var updatedPath = false; + for(var j = 0; j < commonComponentsLength && j < fileComponents.length; j++) { + if(commonComponents[j] != fileComponents[j]) { + commonComponentsLength = j; + updatedPath = true; + if(j == 0) { + this.errorReporter.emitterError(null, "Cannot find the common subdirectory path for the input files"); + return; + } + break; + } + } + if(!updatedPath && fileComponents.length < commonComponentsLength) { + commonComponentsLength = fileComponents.length; + } + } + } + } + this.emitSettings.commonDirectoryPath = commonComponents.slice(0, commonComponentsLength).join("/") + "/"; + if(this.emitSettings.outputOption.charAt(this.emitSettings.outputOption.length - 1) != "/") { + this.emitSettings.outputOption += "/"; + } + }; + TypeScriptCompiler.prototype.parseEmitOption = function (ioHost) { + this.emitSettings.ioHost = ioHost; + if(this.emitSettings.outputOption == "") { + this.emitSettings.outputMany = true; + this.emitSettings.commonDirectoryPath = ""; + return; + } + this.emitSettings.outputOption = TypeScript.switchToForwardSlashes(this.emitSettings.ioHost.resolvePath(this.emitSettings.outputOption)); + if(this.emitSettings.ioHost.directoryExists(this.emitSettings.outputOption)) { + this.emitSettings.outputMany = true; + } else if(this.emitSettings.ioHost.fileExists(this.emitSettings.outputOption)) { + this.emitSettings.outputMany = false; + } else { + this.emitSettings.outputMany = !TypeScript.isJSFile(this.emitSettings.outputOption); + } + if(this.isDynamicModuleCompilation() && !this.emitSettings.outputMany) { + this.errorReporter.emitterError(null, "Cannot compile dynamic modules when emitting into single file"); + } + if(this.emitSettings.outputMany) { + this.updateCommonDirectoryPath(); + } + }; + TypeScriptCompiler.prototype.useUTF8ForFile = function (script) { + if(this.emitSettings.outputMany) { + return this.outputScriptToUTF8(script); + } else { + return this.outputScriptsToUTF8((this.scripts.members)); + } + }; + TypeScriptCompiler.mapToDTSFileName = function mapToDTSFileName(fileName, wholeFileNameReplaced) { + return TypeScript.getDeclareFilePath(fileName); + }; + TypeScriptCompiler.prototype.canEmitDeclarations = function (script) { + if(!this.settings.generateDeclarationFiles) { + return false; + } + if(!!script && (script.isDeclareFile || script.isResident || script.bod == null)) { + return false; + } + return true; + }; + TypeScriptCompiler.prototype.emitDeclarationsUnit = function (script, reuseEmitter, declarationEmitter) { + if(!this.canEmitDeclarations(script)) { + return null; + } + if(!declarationEmitter) { + var declareFileName = this.emitSettings.mapOutputFileName(script.locationInfo.filename, TypeScriptCompiler.mapToDTSFileName); + var declareFile = this.createFile(declareFileName, this.useUTF8ForFile(script)); + declarationEmitter = new TypeScript.DeclarationEmitter(this.typeChecker, this.emitSettings, this.errorReporter); + declarationEmitter.setDeclarationFile(declareFile); + } + declarationEmitter.emitDeclarations(script); + if(!reuseEmitter) { + declarationEmitter.Close(); + return null; + } else { + return declarationEmitter; + } + }; + TypeScriptCompiler.prototype.emitDeclarations = function () { + if(!this.canEmitDeclarations()) { + return; + } + if(this.errorReporter.hasErrors) { + return; + } + if(this.scripts.members.length == 0) { + return; + } + var declarationEmitter = null; + for(var i = 0, len = this.scripts.members.length; i < len; i++) { + var script = this.scripts.members[i]; + if(this.emitSettings.outputMany || declarationEmitter == null) { + declarationEmitter = this.emitDeclarationsUnit(script, !this.emitSettings.outputMany); + } else { + this.emitDeclarationsUnit(script, true, declarationEmitter); + } + } + if(declarationEmitter) { + declarationEmitter.Close(); + } + }; + TypeScriptCompiler.mapToFileNameExtension = function mapToFileNameExtension(extension, fileName, wholeFileNameReplaced) { + if(wholeFileNameReplaced) { + return fileName; + } else { + var splitFname = fileName.split("."); + splitFname.pop(); + return splitFname.join(".") + extension; + } + }; + TypeScriptCompiler.mapToJSFileName = function mapToJSFileName(fileName, wholeFileNameReplaced) { + return TypeScriptCompiler.mapToFileNameExtension(".js", fileName, wholeFileNameReplaced); + }; + TypeScriptCompiler.prototype.emitUnit = function (script, reuseEmitter, emitter, inputOutputMapper) { + if(!script.emitRequired(this.emitSettings)) { + return null; + } + var fname = script.locationInfo.filename; + if(!emitter) { + var outFname = this.emitSettings.mapOutputFileName(fname, TypeScriptCompiler.mapToJSFileName); + var outFile = this.createFile(outFname, this.useUTF8ForFile(script)); + emitter = new TypeScript.Emitter(this.typeChecker, outFname, outFile, this.emitSettings, this.errorReporter); + if(this.settings.mapSourceFiles) { + emitter.setSourceMappings(new TypeScript.SourceMapper(fname, outFname, outFile, this.createFile(outFname + TypeScript.SourceMapper.MapFileExtension, false), this.errorReporter, this.settings.emitFullSourceMapPath)); + } + if(inputOutputMapper) { + inputOutputMapper(script.locationInfo.unitIndex, outFname); + } + } else if(this.settings.mapSourceFiles) { + emitter.setSourceMappings(new TypeScript.SourceMapper(fname, emitter.emittingFileName, emitter.outfile, emitter.sourceMapper.sourceMapOut, this.errorReporter, this.settings.emitFullSourceMapPath)); + } + this.typeChecker.locationInfo = script.locationInfo; + emitter.emitJavascript(script, TypeScript.TokenID.Comma, false); + if(!reuseEmitter) { + emitter.Close(); + return null; + } else { + return emitter; + } + }; + TypeScriptCompiler.prototype.emit = function (ioHost, inputOutputMapper) { + this.parseEmitOption(ioHost); + var emitter = null; + for(var i = 0, len = this.scripts.members.length; i < len; i++) { + var script = this.scripts.members[i]; + if(this.emitSettings.outputMany || emitter == null) { + emitter = this.emitUnit(script, !this.emitSettings.outputMany, null, inputOutputMapper); + } else { + this.emitUnit(script, true, emitter); + } + } + if(emitter) { + emitter.Close(); + } + }; + TypeScriptCompiler.prototype.emitToOutfile = function (outputFile) { + if(this.settings.mapSourceFiles) { + throw Error("Cannot generate source map"); + } + if(this.settings.generateDeclarationFiles) { + throw Error("Cannot generate declaration files"); + } + if(this.settings.outputOption != "") { + throw Error("Cannot parse output option"); + } + var emitter = emitter = new TypeScript.Emitter(this.typeChecker, "stdout", outputFile, this.emitSettings, this.errorReporter); + ; + for(var i = 0, len = this.scripts.members.length; i < len; i++) { + var script = this.scripts.members[i]; + this.typeChecker.locationInfo = script.locationInfo; + emitter.emitJavascript(script, TypeScript.TokenID.Comma, false); + } + }; + TypeScriptCompiler.prototype.emitAST = function (ioHost) { + this.parseEmitOption(ioHost); + var outFile = null; + var context = null; + for(var i = 0, len = this.scripts.members.length; i < len; i++) { + var script = this.scripts.members[i]; + if(this.emitSettings.outputMany || context == null) { + var fname = this.units[i].filename; + var mapToTxtFileName = function (fileName, wholeFileNameReplaced) { + return TypeScriptCompiler.mapToFileNameExtension(".txt", fileName, wholeFileNameReplaced); + }; + var outFname = this.emitSettings.mapOutputFileName(fname, mapToTxtFileName); + outFile = this.createFile(outFname, this.useUTF8ForFile(script)); + context = new TypeScript.PrintContext(outFile, this.parser); + } + TypeScript.getAstWalkerFactory().walk(script, TypeScript.prePrintAST, TypeScript.postPrintAST, null, context); + if(this.emitSettings.outputMany) { + try { + outFile.Close(); + } catch (e) { + this.errorReporter.emitterError(null, e.message); + } + } + } + if(!this.emitSettings.outputMany) { + try { + outFile.Close(); + } catch (e) { + this.errorReporter.emitterError(null, e.message); + } + } + }; + TypeScriptCompiler.prototype.outputScriptToUTF8 = function (script) { + return script.containsUnicodeChar || (this.emitSettings.emitComments && script.containsUnicodeCharInComment); + }; + TypeScriptCompiler.prototype.outputScriptsToUTF8 = function (scripts) { + for(var i = 0, len = scripts.length; i < len; i++) { + var script = scripts[i]; + if(this.outputScriptToUTF8(script)) { + return true; + } + } + return false; + }; + TypeScriptCompiler.prototype.createFile = function (fileName, useUTF8) { + try { + return this.emitSettings.ioHost.createFile(fileName, useUTF8); + } catch (ex) { + this.errorReporter.emitterError(null, ex.message); + } + }; + return TypeScriptCompiler; + })(); + TypeScript.TypeScriptCompiler = TypeScriptCompiler; + var ScopeEntry = (function () { + function ScopeEntry(name, type, sym) { + this.name = name; + this.type = type; + this.sym = sym; + } + return ScopeEntry; + })(); + TypeScript.ScopeEntry = ScopeEntry; + var ScopeTraversal = (function () { + function ScopeTraversal(compiler) { + this.compiler = compiler; + } + ScopeTraversal.prototype.getScope = function (enclosingScopeContext) { + if(enclosingScopeContext.enclosingObjectLit && enclosingScopeContext.isMemberCompletion) { + return enclosingScopeContext.getObjectLiteralScope(); + } else if(enclosingScopeContext.isMemberCompletion) { + if(enclosingScopeContext.useFullAst) { + return this.compiler.typeFlow.findMemberScopeAtFullAst(enclosingScopeContext); + } else { + return this.compiler.typeFlow.findMemberScopeAt(enclosingScopeContext); + } + } else { + return enclosingScopeContext.getScope(); + } + }; + ScopeTraversal.prototype.getScopeEntries = function (enclosingScopeContext, getPrettyTypeName) { + var scope = this.getScope(enclosingScopeContext); + if(scope == null) { + return []; + } + var inScopeNames = new TypeScript.StringHashTable(); + var allSymbolNames = scope.getAllSymbolNames(enclosingScopeContext.isMemberCompletion); + for(var i = 0; i < allSymbolNames.length; i++) { + var name = allSymbolNames[i]; + if(name == TypeScript.globalId || name == "_Core" || name == "_element") { + continue; + } + inScopeNames.add(name, ""); + } + var svModuleDecl = this.compiler.typeChecker.currentModDecl; + this.compiler.typeChecker.currentModDecl = enclosingScopeContext.deepestModuleDecl; + var result = this.getTypeNamesForNames(enclosingScopeContext, inScopeNames.getAllKeys(), scope, getPrettyTypeName); + this.compiler.typeChecker.currentModDecl = svModuleDecl; + return result; + }; + ScopeTraversal.prototype.getTypeNamesForNames = function (enclosingScopeContext, allNames, scope, getPrettyTypeName) { + var result = []; + var enclosingScope = enclosingScopeContext.getScope(); + for(var i = 0; i < allNames.length; i++) { + var name = allNames[i]; + var publicsOnly = enclosingScopeContext.publicsOnly && enclosingScopeContext.isMemberCompletion; + var symbol = scope.find(name, publicsOnly, false); + if(symbol == null) { + symbol = scope.find(name, publicsOnly, true); + } + var displayThisMember = symbol && symbol.flags & TypeScript.SymbolFlags.Private ? symbol.container == scope.container : true; + if(symbol) { + if(displayThisMember && !TypeScript.isQuoted(symbol.name) && !TypeScript.isRelative(symbol.name)) { + var getPrettyOverload = getPrettyTypeName && symbol.declAST && symbol.declAST.nodeType == TypeScript.NodeType.FuncDecl; + var type = symbol.getType(); + var typeName = type ? type.getScopedTypeName(enclosingScope, getPrettyOverload) : ""; + result.push(new ScopeEntry(name, typeName, symbol)); + } + } else { + if(name == "true" || name == "false") { + result.push(new ScopeEntry(name, "bool", this.compiler.typeChecker.booleanType.symbol)); + } + } + } + return result; + }; + return ScopeTraversal; + })(); + TypeScript.ScopeTraversal = ScopeTraversal; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (CompilerDiagnostics) { + CompilerDiagnostics.debug = false; + CompilerDiagnostics.diagnosticWriter = null; + CompilerDiagnostics.analysisPass = 0; + function Alert(output) { + if(CompilerDiagnostics.diagnosticWriter) { + CompilerDiagnostics.diagnosticWriter.Alert(output); + } + } + CompilerDiagnostics.Alert = Alert; + function debugPrint(s) { + if(CompilerDiagnostics.debug) { + Alert(s); + } + } + CompilerDiagnostics.debugPrint = debugPrint; + function assert(condition, s) { + if(CompilerDiagnostics.debug) { + if(!condition) { + Alert(s); + } + } + } + CompilerDiagnostics.assert = assert; + })(TypeScript.CompilerDiagnostics || (TypeScript.CompilerDiagnostics = {})); + var CompilerDiagnostics = TypeScript.CompilerDiagnostics; + var NullLogger = (function () { + function NullLogger() { } + NullLogger.prototype.information = function () { + return false; + }; + NullLogger.prototype.debug = function () { + return false; + }; + NullLogger.prototype.warning = function () { + return false; + }; + NullLogger.prototype.error = function () { + return false; + }; + NullLogger.prototype.fatal = function () { + return false; + }; + NullLogger.prototype.log = function (s) { + }; + return NullLogger; + })(); + TypeScript.NullLogger = NullLogger; + var LoggerAdapter = (function () { + function LoggerAdapter(logger) { + this.logger = logger; + this._information = this.logger.information(); + this._debug = this.logger.debug(); + this._warning = this.logger.warning(); + this._error = this.logger.error(); + this._fatal = this.logger.fatal(); + } + LoggerAdapter.prototype.information = function () { + return this._information; + }; + LoggerAdapter.prototype.debug = function () { + return this._debug; + }; + LoggerAdapter.prototype.warning = function () { + return this._warning; + }; + LoggerAdapter.prototype.error = function () { + return this._error; + }; + LoggerAdapter.prototype.fatal = function () { + return this._fatal; + }; + LoggerAdapter.prototype.log = function (s) { + this.logger.log(s); + }; + return LoggerAdapter; + })(); + TypeScript.LoggerAdapter = LoggerAdapter; + var BufferedLogger = (function () { + function BufferedLogger() { + this.logContents = []; + } + BufferedLogger.prototype.information = function () { + return false; + }; + BufferedLogger.prototype.debug = function () { + return false; + }; + BufferedLogger.prototype.warning = function () { + return false; + }; + BufferedLogger.prototype.error = function () { + return false; + }; + BufferedLogger.prototype.fatal = function () { + return false; + }; + BufferedLogger.prototype.log = function (s) { + this.logContents.push(s); + }; + return BufferedLogger; + })(); + TypeScript.BufferedLogger = BufferedLogger; + function timeFunction(logger, funcDescription, func) { + var start = +new Date(); + var result = func(); + var end = +new Date(); + logger.log(funcDescription + " completed in " + (end - start) + " msec"); + return result; + } + TypeScript.timeFunction = timeFunction; + function stringToLiteral(value, length) { + var result = ""; + var addChar = function (index) { + var ch = value.charCodeAt(index); + switch(ch) { + case 0x09: + result += "\\t"; + break; + case 0x0a: + result += "\\n"; + break; + case 0x0b: + result += "\\v"; + break; + case 0x0c: + result += "\\f"; + break; + case 0x0d: + result += "\\r"; + break; + case 0x22: + result += "\\\""; + break; + case 0x27: + result += "\\\'"; + break; + case 0x5c: + result += "\\"; + break; + default: + result += value.charAt(index); + } + }; + var tooLong = (value.length > length); + if(tooLong) { + var mid = length >> 1; + for(var i = 0; i < mid; i++) { + addChar(i); + } + result += "(...)"; + for(var i = value.length - mid; i < value.length; i++) { + addChar(i); + } + } else { + length = value.length; + for(var i = 0; i < length; i++) { + addChar(i); + } + } + return result; + } + TypeScript.stringToLiteral = stringToLiteral; +})(TypeScript || (TypeScript = {})); +var IOUtils; +(function (IOUtils) { + function createDirectoryStructure(ioHost, dirName) { + if(ioHost.directoryExists(dirName)) { + return; + } + var parentDirectory = ioHost.dirName(dirName); + if(parentDirectory != "") { + createDirectoryStructure(ioHost, parentDirectory); + } + ioHost.createDirectory(dirName); + } + function createFileAndFolderStructure(ioHost, fileName, useUTF8) { + var path = ioHost.resolvePath(fileName); + var dirName = ioHost.dirName(path); + createDirectoryStructure(ioHost, dirName); + return ioHost.createFile(path, useUTF8); + } + IOUtils.createFileAndFolderStructure = createFileAndFolderStructure; + function throwIOError(message, error) { + var errorMessage = message; + if(error && error.message) { + errorMessage += (" " + error.message); + } + throw new Error(errorMessage); + } + IOUtils.throwIOError = throwIOError; + var BufferedTextWriter = (function () { + function BufferedTextWriter(writer, capacity) { + if (typeof capacity === "undefined") { capacity = 1024; } + this.writer = writer; + this.capacity = capacity; + this.buffer = ""; + } + BufferedTextWriter.prototype.Write = function (str) { + this.buffer += str; + if(this.buffer.length >= this.capacity) { + this.writer.Write(this.buffer); + this.buffer = ""; + } + }; + BufferedTextWriter.prototype.WriteLine = function (str) { + this.Write(str + '\r\n'); + }; + BufferedTextWriter.prototype.Close = function () { + this.writer.Write(this.buffer); + this.writer.Close(); + this.buffer = null; + }; + return BufferedTextWriter; + })(); + IOUtils.BufferedTextWriter = BufferedTextWriter; +})(IOUtils || (IOUtils = {})); + +var IO = (function () { + function getWindowsScriptHostIO() { + var fso = new ActiveXObject("Scripting.FileSystemObject"); + var streamObjectPool = []; + function getStreamObject() { + if(streamObjectPool.length > 0) { + return streamObjectPool.pop(); + } else { + return new ActiveXObject("ADODB.Stream"); + } + } + function releaseStreamObject(obj) { + streamObjectPool.push(obj); + } + var args = []; + for(var i = 0; i < WScript.Arguments.length; i++) { + args[i] = WScript.Arguments.Item(i); + } + return { + readFile: function (path) { + try { + var streamObj = getStreamObject(); + streamObj.Open(); + streamObj.Type = 2; + streamObj.Charset = 'x-ansi'; + streamObj.LoadFromFile(path); + var bomChar = streamObj.ReadText(2); + streamObj.Position = 0; + if((bomChar.charCodeAt(0) == 0xFE && bomChar.charCodeAt(1) == 0xFF) || (bomChar.charCodeAt(0) == 0xFF && bomChar.charCodeAt(1) == 0xFE)) { + streamObj.Charset = 'unicode'; + } else if(bomChar.charCodeAt(0) == 0xEF && bomChar.charCodeAt(1) == 0xBB) { + streamObj.Charset = 'utf-8'; + } + var str = streamObj.ReadText(-1); + streamObj.Close(); + releaseStreamObject(streamObj); + return str; + } catch (err) { + IOUtils.throwIOError("Error reading file \"" + path + "\".", err); + } + }, + writeFile: function (path, contents) { + var file = this.createFile(path); + file.Write(contents); + file.Close(); + }, + fileExists: function (path) { + return fso.FileExists(path); + }, + resolvePath: function (path) { + return fso.GetAbsolutePathName(path); + }, + dirName: function (path) { + return fso.GetParentFolderName(path); + }, + findFile: function (rootPath, partialFilePath) { + var path = fso.GetAbsolutePathName(rootPath) + "/" + partialFilePath; + while(true) { + if(fso.FileExists(path)) { + try { + var content = this.readFile(path); + return { + content: content, + path: path + }; + } catch (err) { + } + } else { + rootPath = fso.GetParentFolderName(fso.GetAbsolutePathName(rootPath)); + if(rootPath == "") { + return null; + } else { + path = fso.BuildPath(rootPath, partialFilePath); + } + } + } + }, + deleteFile: function (path) { + try { + if(fso.FileExists(path)) { + fso.DeleteFile(path, true); + } + } catch (e) { + IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); + } + }, + createFile: function (path, useUTF8) { + try { + var streamObj = getStreamObject(); + streamObj.Charset = useUTF8 ? 'utf-8' : 'x-ansi'; + streamObj.Open(); + return { + Write: function (str) { + streamObj.WriteText(str, 0); + }, + WriteLine: function (str) { + streamObj.WriteText(str, 1); + }, + Close: function () { + try { + streamObj.SaveToFile(path, 2); + } catch (saveError) { + IOUtils.throwIOError("Couldn't write to file '" + path + "'.", saveError); + }finally { + if(streamObj.State != 0) { + streamObj.Close(); + } + releaseStreamObject(streamObj); + } + } + }; + } catch (creationError) { + IOUtils.throwIOError("Couldn't write to file '" + path + "'.", creationError); + } + }, + directoryExists: function (path) { + return fso.FolderExists(path); + }, + createDirectory: function (path) { + try { + if(!this.directoryExists(path)) { + fso.CreateFolder(path); + } + } catch (e) { + IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e); + } + }, + dir: function (path, spec, options) { + options = options || { + }; + function filesInFolder(folder, root) { + var paths = []; + var fc; + if(options.recursive) { + fc = new Enumerator(folder.subfolders); + for(; !fc.atEnd(); fc.moveNext()) { + paths = paths.concat(filesInFolder(fc.item(), root + "/" + fc.item().Name)); + } + } + fc = new Enumerator(folder.files); + for(; !fc.atEnd(); fc.moveNext()) { + if(!spec || fc.item().Name.match(spec)) { + paths.push(root + "/" + fc.item().Name); + } + } + return paths; + } + var folder = fso.GetFolder(path); + var paths = []; + return filesInFolder(folder, path); + }, + print: function (str) { + WScript.StdOut.Write(str); + }, + printLine: function (str) { + WScript.Echo(str); + }, + arguments: args, + stderr: WScript.StdErr, + stdout: WScript.StdOut, + watchFile: null, + run: function (source, filename) { + try { + eval(source); + } catch (e) { + IOUtils.throwIOError("Error while executing file '" + filename + "'.", e); + } + }, + getExecutingFilePath: function () { + return WScript.ScriptFullName; + }, + quit: function (exitCode) { + if (typeof exitCode === "undefined") { exitCode = 0; } + try { + WScript.Quit(exitCode); + } catch (e) { + } + } + }; + } + ; + function getNodeIO() { + var _fs = require('fs'); + var _path = require('path'); + var _module = require('module'); + return { + readFile: function (file) { + try { + var buffer = _fs.readFileSync(file); + switch(buffer[0]) { + case 0xFE: + if(buffer[1] == 0xFF) { + var i = 0; + while((i + 1) < buffer.length) { + var temp = buffer[i]; + buffer[i] = buffer[i + 1]; + buffer[i + 1] = temp; + i += 2; + } + return buffer.toString("ucs2", 2); + } + break; + case 0xFF: + if(buffer[1] == 0xFE) { + return buffer.toString("ucs2", 2); + } + break; + case 0xEF: + if(buffer[1] == 0xBB) { + return buffer.toString("utf8", 3); + } + } + return buffer.toString(); + } catch (e) { + IOUtils.throwIOError("Error reading file \"" + file + "\".", e); + } + }, + writeFile: _fs.writeFileSync, + deleteFile: function (path) { + try { + _fs.unlinkSync(path); + } catch (e) { + IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); + } + }, + fileExists: function (path) { + return _fs.existsSync(path); + }, + createFile: function (path, useUTF8) { + function mkdirRecursiveSync(path) { + var stats = _fs.statSync(path); + if(stats.isFile()) { + IOUtils.throwIOError("\"" + path + "\" exists but isn't a directory.", null); + } else if(stats.isDirectory()) { + return; + } else { + mkdirRecursiveSync(_path.dirname(path)); + _fs.mkdirSync(path, 0775); + } + } + mkdirRecursiveSync(_path.dirname(path)); + try { + var fd = _fs.openSync(path, 'w'); + } catch (e) { + IOUtils.throwIOError("Couldn't write to file '" + path + "'.", e); + } + return new IOUtils.BufferedTextWriter({ + Write: function (str) { + _fs.writeSync(fd, str); + }, + Close: function () { + _fs.closeSync(fd); + fd = null; + } + }); + }, + dir: function dir(path, spec, options) { + options = options || { + }; + function filesInFolder(folder) { + var paths = []; + var files = _fs.readdirSync(folder); + for(var i = 0; i < files.length; i++) { + var stat = _fs.statSync(folder + "/" + files[i]); + if(options.recursive && stat.isDirectory()) { + paths = paths.concat(filesInFolder(folder + "/" + files[i])); + } else if(stat.isFile() && (!spec || files[i].match(spec))) { + paths.push(folder + "/" + files[i]); + } + } + return paths; + } + return filesInFolder(path); + }, + createDirectory: function (path) { + try { + if(!this.directoryExists(path)) { + _fs.mkdirSync(path); + } + } catch (e) { + IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e); + } + }, + directoryExists: function (path) { + return _fs.existsSync(path) && _fs.lstatSync(path).isDirectory(); + }, + resolvePath: function (path) { + return _path.resolve(path); + }, + dirName: function (path) { + return _path.dirname(path); + }, + findFile: function (rootPath, partialFilePath) { + var path = rootPath + "/" + partialFilePath; + while(true) { + if(_fs.existsSync(path)) { + try { + var content = this.readFile(path); + return { + content: content, + path: path + }; + } catch (err) { + } + } else { + var parentPath = _path.resolve(rootPath, ".."); + if(rootPath === parentPath) { + return null; + } else { + rootPath = parentPath; + path = _path.resolve(rootPath, partialFilePath); + } + } + } + }, + print: function (str) { + process.stdout.write(str); + }, + printLine: function (str) { + process.stdout.write(str + '\n'); + }, + arguments: process.argv.slice(2), + stderr: { + Write: function (str) { + process.stderr.write(str); + }, + WriteLine: function (str) { + process.stderr.write(str + '\n'); + }, + Close: function () { + } + }, + stdout: { + Write: function (str) { + process.stdout.write(str); + }, + WriteLine: function (str) { + process.stdout.write(str + '\n'); + }, + Close: function () { + } + }, + watchFile: function (filename, callback) { + var firstRun = true; + var processingChange = false; + var fileChanged = function (curr, prev) { + if(!firstRun) { + if(curr.mtime < prev.mtime) { + return; + } + _fs.unwatchFile(filename, fileChanged); + if(!processingChange) { + processingChange = true; + callback(filename); + setTimeout(function () { + processingChange = false; + }, 100); + } + } + firstRun = false; + _fs.watchFile(filename, { + persistent: true, + interval: 500 + }, fileChanged); + }; + fileChanged(); + return { + filename: filename, + close: function () { + _fs.unwatchFile(filename, fileChanged); + } + }; + }, + run: function (source, filename) { + require.main.filename = filename; + require.main.paths = _module._nodeModulePaths(_path.dirname(_fs.realpathSync(filename))); + require.main._compile(source, filename); + }, + getExecutingFilePath: function () { + return process.mainModule.filename; + }, + quit: process.exit + }; + } + ; + if(typeof ActiveXObject === "function") { + return getWindowsScriptHostIO(); + } else if(typeof require === "function") { + return getNodeIO(); + } else { + return null; + } +})(); +var OptionsParser = (function () { + function OptionsParser(host) { + this.host = host; + this.DEFAULT_SHORT_FLAG = "-"; + this.DEFAULT_LONG_FLAG = "--"; + this.unnamed = []; + this.options = []; + } + OptionsParser.prototype.findOption = function (arg) { + for(var i = 0; i < this.options.length; i++) { + if(arg === this.options[i].short || arg === this.options[i].name) { + return this.options[i]; + } + } + return null; + }; + OptionsParser.prototype.printUsage = function () { + this.host.printLine("Syntax: tsc [options] [file ..]"); + this.host.printLine(""); + this.host.printLine("Examples: tsc hello.ts"); + this.host.printLine(" tsc --out foo.js foo.ts"); + this.host.printLine(" tsc @args.txt"); + this.host.printLine(""); + this.host.printLine("Options:"); + var output = []; + var maxLength = 0; + this.options = this.options.sort(function (a, b) { + var aName = a.name.toLowerCase(); + var bName = b.name.toLowerCase(); + if(aName > bName) { + return 1; + } else if(aName < bName) { + return -1; + } else { + return 0; + } + }); + for(var i = 0; i < this.options.length; i++) { + var option = this.options[i]; + if(option.experimental) { + continue; + } + if(!option.usage) { + break; + } + var usageString = " "; + var type = option.type ? " " + option.type.toUpperCase() : ""; + if(option.short) { + usageString += this.DEFAULT_SHORT_FLAG + option.short + type + ", "; + } + usageString += this.DEFAULT_LONG_FLAG + option.name + type; + output.push([ + usageString, + option.usage + ]); + if(usageString.length > maxLength) { + maxLength = usageString.length; + } + } + output.push([ + " @", + "Insert command line options and files from a file." + ]); + for(var i = 0; i < output.length; i++) { + this.host.printLine(output[i][0] + (new Array(maxLength - output[i][0].length + 3)).join(" ") + output[i][1]); + } + }; + OptionsParser.prototype.option = function (name, config, short) { + if(!config) { + config = short; + short = null; + } + config.name = name; + config.short = short; + config.flag = false; + this.options.push(config); + }; + OptionsParser.prototype.flag = function (name, config, short) { + if(!config) { + config = short; + short = null; + } + config.name = name; + config.short = short; + config.flag = true; + this.options.push(config); + }; + OptionsParser.prototype.parseString = function (argString) { + var position = 0; + var tokens = argString.match(/\s+|"|[^\s"]+/g); + function peek() { + return tokens[position]; + } + function consume() { + return tokens[position++]; + } + function consumeQuotedString() { + var value = ''; + consume(); + var token = peek(); + while(token && token !== '"') { + consume(); + value += token; + token = peek(); + } + consume(); + return value; + } + var args = []; + var currentArg = ''; + while(position < tokens.length) { + var token = peek(); + if(token === '"') { + currentArg += consumeQuotedString(); + } else if(token.match(/\s/)) { + if(currentArg.length > 0) { + args.push(currentArg); + currentArg = ''; + } + consume(); + } else { + consume(); + currentArg += token; + } + } + if(currentArg.length > 0) { + args.push(currentArg); + } + this.parse(args); + }; + OptionsParser.prototype.parse = function (args) { + var position = 0; + function consume() { + return args[position++]; + } + while(position < args.length) { + var current = consume(); + var match = current.match(/^(--?|@)(.*)/); + var value = null; + if(match) { + if(match[1] === '@') { + this.parseString(this.host.readFile(match[2])); + } else { + var arg = match[2]; + var option = this.findOption(arg); + if(option === null) { + this.host.printLine("Unknown option '" + arg + "'"); + this.host.printLine("Use the '--help' flag to see options"); + } else { + if(!option.flag) { + value = consume(); + } + option.set(value); + } + } + } else { + this.unnamed.push(current); + } + } + }; + return OptionsParser; +})(); +var ErrorReporter = (function () { + function ErrorReporter(ioHost) { + this.ioHost = ioHost; + this.hasErrors = false; + } + ErrorReporter.prototype.Write = function (s) { + this.hasErrors = true; + this.ioHost.stderr.Write(s); + }; + ErrorReporter.prototype.WriteLine = function (s) { + this.hasErrors = true; + this.ioHost.stderr.WriteLine(s); + }; + ErrorReporter.prototype.Close = function () { + }; + ErrorReporter.prototype.reset = function () { + this.hasErrors = false; + }; + return ErrorReporter; +})(); +var CommandLineHost = (function () { + function CommandLineHost(compilationSettings, errorReporter) { + this.compilationSettings = compilationSettings; + this.errorReporter = errorReporter; + this.pathMap = { + }; + this.resolvedPaths = { + }; + } + CommandLineHost.prototype.getPathIdentifier = function (path) { + return this.compilationSettings.useCaseSensitiveFileResolution ? path : path.toLocaleUpperCase(); + }; + CommandLineHost.prototype.isResolved = function (path) { + return this.resolvedPaths[this.getPathIdentifier(this.pathMap[path])] != undefined; + }; + CommandLineHost.prototype.resolveCompilationEnvironment = function (preEnv, resolver, traceDependencies) { + var _this = this; + var resolvedEnv = new TypeScript.CompilationEnvironment(preEnv.compilationSettings, preEnv.ioHost); + var nCode = preEnv.code.length; + var path = ""; + var postResolutionError = function (errorFile, errorMessage) { + _this.errorReporter(errorFile + (errorMessage == "" ? "" : ": " + errorMessage)); + }; + var resolutionDispatcher = { + postResolutionError: function (errorFile, line, col, errorMessage) { + _this.errorReporter(errorFile + "(" + line + "," + col + ") " + (errorMessage == "" ? "" : ": " + errorMessage)); + }, + postResolution: function (path, code) { + var pathId = _this.getPathIdentifier(path); + if(!_this.resolvedPaths[pathId]) { + resolvedEnv.code.push(code); + _this.resolvedPaths[pathId] = true; + } + } + }; + for(var i = 0; i < nCode; i++) { + path = TypeScript.switchToForwardSlashes(preEnv.ioHost.resolvePath(preEnv.code[i].path)); + this.pathMap[preEnv.code[i].path] = path; + resolver.resolveCode(path, "", false, resolutionDispatcher); + } + return resolvedEnv; + }; + return CommandLineHost; +})(); +var BatchCompiler = (function () { + function BatchCompiler(ioHost) { + this.ioHost = ioHost; + this.resolvedEnvironment = null; + this.compilerVersion = "0.8.3.0"; + this.printedVersion = false; + this.errorReporter = null; + this.compilationSettings = new TypeScript.CompilationSettings(); + this.compilationEnvironment = new TypeScript.CompilationEnvironment(this.compilationSettings, this.ioHost); + this.errorReporter = new ErrorReporter(this.ioHost); + } + BatchCompiler.prototype.resolve = function () { + var _this = this; + var resolver = new TypeScript.CodeResolver(this.compilationEnvironment); + var commandLineHost = new CommandLineHost(this.compilationSettings, function (err) { + return _this.errorReporter.WriteLine(err); + }); + var ret = commandLineHost.resolveCompilationEnvironment(this.compilationEnvironment, resolver, true); + for(var i = 0; i < this.compilationEnvironment.code.length; i++) { + if(!commandLineHost.isResolved(this.compilationEnvironment.code[i].path)) { + var path = this.compilationEnvironment.code[i].path; + if(!TypeScript.isSTRFile(path) && !TypeScript.isDSTRFile(path) && !TypeScript.isTSFile(path) && !TypeScript.isDTSFile(path)) { + this.errorReporter.WriteLine("Unknown extension for file: \"" + path + "\". Only .ts and .d.ts extensions are allowed."); + } else { + this.errorReporter.WriteLine("Error reading file \"" + path + "\": File not found"); + } + } + } + return ret; + }; + BatchCompiler.prototype.compile = function () { + var _this = this; + var compiler; + compiler = new TypeScript.TypeScriptCompiler(this.errorReporter, new TypeScript.NullLogger(), this.compilationSettings); + compiler.setErrorOutput(this.errorReporter); + compiler.setErrorCallback(function (minChar, charLen, message, unitIndex) { + compiler.errorReporter.hasErrors = true; + var fname = _this.resolvedEnvironment.code[unitIndex].path; + var lineCol = { + line: -1, + col: -1 + }; + compiler.parser.getSourceLineCol(lineCol, minChar); + var msg = fname + " (" + lineCol.line + "," + (lineCol.col + 1) + "): " + message; + if(_this.compilationSettings.errorRecovery) { + _this.errorReporter.WriteLine(msg); + } else { + throw new SyntaxError(msg); + } + }); + if(this.compilationSettings.emitComments) { + compiler.emitCommentsToOutput(); + } + var consumeUnit = function (code, addAsResident) { + try { + if(!_this.compilationSettings.resolve) { + code.content = _this.ioHost.readFile(code.path); + if(_this.compilationSettings.generateDeclarationFiles) { + TypeScript.CompilerDiagnostics.assert(code.referencedFiles == null, "With no resolve option, referenced files need to null"); + code.referencedFiles = TypeScript.getReferencedFiles(code); + } + } + if(code.content != null) { + if(_this.compilationSettings.parseOnly) { + compiler.parseUnit(code.content, code.path); + } else { + if(_this.compilationSettings.errorRecovery) { + compiler.parser.setErrorRecovery(_this.errorReporter); + } + compiler.addUnit(code.content, code.path, addAsResident, code.referencedFiles); + } + } + } catch (err) { + compiler.errorReporter.hasErrors = true; + _this.errorReporter.WriteLine(err.message); + } + }; + for(var iCode = 0; iCode < this.resolvedEnvironment.code.length; iCode++) { + if(!this.compilationSettings.parseOnly || (iCode > 0)) { + consumeUnit(this.resolvedEnvironment.code[iCode], false); + } + } + var emitterIOHost = { + createFile: function (fileName, useUTF8) { + return IOUtils.createFileAndFolderStructure(_this.ioHost, fileName, useUTF8); + }, + directoryExists: this.ioHost.directoryExists, + fileExists: this.ioHost.fileExists, + resolvePath: this.ioHost.resolvePath + }; + try { + if(!this.compilationSettings.parseOnly) { + compiler.typeCheck(); + var mapInputToOutput = function (unitIndex, outFile) { + _this.compilationEnvironment.inputOutputMap[unitIndex] = outFile; + }; + compiler.emit(emitterIOHost, mapInputToOutput); + compiler.emitDeclarations(); + } else { + compiler.emitAST(emitterIOHost); + } + } catch (err) { + compiler.errorReporter.hasErrors = true; + if(err.message != "EmitError") { + throw err; + } + } + return compiler.errorReporter.hasErrors; + }; + BatchCompiler.prototype.run = function () { + for(var i in this.compilationEnvironment.code) { + var outputFileName = this.compilationEnvironment.inputOutputMap[i]; + if(this.ioHost.fileExists(outputFileName)) { + var unitRes = this.ioHost.readFile(outputFileName); + this.ioHost.run(unitRes, outputFileName); + } + } + }; + BatchCompiler.prototype.batchCompile = function () { + var _this = this; + TypeScript.CompilerDiagnostics.diagnosticWriter = { + Alert: function (s) { + _this.ioHost.printLine(s); + } + }; + var code; + var opts = new OptionsParser(this.ioHost); + opts.option('out', { + usage: 'Concatenate and emit output to single file | Redirect output structure to the directory', + type: 'file|directory', + set: function (str) { + _this.compilationSettings.outputOption = str; + } + }); + opts.option('style', { + usage: 'Select style checking options (examples --style requireSemi:off or --style "eqeqeq;bitwise:off")', + experimental: true, + set: function (str) { + _this.compilationSettings.setStyleOptions(str); + } + }); + opts.flag('sourcemap', { + usage: 'Generates corresponding .map file', + set: function () { + _this.compilationSettings.mapSourceFiles = true; + } + }); + opts.flag('fullSourceMapPath', { + usage: 'Writes the full path of map file in the generated js file', + experimental: true, + set: function () { + _this.compilationSettings.emitFullSourceMapPath = true; + } + }); + opts.flag('declaration', { + usage: 'Generates corresponding .d.ts file', + set: function () { + _this.compilationSettings.generateDeclarationFiles = true; + } + }); + if(this.ioHost.watchFile) { + opts.flag('watch', { + usage: 'Watch output files', + set: function () { + _this.compilationSettings.watch = true; + } + }, 'w'); + } + opts.flag('exec', { + usage: 'Execute the script after compilation', + set: function () { + _this.compilationSettings.exec = true; + } + }, 'e'); + opts.flag('parse', { + usage: 'Parse only', + experimental: true, + set: function () { + _this.compilationSettings.parseOnly = true; + } + }); + opts.flag('minw', { + usage: 'Minimize whitespace', + experimental: true, + set: function () { + _this.compilationSettings.minWhitespace = true; + } + }, 'mw'); + opts.flag('const', { + usage: 'Propagate constants to emitted code', + experimental: true, + set: function () { + _this.compilationSettings.propagateConstants = true; + } + }); + opts.flag('errorrecovery', { + usage: 'Enable error recovery', + experimental: true, + set: function () { + _this.compilationSettings.errorRecovery = true; + } + }, 'er'); + opts.flag('comments', { + usage: 'Emit comments to output', + set: function () { + _this.compilationSettings.emitComments = true; + } + }, 'c'); + opts.flag('cflow', { + usage: 'Control flow', + experimental: true, + set: function () { + _this.compilationSettings.controlFlow = true; + } + }); + opts.flag('cflowp', { + usage: 'Print control flow', + experimental: true, + set: function () { + _this.compilationSettings.controlFlow = true; + _this.compilationSettings.printControlFlow = true; + } + }); + opts.flag('cflowu', { + usage: 'Print Use Def control flow', + experimental: true, + set: function () { + _this.compilationSettings.controlFlow = true; + _this.compilationSettings.controlFlowUseDef = true; + } + }); + opts.flag('noerroronwith', { + usage: 'Allow with statements', + experimental: true, + set: function () { + _this.compilationSettings.errorOnWith = false; + } + }); + opts.flag('noresolve', { + usage: 'Skip resolution and preprocessing', + experimental: true, + set: function () { + _this.compilationSettings.resolve = false; + _this.compilationSettings.preprocess = false; + } + }); + opts.flag('debug', { + usage: 'Print debug output', + experimental: true, + set: function () { + TypeScript.CompilerDiagnostics.debug = true; + } + }); + opts.flag('canCallDefinitionSignature', { + usage: 'Allows you to call the definition signature of an overload group', + experimental: true, + set: function () { + _this.compilationSettings.canCallDefinitionSignature = true; + } + }); + opts.flag('nooptimizemodules', { + usage: 'Do not optimize module codegen', + experimental: true, + set: function () { + TypeScript.optimizeModuleCodeGen = false; + } + }); + opts.flag('nolib', { + usage: 'Do not include a default lib.d.ts with global declarations', + set: function () { + _this.compilationSettings.useDefaultLib = false; + } + }); + opts.flag('inferProperties', { + usage: 'Infer class properties from top-level assignments to \'this\'', + experimental: true, + set: function () { + _this.compilationSettings.inferPropertiesFromThisAssignment = true; + } + }); + opts.option('target', { + usage: 'Specify ECMAScript target version: "ES3" (default), or "ES5"', + type: 'VER', + set: function (type) { + type = type.toLowerCase(); + if(type === 'es3') { + _this.compilationSettings.codeGenTarget = TypeScript.CodeGenTarget.ES3; + } else if(type === 'es5') { + _this.compilationSettings.codeGenTarget = TypeScript.CodeGenTarget.ES5; + } else { + _this.errorReporter.WriteLine("ECMAScript target version '" + type + "' not supported. Using default 'ES3' code generation"); + } + } + }); + opts.option('module', { + usage: 'Specify module code generation: "commonjs" (default) or "amd"', + type: 'kind', + set: function (type) { + type = type.toLowerCase(); + if(type === 'commonjs' || type === 'node') { + TypeScript.moduleGenTarget = TypeScript.ModuleGenTarget.Synchronous; + } else if(type === 'amd') { + TypeScript.moduleGenTarget = TypeScript.ModuleGenTarget.Asynchronous; + } else { + _this.errorReporter.WriteLine("Module code generation '" + type + "' not supported. Using default 'commonjs' code generation"); + } + } + }); + var printedUsage = false; + opts.flag('help', { + usage: 'Print this message', + set: function () { + _this.printVersion(); + opts.printUsage(); + printedUsage = true; + } + }, 'h'); + opts.flag('useCaseSensitiveFileResolution', { + usage: 'Force file resolution to be case sensitive', + experimental: true, + set: function () { + _this.compilationSettings.useCaseSensitiveFileResolution = true; + } + }); + opts.flag('version', { + usage: 'Print the compiler\'s version: ' + this.compilerVersion, + set: function () { + _this.printVersion(); + } + }, 'v'); + opts.parse(this.ioHost.arguments); + if(this.compilationSettings.useDefaultLib) { + var compilerFilePath = this.ioHost.getExecutingFilePath(); + var binDirPath = this.ioHost.dirName(compilerFilePath); + var libStrPath = this.ioHost.resolvePath(binDirPath + "/lib.d.ts"); + code = new TypeScript.SourceUnit(libStrPath, null); + this.compilationEnvironment.code.push(code); + } + for(var i = 0; i < opts.unnamed.length; i++) { + code = new TypeScript.SourceUnit(opts.unnamed[i], null); + this.compilationEnvironment.code.push(code); + } + if(this.compilationEnvironment.code.length == (this.compilationSettings.useDefaultLib ? 1 : 0)) { + if(!printedUsage && !this.printedVersion) { + this.printVersion(); + opts.printUsage(); + this.ioHost.quit(1); + } + return; + } + var sourceFiles = []; + if(this.compilationSettings.watch) { + sourceFiles = this.compilationEnvironment.code.slice(0); + } + this.resolvedEnvironment = this.compilationSettings.resolve ? this.resolve() : this.compilationEnvironment; + this.compile(); + if(!this.errorReporter.hasErrors) { + if(this.compilationSettings.exec) { + this.run(); + } + } + if(this.compilationSettings.watch) { + this.watchFiles(sourceFiles); + } else { + this.ioHost.quit(this.errorReporter.hasErrors ? 1 : 0); + } + }; + BatchCompiler.prototype.printVersion = function () { + if(!this.printedVersion) { + this.ioHost.printLine("Version " + this.compilerVersion); + this.printedVersion = true; + } + }; + BatchCompiler.prototype.watchFiles = function (soruceFiles) { + var _this = this; + if(!this.ioHost.watchFile) { + this.errorReporter.WriteLine("Error: Current host does not support -w[atch] option"); + return; + } + var resolvedFiles = []; + var watchers = { + }; + var addWatcher = function (filename) { + if(!watchers[filename]) { + var watcher = _this.ioHost.watchFile(filename, onWatchedFileChange); + watchers[filename] = watcher; + } else { + TypeScript.CompilerDiagnostics.debugPrint("Cannot watch file, it is already watched."); + } + }; + var removeWatcher = function (filename) { + if(watchers[filename]) { + watchers[filename].close(); + delete watchers[filename]; + } else { + TypeScript.CompilerDiagnostics.debugPrint("Cannot stop watching file, it is not being watched."); + } + }; + var onWatchedFileChange = function () { + _this.compilationEnvironment.code = soruceFiles; + _this.errorReporter.reset(); + _this.resolvedEnvironment = _this.compilationSettings.resolve ? _this.resolve() : _this.compilationEnvironment; + var oldFiles = resolvedFiles; + var newFiles = []; + _this.resolvedEnvironment.code.forEach(function (sf) { + return newFiles.push(sf.path); + }); + newFiles = newFiles.sort(); + var i = 0, j = 0; + while(i < oldFiles.length && j < newFiles.length) { + var compareResult = oldFiles[i].localeCompare(newFiles[j]); + if(compareResult == 0) { + i++; + j++; + } else if(compareResult < 0) { + removeWatcher(oldFiles[i]); + i++; + } else { + addWatcher(newFiles[j]); + j++; + } + } + for(var k = i; k < oldFiles.length; k++) { + removeWatcher(oldFiles[k]); + } + for(var k = j; k < newFiles.length; k++) { + addWatcher(newFiles[k]); + } + resolvedFiles = newFiles; + ; + _this.ioHost.printLine(""); + _this.ioHost.printLine("Recompiling (" + new Date() + "): "); + resolvedFiles.forEach(function (f) { + return _this.ioHost.printLine(" " + f); + }); + _this.compile(); + if(!_this.errorReporter.hasErrors) { + if(_this.compilationSettings.exec) { + _this.run(); + } + } + }; + this.ioHost.stderr = this.ioHost.stdout; + this.resolvedEnvironment.code.forEach(function (sf) { + resolvedFiles.push(sf.path); + addWatcher(sf.path); + }); + resolvedFiles.sort(); + }; + return BatchCompiler; +})(); +var batch = new BatchCompiler(IO); +batch.batchCompile(); diff --git a/_infrastructure/tests/typescript_0.8.3/typescript.js b/_infrastructure/tests/typescript_0.8.3/typescript.js new file mode 100644 index 0000000000..94641b33cb --- /dev/null +++ b/_infrastructure/tests/typescript_0.8.3/typescript.js @@ -0,0 +1,23710 @@ +/* ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + +var TypeScript; +(function (TypeScript) { + function hasFlag(val, flag) { + return (val & flag) != 0; + } + TypeScript.hasFlag = hasFlag; + (function (ErrorRecoverySet) { + ErrorRecoverySet._map = []; + ErrorRecoverySet.None = 0; + ErrorRecoverySet.Comma = 1; + ErrorRecoverySet.SColon = 1 << 1; + ErrorRecoverySet.Asg = 1 << 2; + ErrorRecoverySet.BinOp = 1 << 3; + ErrorRecoverySet.RBrack = 1 << 4; + ErrorRecoverySet.RCurly = 1 << 5; + ErrorRecoverySet.RParen = 1 << 6; + ErrorRecoverySet.Dot = 1 << 7; + ErrorRecoverySet.Colon = 1 << 8; + ErrorRecoverySet.PrimType = 1 << 9; + ErrorRecoverySet.AddOp = 1 << 10; + ErrorRecoverySet.LCurly = 1 << 11; + ErrorRecoverySet.PreOp = 1 << 12; + ErrorRecoverySet.RegExp = 1 << 13; + ErrorRecoverySet.LParen = 1 << 14; + ErrorRecoverySet.LBrack = 1 << 15; + ErrorRecoverySet.Scope = 1 << 16; + ErrorRecoverySet.In = 1 << 17; + ErrorRecoverySet.SCase = 1 << 18; + ErrorRecoverySet.Else = 1 << 19; + ErrorRecoverySet.Catch = 1 << 20; + ErrorRecoverySet.Var = 1 << 21; + ErrorRecoverySet.Stmt = 1 << 22; + ErrorRecoverySet.While = 1 << 23; + ErrorRecoverySet.ID = 1 << 24; + ErrorRecoverySet.Prefix = 1 << 25; + ErrorRecoverySet.Literal = 1 << 26; + ErrorRecoverySet.RLit = 1 << 27; + ErrorRecoverySet.Func = 1 << 28; + ErrorRecoverySet.EOF = 1 << 29; + ErrorRecoverySet.TypeScriptS = 1 << 30; + ErrorRecoverySet.ExprStart = ErrorRecoverySet.SColon | ErrorRecoverySet.AddOp | ErrorRecoverySet.LCurly | ErrorRecoverySet.PreOp | ErrorRecoverySet.RegExp | ErrorRecoverySet.LParen | ErrorRecoverySet.LBrack | ErrorRecoverySet.ID | ErrorRecoverySet.Prefix | ErrorRecoverySet.RLit | ErrorRecoverySet.Func | ErrorRecoverySet.Literal; + ErrorRecoverySet.StmtStart = ErrorRecoverySet.ExprStart | ErrorRecoverySet.SColon | ErrorRecoverySet.Var | ErrorRecoverySet.Stmt | ErrorRecoverySet.While | ErrorRecoverySet.TypeScriptS; + ErrorRecoverySet.Postfix = ErrorRecoverySet.Dot | ErrorRecoverySet.LParen | ErrorRecoverySet.LBrack; + })(TypeScript.ErrorRecoverySet || (TypeScript.ErrorRecoverySet = {})); + var ErrorRecoverySet = TypeScript.ErrorRecoverySet; + (function (AllowedElements) { + AllowedElements._map = []; + AllowedElements.None = 0; + AllowedElements.ModuleDeclarations = 1 << 2; + AllowedElements.ClassDeclarations = 1 << 3; + AllowedElements.InterfaceDeclarations = 1 << 4; + AllowedElements.AmbientDeclarations = 1 << 10; + AllowedElements.Properties = 1 << 11; + AllowedElements.Global = AllowedElements.ModuleDeclarations | AllowedElements.ClassDeclarations | AllowedElements.InterfaceDeclarations | AllowedElements.AmbientDeclarations; + AllowedElements.QuickParse = AllowedElements.Global | AllowedElements.Properties; + })(TypeScript.AllowedElements || (TypeScript.AllowedElements = {})); + var AllowedElements = TypeScript.AllowedElements; + (function (Modifiers) { + Modifiers._map = []; + Modifiers.None = 0; + Modifiers.Private = 1; + Modifiers.Public = 1 << 1; + Modifiers.Readonly = 1 << 2; + Modifiers.Ambient = 1 << 3; + Modifiers.Exported = 1 << 4; + Modifiers.Getter = 1 << 5; + Modifiers.Setter = 1 << 6; + Modifiers.Static = 1 << 7; + })(TypeScript.Modifiers || (TypeScript.Modifiers = {})); + var Modifiers = TypeScript.Modifiers; + (function (ASTFlags) { + ASTFlags._map = []; + ASTFlags.None = 0; + ASTFlags.ExplicitSemicolon = 1; + ASTFlags.AutomaticSemicolon = 1 << 1; + ASTFlags.Writeable = 1 << 2; + ASTFlags.Error = 1 << 3; + ASTFlags.DotLHSPartial = 1 << 4; + ASTFlags.DotLHS = 1 << 5; + ASTFlags.IsStatement = 1 << 6; + ASTFlags.StrictMode = 1 << 7; + ASTFlags.PossibleOptionalParameter = 1 << 8; + ASTFlags.ClassBaseConstructorCall = 1 << 9; + ASTFlags.OptionalName = 1 << 10; + ASTFlags.SkipNextRParen = 1 << 11; + })(TypeScript.ASTFlags || (TypeScript.ASTFlags = {})); + var ASTFlags = TypeScript.ASTFlags; + (function (DeclFlags) { + DeclFlags._map = []; + DeclFlags.None = 0; + DeclFlags.Exported = 1; + DeclFlags.Private = 1 << 1; + DeclFlags.Public = 1 << 2; + DeclFlags.Ambient = 1 << 3; + DeclFlags.Static = 1 << 4; + DeclFlags.LocalStatic = 1 << 5; + DeclFlags.GetAccessor = 1 << 6; + DeclFlags.SetAccessor = 1 << 7; + })(TypeScript.DeclFlags || (TypeScript.DeclFlags = {})); + var DeclFlags = TypeScript.DeclFlags; + (function (ModuleFlags) { + ModuleFlags._map = []; + ModuleFlags.None = 0; + ModuleFlags.Exported = 1; + ModuleFlags.Private = 1 << 1; + ModuleFlags.Public = 1 << 2; + ModuleFlags.Ambient = 1 << 3; + ModuleFlags.Static = 1 << 4; + ModuleFlags.LocalStatic = 1 << 5; + ModuleFlags.GetAccessor = 1 << 6; + ModuleFlags.SetAccessor = 1 << 7; + ModuleFlags.IsEnum = 1 << 8; + ModuleFlags.ShouldEmitModuleDecl = 1 << 9; + ModuleFlags.IsWholeFile = 1 << 10; + ModuleFlags.IsDynamic = 1 << 11; + ModuleFlags.MustCaptureThis = 1 << 12; + })(TypeScript.ModuleFlags || (TypeScript.ModuleFlags = {})); + var ModuleFlags = TypeScript.ModuleFlags; + (function (SymbolFlags) { + SymbolFlags._map = []; + SymbolFlags.None = 0; + SymbolFlags.Exported = 1; + SymbolFlags.Private = 1 << 1; + SymbolFlags.Public = 1 << 2; + SymbolFlags.Ambient = 1 << 3; + SymbolFlags.Static = 1 << 4; + SymbolFlags.LocalStatic = 1 << 5; + SymbolFlags.GetAccessor = 1 << 6; + SymbolFlags.SetAccessor = 1 << 7; + SymbolFlags.Property = 1 << 8; + SymbolFlags.Readonly = 1 << 9; + SymbolFlags.ModuleMember = 1 << 10; + SymbolFlags.InterfaceMember = 1 << 11; + SymbolFlags.ClassMember = 1 << 12; + SymbolFlags.BuiltIn = 1 << 13; + SymbolFlags.TypeSetDuringScopeAssignment = 1 << 14; + SymbolFlags.Constant = 1 << 15; + SymbolFlags.Optional = 1 << 16; + SymbolFlags.RecursivelyReferenced = 1 << 17; + SymbolFlags.Bound = 1 << 18; + SymbolFlags.CompilerGenerated = 1 << 19; + })(TypeScript.SymbolFlags || (TypeScript.SymbolFlags = {})); + var SymbolFlags = TypeScript.SymbolFlags; + (function (VarFlags) { + VarFlags._map = []; + VarFlags.None = 0; + VarFlags.Exported = 1; + VarFlags.Private = 1 << 1; + VarFlags.Public = 1 << 2; + VarFlags.Ambient = 1 << 3; + VarFlags.Static = 1 << 4; + VarFlags.LocalStatic = 1 << 5; + VarFlags.GetAccessor = 1 << 6; + VarFlags.SetAccessor = 1 << 7; + VarFlags.AutoInit = 1 << 8; + VarFlags.Property = 1 << 9; + VarFlags.Readonly = 1 << 10; + VarFlags.Class = 1 << 11; + VarFlags.ClassProperty = 1 << 12; + VarFlags.ClassBodyProperty = 1 << 13; + VarFlags.ClassConstructorProperty = 1 << 14; + VarFlags.ClassSuperMustBeFirstCallInConstructor = 1 << 15; + VarFlags.Constant = 1 << 16; + VarFlags.MustCaptureThis = 1 << 17; + })(TypeScript.VarFlags || (TypeScript.VarFlags = {})); + var VarFlags = TypeScript.VarFlags; + (function (FncFlags) { + FncFlags._map = []; + FncFlags.None = 0; + FncFlags.Exported = 1; + FncFlags.Private = 1 << 1; + FncFlags.Public = 1 << 2; + FncFlags.Ambient = 1 << 3; + FncFlags.Static = 1 << 4; + FncFlags.LocalStatic = 1 << 5; + FncFlags.GetAccessor = 1 << 6; + FncFlags.SetAccessor = 1 << 7; + FncFlags.Signature = 1 << 9; + FncFlags.Method = 1 << 10; + FncFlags.HasReturnExpression = 1 << 11; + FncFlags.CallMember = 1 << 12; + FncFlags.ConstructMember = 1 << 13; + FncFlags.HasSelfReference = 1 << 14; + FncFlags.IsFatArrowFunction = 1 << 15; + FncFlags.IndexerMember = 1 << 16; + FncFlags.IsFunctionExpression = 1 << 17; + FncFlags.ClassMethod = 1 << 18; + FncFlags.ClassPropertyMethodExported = 1 << 19; + FncFlags.HasSuperReferenceInFatArrowFunction = 1 << 20; + FncFlags.IsPropertyBound = 1 << 21; + })(TypeScript.FncFlags || (TypeScript.FncFlags = {})); + var FncFlags = TypeScript.FncFlags; + (function (SignatureFlags) { + SignatureFlags._map = []; + SignatureFlags.None = 0; + SignatureFlags.IsIndexer = 1; + SignatureFlags.IsStringIndexer = 1 << 1; + SignatureFlags.IsNumberIndexer = 1 << 2; + })(TypeScript.SignatureFlags || (TypeScript.SignatureFlags = {})); + var SignatureFlags = TypeScript.SignatureFlags; + function ToDeclFlags(fncOrVarOrSymbolOrModuleFlags) { + return fncOrVarOrSymbolOrModuleFlags; + } + TypeScript.ToDeclFlags = ToDeclFlags; + (function (TypeFlags) { + TypeFlags._map = []; + TypeFlags.None = 0; + TypeFlags.HasImplementation = 1; + TypeFlags.HasSelfReference = 1 << 1; + TypeFlags.MergeResult = 1 << 2; + TypeFlags.IsEnum = 1 << 3; + TypeFlags.BuildingName = 1 << 4; + TypeFlags.HasBaseType = 1 << 5; + TypeFlags.HasBaseTypeOfObject = 1 << 6; + TypeFlags.IsClass = 1 << 7; + })(TypeScript.TypeFlags || (TypeScript.TypeFlags = {})); + var TypeFlags = TypeScript.TypeFlags; + (function (TypeRelationshipFlags) { + TypeRelationshipFlags._map = []; + TypeRelationshipFlags.SuccessfulComparison = 0; + TypeRelationshipFlags.SourceIsNullTargetIsVoidOrUndefined = 1; + TypeRelationshipFlags.RequiredPropertyIsMissing = 1 << 1; + TypeRelationshipFlags.IncompatibleSignatures = 1 << 2; + TypeRelationshipFlags.SourceSignatureHasTooManyParameters = 3; + TypeRelationshipFlags.IncompatibleReturnTypes = 1 << 4; + TypeRelationshipFlags.IncompatiblePropertyTypes = 1 << 5; + TypeRelationshipFlags.IncompatibleParameterTypes = 1 << 6; + })(TypeScript.TypeRelationshipFlags || (TypeScript.TypeRelationshipFlags = {})); + var TypeRelationshipFlags = TypeScript.TypeRelationshipFlags; + (function (CodeGenTarget) { + CodeGenTarget._map = []; + CodeGenTarget.ES3 = 0; + CodeGenTarget.ES5 = 1; + })(TypeScript.CodeGenTarget || (TypeScript.CodeGenTarget = {})); + var CodeGenTarget = TypeScript.CodeGenTarget; + (function (ModuleGenTarget) { + ModuleGenTarget._map = []; + ModuleGenTarget.Synchronous = 0; + ModuleGenTarget.Asynchronous = 1; + ModuleGenTarget.Local = 1 << 1; + })(TypeScript.ModuleGenTarget || (TypeScript.ModuleGenTarget = {})); + var ModuleGenTarget = TypeScript.ModuleGenTarget; + TypeScript.codeGenTarget = CodeGenTarget.ES3; + TypeScript.moduleGenTarget = ModuleGenTarget.Synchronous; + TypeScript.optimizeModuleCodeGen = true; + function flagsToString(e, flags) { + var builder = ""; + for(var i = 1; i < (1 << 31); i = i << 1) { + if((flags & i) != 0) { + for(var k in e) { + if(e[k] == i) { + if(builder.length > 0) { + builder += "|"; + } + builder += k; + break; + } + } + } + } + return builder; + } + TypeScript.flagsToString = flagsToString; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (NodeType) { + NodeType._map = []; + NodeType._map[0] = "None"; + NodeType.None = 0; + NodeType._map[1] = "Empty"; + NodeType.Empty = 1; + NodeType._map[2] = "EmptyExpr"; + NodeType.EmptyExpr = 2; + NodeType._map[3] = "True"; + NodeType.True = 3; + NodeType._map[4] = "False"; + NodeType.False = 4; + NodeType._map[5] = "This"; + NodeType.This = 5; + NodeType._map[6] = "Super"; + NodeType.Super = 6; + NodeType._map[7] = "QString"; + NodeType.QString = 7; + NodeType._map[8] = "Regex"; + NodeType.Regex = 8; + NodeType._map[9] = "Null"; + NodeType.Null = 9; + NodeType._map[10] = "ArrayLit"; + NodeType.ArrayLit = 10; + NodeType._map[11] = "ObjectLit"; + NodeType.ObjectLit = 11; + NodeType._map[12] = "Void"; + NodeType.Void = 12; + NodeType._map[13] = "Comma"; + NodeType.Comma = 13; + NodeType._map[14] = "Pos"; + NodeType.Pos = 14; + NodeType._map[15] = "Neg"; + NodeType.Neg = 15; + NodeType._map[16] = "Delete"; + NodeType.Delete = 16; + NodeType._map[17] = "Await"; + NodeType.Await = 17; + NodeType._map[18] = "In"; + NodeType.In = 18; + NodeType._map[19] = "Dot"; + NodeType.Dot = 19; + NodeType._map[20] = "From"; + NodeType.From = 20; + NodeType._map[21] = "Is"; + NodeType.Is = 21; + NodeType._map[22] = "InstOf"; + NodeType.InstOf = 22; + NodeType._map[23] = "Typeof"; + NodeType.Typeof = 23; + NodeType._map[24] = "NumberLit"; + NodeType.NumberLit = 24; + NodeType._map[25] = "Name"; + NodeType.Name = 25; + NodeType._map[26] = "TypeRef"; + NodeType.TypeRef = 26; + NodeType._map[27] = "Index"; + NodeType.Index = 27; + NodeType._map[28] = "Call"; + NodeType.Call = 28; + NodeType._map[29] = "New"; + NodeType.New = 29; + NodeType._map[30] = "Asg"; + NodeType.Asg = 30; + NodeType._map[31] = "AsgAdd"; + NodeType.AsgAdd = 31; + NodeType._map[32] = "AsgSub"; + NodeType.AsgSub = 32; + NodeType._map[33] = "AsgDiv"; + NodeType.AsgDiv = 33; + NodeType._map[34] = "AsgMul"; + NodeType.AsgMul = 34; + NodeType._map[35] = "AsgMod"; + NodeType.AsgMod = 35; + NodeType._map[36] = "AsgAnd"; + NodeType.AsgAnd = 36; + NodeType._map[37] = "AsgXor"; + NodeType.AsgXor = 37; + NodeType._map[38] = "AsgOr"; + NodeType.AsgOr = 38; + NodeType._map[39] = "AsgLsh"; + NodeType.AsgLsh = 39; + NodeType._map[40] = "AsgRsh"; + NodeType.AsgRsh = 40; + NodeType._map[41] = "AsgRs2"; + NodeType.AsgRs2 = 41; + NodeType._map[42] = "ConditionalExpression"; + NodeType.ConditionalExpression = 42; + NodeType._map[43] = "LogOr"; + NodeType.LogOr = 43; + NodeType._map[44] = "LogAnd"; + NodeType.LogAnd = 44; + NodeType._map[45] = "Or"; + NodeType.Or = 45; + NodeType._map[46] = "Xor"; + NodeType.Xor = 46; + NodeType._map[47] = "And"; + NodeType.And = 47; + NodeType._map[48] = "Eq"; + NodeType.Eq = 48; + NodeType._map[49] = "Ne"; + NodeType.Ne = 49; + NodeType._map[50] = "Eqv"; + NodeType.Eqv = 50; + NodeType._map[51] = "NEqv"; + NodeType.NEqv = 51; + NodeType._map[52] = "Lt"; + NodeType.Lt = 52; + NodeType._map[53] = "Le"; + NodeType.Le = 53; + NodeType._map[54] = "Gt"; + NodeType.Gt = 54; + NodeType._map[55] = "Ge"; + NodeType.Ge = 55; + NodeType._map[56] = "Add"; + NodeType.Add = 56; + NodeType._map[57] = "Sub"; + NodeType.Sub = 57; + NodeType._map[58] = "Mul"; + NodeType.Mul = 58; + NodeType._map[59] = "Div"; + NodeType.Div = 59; + NodeType._map[60] = "Mod"; + NodeType.Mod = 60; + NodeType._map[61] = "Lsh"; + NodeType.Lsh = 61; + NodeType._map[62] = "Rsh"; + NodeType.Rsh = 62; + NodeType._map[63] = "Rs2"; + NodeType.Rs2 = 63; + NodeType._map[64] = "Not"; + NodeType.Not = 64; + NodeType._map[65] = "LogNot"; + NodeType.LogNot = 65; + NodeType._map[66] = "IncPre"; + NodeType.IncPre = 66; + NodeType._map[67] = "DecPre"; + NodeType.DecPre = 67; + NodeType._map[68] = "IncPost"; + NodeType.IncPost = 68; + NodeType._map[69] = "DecPost"; + NodeType.DecPost = 69; + NodeType._map[70] = "TypeAssertion"; + NodeType.TypeAssertion = 70; + NodeType._map[71] = "FuncDecl"; + NodeType.FuncDecl = 71; + NodeType._map[72] = "Member"; + NodeType.Member = 72; + NodeType._map[73] = "VarDecl"; + NodeType.VarDecl = 73; + NodeType._map[74] = "ArgDecl"; + NodeType.ArgDecl = 74; + NodeType._map[75] = "Return"; + NodeType.Return = 75; + NodeType._map[76] = "Break"; + NodeType.Break = 76; + NodeType._map[77] = "Continue"; + NodeType.Continue = 77; + NodeType._map[78] = "Throw"; + NodeType.Throw = 78; + NodeType._map[79] = "For"; + NodeType.For = 79; + NodeType._map[80] = "ForIn"; + NodeType.ForIn = 80; + NodeType._map[81] = "If"; + NodeType.If = 81; + NodeType._map[82] = "While"; + NodeType.While = 82; + NodeType._map[83] = "DoWhile"; + NodeType.DoWhile = 83; + NodeType._map[84] = "Block"; + NodeType.Block = 84; + NodeType._map[85] = "Case"; + NodeType.Case = 85; + NodeType._map[86] = "Switch"; + NodeType.Switch = 86; + NodeType._map[87] = "Try"; + NodeType.Try = 87; + NodeType._map[88] = "TryCatch"; + NodeType.TryCatch = 88; + NodeType._map[89] = "TryFinally"; + NodeType.TryFinally = 89; + NodeType._map[90] = "Finally"; + NodeType.Finally = 90; + NodeType._map[91] = "Catch"; + NodeType.Catch = 91; + NodeType._map[92] = "List"; + NodeType.List = 92; + NodeType._map[93] = "Script"; + NodeType.Script = 93; + NodeType._map[94] = "ClassDeclaration"; + NodeType.ClassDeclaration = 94; + NodeType._map[95] = "InterfaceDeclaration"; + NodeType.InterfaceDeclaration = 95; + NodeType._map[96] = "ModuleDeclaration"; + NodeType.ModuleDeclaration = 96; + NodeType._map[97] = "ImportDeclaration"; + NodeType.ImportDeclaration = 97; + NodeType._map[98] = "With"; + NodeType.With = 98; + NodeType._map[99] = "Label"; + NodeType.Label = 99; + NodeType._map[100] = "LabeledStatement"; + NodeType.LabeledStatement = 100; + NodeType._map[101] = "EBStart"; + NodeType.EBStart = 101; + NodeType._map[102] = "GotoEB"; + NodeType.GotoEB = 102; + NodeType._map[103] = "EndCode"; + NodeType.EndCode = 103; + NodeType._map[104] = "Error"; + NodeType.Error = 104; + NodeType._map[105] = "Comment"; + NodeType.Comment = 105; + NodeType._map[106] = "Debugger"; + NodeType.Debugger = 106; + NodeType.GeneralNode = NodeType.FuncDecl; + NodeType.LastAsg = NodeType.AsgRs2; + })(TypeScript.NodeType || (TypeScript.NodeType = {})); + var NodeType = TypeScript.NodeType; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var BlockIntrinsics = (function () { + function BlockIntrinsics() { + this.prototype = undefined; + this.toString = undefined; + this.toLocaleString = undefined; + this.valueOf = undefined; + this.hasOwnProperty = undefined; + this.propertyIsEnumerable = undefined; + this.isPrototypeOf = undefined; + this["constructor"] = undefined; + } + return BlockIntrinsics; + })(); + TypeScript.BlockIntrinsics = BlockIntrinsics; + var StringHashTable = (function () { + function StringHashTable() { + this.itemCount = 0; + this.table = (new BlockIntrinsics()); + } + StringHashTable.prototype.getAllKeys = function () { + var result = []; + for(var k in this.table) { + if(this.table[k] != undefined) { + result[result.length] = k; + } + } + return result; + }; + StringHashTable.prototype.add = function (key, data) { + if(this.table[key] != undefined) { + return false; + } + this.table[key] = data; + this.itemCount++; + return true; + }; + StringHashTable.prototype.addOrUpdate = function (key, data) { + if(this.table[key] != undefined) { + this.table[key] = data; + return false; + } + this.table[key] = data; + this.itemCount++; + return true; + }; + StringHashTable.prototype.map = function (fn, context) { + for(var k in this.table) { + var data = this.table[k]; + if(data != undefined) { + fn(k, this.table[k], context); + } + } + }; + StringHashTable.prototype.every = function (fn, context) { + for(var k in this.table) { + var data = this.table[k]; + if(data != undefined) { + if(!fn(k, this.table[k], context)) { + return false; + } + } + } + return true; + }; + StringHashTable.prototype.some = function (fn, context) { + for(var k in this.table) { + var data = this.table[k]; + if(data != undefined) { + if(fn(k, this.table[k], context)) { + return true; + } + } + } + return false; + }; + StringHashTable.prototype.count = function () { + return this.itemCount; + }; + StringHashTable.prototype.lookup = function (key) { + var data = this.table[key]; + if(data != undefined) { + return data; + } else { + return (null); + } + }; + return StringHashTable; + })(); + TypeScript.StringHashTable = StringHashTable; + var DualStringHashTable = (function () { + function DualStringHashTable(primaryTable, secondaryTable) { + this.primaryTable = primaryTable; + this.secondaryTable = secondaryTable; + this.insertPrimary = true; + } + DualStringHashTable.prototype.getAllKeys = function () { + return this.primaryTable.getAllKeys().concat(this.secondaryTable.getAllKeys()); + }; + DualStringHashTable.prototype.add = function (key, data) { + if(this.insertPrimary) { + return this.primaryTable.add(key, data); + } else { + return this.secondaryTable.add(key, data); + } + }; + DualStringHashTable.prototype.addOrUpdate = function (key, data) { + if(this.insertPrimary) { + return this.primaryTable.addOrUpdate(key, data); + } else { + return this.secondaryTable.addOrUpdate(key, data); + } + }; + DualStringHashTable.prototype.map = function (fn, context) { + this.primaryTable.map(fn, context); + this.secondaryTable.map(fn, context); + }; + DualStringHashTable.prototype.every = function (fn, context) { + return this.primaryTable.every(fn, context) && this.secondaryTable.every(fn, context); + }; + DualStringHashTable.prototype.some = function (fn, context) { + return this.primaryTable.some(fn, context) || this.secondaryTable.some(fn, context); + }; + DualStringHashTable.prototype.count = function () { + return this.primaryTable.count() + this.secondaryTable.count(); + }; + DualStringHashTable.prototype.lookup = function (key) { + var data = this.primaryTable.lookup(key); + if(data != undefined) { + return data; + } else { + return this.secondaryTable.lookup(key); + } + }; + return DualStringHashTable; + })(); + TypeScript.DualStringHashTable = DualStringHashTable; + function numberHashFn(key) { + var c2 = 0x27d4eb2d; + key = (key ^ 61) ^ (key >>> 16); + key = key + (key << 3); + key = key ^ (key >>> 4); + key = key * c2; + key = key ^ (key >>> 15); + return key; + } + TypeScript.numberHashFn = numberHashFn; + function combineHashes(key1, key2) { + return key2 ^ ((key1 >> 5) + key1); + } + TypeScript.combineHashes = combineHashes; + var HashEntry = (function () { + function HashEntry(key, data) { + this.key = key; + this.data = data; + } + return HashEntry; + })(); + TypeScript.HashEntry = HashEntry; + var HashTable = (function () { + function HashTable(size, hashFn, equalsFn) { + this.size = size; + this.hashFn = hashFn; + this.equalsFn = equalsFn; + this.itemCount = 0; + this.table = new Array(); + for(var i = 0; i < this.size; i++) { + this.table[i] = null; + } + } + HashTable.prototype.add = function (key, data) { + var current; + var entry = new HashEntry(key, data); + var val = this.hashFn(key); + val = val % this.size; + for(current = this.table[val]; current != null; current = current.next) { + if(this.equalsFn(key, current.key)) { + return false; + } + } + entry.next = this.table[val]; + this.table[val] = entry; + this.itemCount++; + return true; + }; + HashTable.prototype.remove = function (key) { + var current; + var val = this.hashFn(key); + val = val % this.size; + var result = null; + var prevEntry = null; + for(current = this.table[val]; current != null; current = current.next) { + if(this.equalsFn(key, current.key)) { + result = current.data; + this.itemCount--; + if(prevEntry) { + prevEntry.next = current.next; + } else { + this.table[val] = current.next; + } + break; + } + prevEntry = current; + } + return result; + }; + HashTable.prototype.count = function () { + return this.itemCount; + }; + HashTable.prototype.lookup = function (key) { + var current; + var val = this.hashFn(key); + val = val % this.size; + for(current = this.table[val]; current != null; current = current.next) { + if(this.equalsFn(key, current.key)) { + return (current.data); + } + } + return (null); + }; + return HashTable; + })(); + TypeScript.HashTable = HashTable; + var SimpleHashTable = (function () { + function SimpleHashTable() { + this.keys = []; + this.values = []; + } + SimpleHashTable.prototype.lookup = function (key, findValue) { + var searchArray = this.keys; + if(findValue) { + searchArray = this.values; + } + for(var i = 0; i < searchArray.length; i++) { + if(searchArray[i] == key) { + return { + key: this.keys[i], + data: this.values[i] + }; + } + } + return null; + }; + SimpleHashTable.prototype.add = function (key, data) { + var lookupData = this.lookup(key); + if(lookupData) { + return false; + } + this.keys[this.keys.length] = key; + this.values[this.values.length] = data; + return true; + }; + return SimpleHashTable; + })(); + TypeScript.SimpleHashTable = SimpleHashTable; +})(TypeScript || (TypeScript = {})); +var __extends = this.__extends || function (d, b) { + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var TypeScript; +(function (TypeScript) { + var ASTSpan = (function () { + function ASTSpan() { + this.minChar = -1; + this.limChar = -1; + } + return ASTSpan; + })(); + TypeScript.ASTSpan = ASTSpan; + var AST = (function (_super) { + __extends(AST, _super); + function AST(nodeType) { + _super.call(this); + this.nodeType = nodeType; + this.type = null; + this.flags = TypeScript.ASTFlags.Writeable; + this.passCreated = TypeScript.CompilerDiagnostics.analysisPass; + this.preComments = null; + this.postComments = null; + this.docComments = null; + this.isParenthesized = false; + } + AST.prototype.isExpression = function () { + return false; + }; + AST.prototype.isStatementOrExpression = function () { + return false; + }; + AST.prototype.isCompoundStatement = function () { + return false; + }; + AST.prototype.isLeaf = function () { + return this.isStatementOrExpression() && (!this.isCompoundStatement()); + }; + AST.prototype.isDeclaration = function () { + return false; + }; + AST.prototype.typeCheck = function (typeFlow) { + switch(this.nodeType) { + case TypeScript.NodeType.Error: + case TypeScript.NodeType.EmptyExpr: + this.type = typeFlow.anyType; + break; + case TypeScript.NodeType.This: + return typeFlow.typeCheckThis(this); + case TypeScript.NodeType.Null: + this.type = typeFlow.nullType; + break; + case TypeScript.NodeType.False: + case TypeScript.NodeType.True: + this.type = typeFlow.booleanType; + break; + case TypeScript.NodeType.Super: + return typeFlow.typeCheckSuper(this); + case TypeScript.NodeType.EndCode: + case TypeScript.NodeType.Empty: + case TypeScript.NodeType.Void: + this.type = typeFlow.voidType; + break; + default: + throw new Error("please implement in derived class"); + } + return this; + }; + AST.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + switch(this.nodeType) { + case TypeScript.NodeType.This: + emitter.recordSourceMappingStart(this); + if(emitter.thisFnc && (TypeScript.hasFlag(emitter.thisFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction))) { + emitter.writeToOutput("_this"); + } else { + emitter.writeToOutput("this"); + } + emitter.recordSourceMappingEnd(this); + break; + case TypeScript.NodeType.Null: + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("null"); + emitter.recordSourceMappingEnd(this); + break; + case TypeScript.NodeType.False: + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("false"); + emitter.recordSourceMappingEnd(this); + break; + case TypeScript.NodeType.True: + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("true"); + emitter.recordSourceMappingEnd(this); + break; + case TypeScript.NodeType.Super: + emitter.recordSourceMappingStart(this); + emitter.emitSuperReference(); + emitter.recordSourceMappingEnd(this); + break; + case TypeScript.NodeType.EndCode: + case TypeScript.NodeType.Error: + case TypeScript.NodeType.EmptyExpr: + break; + case TypeScript.NodeType.Empty: + emitter.recordSourceMappingStart(this); + emitter.recordSourceMappingEnd(this); + break; + case TypeScript.NodeType.Void: + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("void "); + emitter.recordSourceMappingEnd(this); + break; + default: + throw new Error("please implement in derived class"); + } + emitter.emitParensAndCommentsInPlace(this, false); + }; + AST.prototype.print = function (context) { + context.startLine(); + var lineCol = { + line: -1, + col: -1 + }; + var limLineCol = { + line: -1, + col: -1 + }; + if(context.parser !== null) { + context.parser.getSourceLineCol(lineCol, this.minChar); + context.parser.getSourceLineCol(limLineCol, this.limChar); + context.write("(" + lineCol.line + "," + lineCol.col + ")--" + "(" + limLineCol.line + "," + limLineCol.col + "): "); + } + var lab = this.printLabel(); + if(TypeScript.hasFlag(this.flags, TypeScript.ASTFlags.Error)) { + lab += " (Error)"; + } + context.writeLine(lab); + }; + AST.prototype.printLabel = function () { + if(TypeScript.nodeTypeTable[this.nodeType] !== undefined) { + return TypeScript.nodeTypeTable[this.nodeType]; + } else { + return (TypeScript.NodeType)._map[this.nodeType]; + } + }; + AST.prototype.addToControlFlow = function (context) { + context.walker.options.goChildren = false; + context.addContent(this); + }; + AST.prototype.netFreeUses = function (container, freeUses) { + }; + AST.prototype.treeViewLabel = function () { + return (TypeScript.NodeType)._map[this.nodeType]; + }; + AST.getResolvedIdentifierName = function getResolvedIdentifierName(name) { + if(!name) { + return ""; + } + var resolved = ""; + var start = 0; + var i = 0; + while(i <= name.length - 6) { + if(name.charAt(i) == '\\' && name.charAt(i + 1) == 'u') { + var charCode = parseInt(name.substr(i + 2, 4), 16); + resolved += name.substr(start, i - start); + resolved += String.fromCharCode(charCode); + i += 6; + start = i; + continue; + } + i++; + } + resolved += name.substring(start); + return resolved; + }; + AST.prototype.getDocComments = function () { + if(!this.isDeclaration() || !this.preComments || this.preComments.length == 0) { + return []; + } + if(!this.docComments) { + var preCommentsLength = this.preComments.length; + var docComments = []; + for(var i = preCommentsLength - 1; i >= 0; i--) { + if(this.preComments[i].isDocComment()) { + var prevDocComment = docComments.length > 0 ? docComments[docComments.length - 1] : null; + if(prevDocComment == null || (this.preComments[i].limLine == prevDocComment.minLine || this.preComments[i].limLine + 1 == prevDocComment.minLine)) { + docComments.push(this.preComments[i]); + continue; + } + } + break; + } + this.docComments = docComments.reverse(); + } + return this.docComments; + }; + return AST; + })(ASTSpan); + TypeScript.AST = AST; + var IncompleteAST = (function (_super) { + __extends(IncompleteAST, _super); + function IncompleteAST(min, lim) { + _super.call(this, TypeScript.NodeType.Error); + this.minChar = min; + this.limChar = lim; + } + return IncompleteAST; + })(AST); + TypeScript.IncompleteAST = IncompleteAST; + var ASTList = (function (_super) { + __extends(ASTList, _super); + function ASTList() { + _super.call(this, TypeScript.NodeType.List); + this.enclosingScope = null; + this.members = new Array(); + } + ASTList.prototype.addToControlFlow = function (context) { + var len = this.members.length; + for(var i = 0; i < len; i++) { + if(context.noContinuation) { + context.addUnreachable(this.members[i]); + break; + } else { + this.members[i] = context.walk(this.members[i], this); + } + } + context.walker.options.goChildren = false; + }; + ASTList.prototype.append = function (ast) { + this.members[this.members.length] = ast; + return this; + }; + ASTList.prototype.appendAll = function (ast) { + if(ast.nodeType == TypeScript.NodeType.List) { + var list = ast; + for(var i = 0, len = list.members.length; i < len; i++) { + this.append(list.members[i]); + } + } else { + this.append(ast); + } + return this; + }; + ASTList.prototype.emit = function (emitter, tokenId, startLine) { + emitter.recordSourceMappingStart(this); + emitter.emitJavascriptList(this, null, TypeScript.TokenID.Semicolon, startLine, false, false); + emitter.recordSourceMappingEnd(this); + }; + ASTList.prototype.typeCheck = function (typeFlow) { + var len = this.members.length; + typeFlow.nestingLevel++; + for(var i = 0; i < len; i++) { + if(this.members[i]) { + this.members[i] = this.members[i].typeCheck(typeFlow); + } + } + typeFlow.nestingLevel--; + return this; + }; + return ASTList; + })(AST); + TypeScript.ASTList = ASTList; + var Identifier = (function (_super) { + __extends(Identifier, _super); + function Identifier(actualText, hasEscapeSequence) { + _super.call(this, TypeScript.NodeType.Name); + this.actualText = actualText; + this.hasEscapeSequence = hasEscapeSequence; + this.sym = null; + this.cloId = -1; + this.setText(actualText, hasEscapeSequence); + } + Identifier.prototype.setText = function (actualText, hasEscapeSequence) { + this.actualText = actualText; + if(hasEscapeSequence) { + this.text = AST.getResolvedIdentifierName(actualText); + } else { + this.text = actualText; + } + }; + Identifier.prototype.isMissing = function () { + return false; + }; + Identifier.prototype.isLeaf = function () { + return true; + }; + Identifier.prototype.treeViewLabel = function () { + return "id: " + this.actualText; + }; + Identifier.prototype.printLabel = function () { + if(this.actualText) { + return "id: " + this.actualText; + } else { + return "name node"; + } + }; + Identifier.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckName(this); + }; + Identifier.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitJavascriptName(this, true); + }; + Identifier.fromToken = function fromToken(token) { + return new Identifier(token.getText(), (token).hasEscapeSequence); + }; + return Identifier; + })(AST); + TypeScript.Identifier = Identifier; + var MissingIdentifier = (function (_super) { + __extends(MissingIdentifier, _super); + function MissingIdentifier() { + _super.call(this, "__missing"); + } + MissingIdentifier.prototype.isMissing = function () { + return true; + }; + MissingIdentifier.prototype.emit = function (emitter, tokenId, startLine) { + }; + return MissingIdentifier; + })(Identifier); + TypeScript.MissingIdentifier = MissingIdentifier; + var Label = (function (_super) { + __extends(Label, _super); + function Label(id) { + _super.call(this, TypeScript.NodeType.Label); + this.id = id; + } + Label.prototype.printLabel = function () { + return this.id.actualText + ":"; + }; + Label.prototype.typeCheck = function (typeFlow) { + this.type = typeFlow.voidType; + return this; + }; + Label.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.recordSourceMappingStart(this.id); + emitter.writeToOutput(this.id.actualText); + emitter.recordSourceMappingEnd(this.id); + emitter.writeLineToOutput(":"); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return Label; + })(AST); + TypeScript.Label = Label; + var Expression = (function (_super) { + __extends(Expression, _super); + function Expression(nodeType) { + _super.call(this, nodeType); + } + Expression.prototype.isExpression = function () { + return true; + }; + Expression.prototype.isStatementOrExpression = function () { + return true; + }; + return Expression; + })(AST); + TypeScript.Expression = Expression; + var UnaryExpression = (function (_super) { + __extends(UnaryExpression, _super); + function UnaryExpression(nodeType, operand) { + _super.call(this, nodeType); + this.operand = operand; + this.targetType = null; + this.castTerm = null; + } + UnaryExpression.prototype.addToControlFlow = function (context) { + _super.prototype.addToControlFlow.call(this, context); + if(this.nodeType == TypeScript.NodeType.Throw) { + context.returnStmt(); + } + }; + UnaryExpression.prototype.typeCheck = function (typeFlow) { + switch(this.nodeType) { + case TypeScript.NodeType.Not: + return typeFlow.typeCheckBitNot(this); + case TypeScript.NodeType.LogNot: + return typeFlow.typeCheckLogNot(this); + case TypeScript.NodeType.Pos: + case TypeScript.NodeType.Neg: + return typeFlow.typeCheckUnaryNumberOperator(this); + case TypeScript.NodeType.IncPost: + case TypeScript.NodeType.IncPre: + case TypeScript.NodeType.DecPost: + case TypeScript.NodeType.DecPre: + return typeFlow.typeCheckIncOrDec(this); + case TypeScript.NodeType.ArrayLit: + typeFlow.typeCheckArrayLit(this); + return this; + case TypeScript.NodeType.ObjectLit: + typeFlow.typeCheckObjectLit(this); + return this; + case TypeScript.NodeType.Throw: + this.operand = typeFlow.typeCheck(this.operand); + this.type = typeFlow.voidType; + return this; + case TypeScript.NodeType.Typeof: + this.operand = typeFlow.typeCheck(this.operand); + this.type = typeFlow.stringType; + return this; + case TypeScript.NodeType.Delete: + this.operand = typeFlow.typeCheck(this.operand); + this.type = typeFlow.booleanType; + break; + case TypeScript.NodeType.TypeAssertion: + this.castTerm = typeFlow.typeCheck(this.castTerm); + var applyTargetType = !this.operand.isParenthesized; + var targetType = applyTargetType ? this.castTerm.type : null; + typeFlow.checker.typeCheckWithContextualType(targetType, typeFlow.checker.inProvisionalTypecheckMode(), true, this.operand); + typeFlow.castWithCoercion(this.operand, this.castTerm.type, false, true); + this.type = this.castTerm.type; + return this; + case TypeScript.NodeType.Void: + this.operand = typeFlow.typeCheck(this.operand); + this.type = typeFlow.checker.undefinedType; + break; + default: + throw new Error("please implement in derived class"); + } + return this; + }; + UnaryExpression.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + switch(this.nodeType) { + case TypeScript.NodeType.IncPost: + emitter.emitJavascript(this.operand, TypeScript.TokenID.PlusPlus, false); + emitter.writeToOutput("++"); + break; + case TypeScript.NodeType.LogNot: + emitter.writeToOutput("!"); + emitter.emitJavascript(this.operand, TypeScript.TokenID.Exclamation, false); + break; + case TypeScript.NodeType.DecPost: + emitter.emitJavascript(this.operand, TypeScript.TokenID.MinusMinus, false); + emitter.writeToOutput("--"); + break; + case TypeScript.NodeType.ObjectLit: + emitter.emitObjectLiteral(this.operand); + break; + case TypeScript.NodeType.ArrayLit: + emitter.emitArrayLiteral(this.operand); + break; + case TypeScript.NodeType.Not: + emitter.writeToOutput("~"); + emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); + break; + case TypeScript.NodeType.Neg: + emitter.writeToOutput("-"); + if(this.operand.nodeType == TypeScript.NodeType.Neg) { + this.operand.isParenthesized = true; + } + emitter.emitJavascript(this.operand, TypeScript.TokenID.Minus, false); + break; + case TypeScript.NodeType.Pos: + emitter.writeToOutput("+"); + if(this.operand.nodeType == TypeScript.NodeType.Pos) { + this.operand.isParenthesized = true; + } + emitter.emitJavascript(this.operand, TypeScript.TokenID.Plus, false); + break; + case TypeScript.NodeType.IncPre: + emitter.writeToOutput("++"); + emitter.emitJavascript(this.operand, TypeScript.TokenID.PlusPlus, false); + break; + case TypeScript.NodeType.DecPre: + emitter.writeToOutput("--"); + emitter.emitJavascript(this.operand, TypeScript.TokenID.MinusMinus, false); + break; + case TypeScript.NodeType.Throw: + emitter.writeToOutput("throw "); + emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); + emitter.writeToOutput(";"); + break; + case TypeScript.NodeType.Typeof: + emitter.writeToOutput("typeof "); + emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); + break; + case TypeScript.NodeType.Delete: + emitter.writeToOutput("delete "); + emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); + break; + case TypeScript.NodeType.Void: + emitter.writeToOutput("void "); + emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); + break; + case TypeScript.NodeType.TypeAssertion: + emitter.emitJavascript(this.operand, TypeScript.TokenID.Tilde, false); + break; + default: + throw new Error("please implement in derived class"); + } + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return UnaryExpression; + })(Expression); + TypeScript.UnaryExpression = UnaryExpression; + var CallExpression = (function (_super) { + __extends(CallExpression, _super); + function CallExpression(nodeType, target, arguments) { + _super.call(this, nodeType); + this.target = target; + this.arguments = arguments; + this.signature = null; + this.minChar = this.target.minChar; + } + CallExpression.prototype.typeCheck = function (typeFlow) { + if(this.nodeType == TypeScript.NodeType.New) { + return typeFlow.typeCheckNew(this); + } else { + return typeFlow.typeCheckCall(this); + } + }; + CallExpression.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + if(this.nodeType == TypeScript.NodeType.New) { + emitter.emitNew(this.target, this.arguments); + } else { + emitter.emitCall(this, this.target, this.arguments); + } + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return CallExpression; + })(Expression); + TypeScript.CallExpression = CallExpression; + var BinaryExpression = (function (_super) { + __extends(BinaryExpression, _super); + function BinaryExpression(nodeType, operand1, operand2) { + _super.call(this, nodeType); + this.operand1 = operand1; + this.operand2 = operand2; + } + BinaryExpression.prototype.typeCheck = function (typeFlow) { + switch(this.nodeType) { + case TypeScript.NodeType.Dot: + return typeFlow.typeCheckDotOperator(this); + case TypeScript.NodeType.Asg: + return typeFlow.typeCheckAsgOperator(this); + case TypeScript.NodeType.Add: + case TypeScript.NodeType.Sub: + case TypeScript.NodeType.Mul: + case TypeScript.NodeType.Div: + case TypeScript.NodeType.Mod: + case TypeScript.NodeType.Or: + case TypeScript.NodeType.And: + return typeFlow.typeCheckArithmeticOperator(this, false); + case TypeScript.NodeType.Xor: + return typeFlow.typeCheckBitwiseOperator(this, false); + case TypeScript.NodeType.Ne: + case TypeScript.NodeType.Eq: + var text; + if(typeFlow.checker.styleSettings.eqeqeq) { + text = TypeScript.nodeTypeTable[this.nodeType]; + typeFlow.checker.errorReporter.styleError(this, "use of " + text); + } else if(typeFlow.checker.styleSettings.eqnull) { + text = TypeScript.nodeTypeTable[this.nodeType]; + if((this.operand2 !== null) && (this.operand2.nodeType == TypeScript.NodeType.Null)) { + typeFlow.checker.errorReporter.styleError(this, "use of " + text + " to compare with null"); + } + } + case TypeScript.NodeType.Eqv: + case TypeScript.NodeType.NEqv: + case TypeScript.NodeType.Lt: + case TypeScript.NodeType.Le: + case TypeScript.NodeType.Ge: + case TypeScript.NodeType.Gt: + return typeFlow.typeCheckBooleanOperator(this); + case TypeScript.NodeType.Index: + return typeFlow.typeCheckIndex(this); + case TypeScript.NodeType.Member: + this.type = typeFlow.voidType; + return this; + case TypeScript.NodeType.LogOr: + return typeFlow.typeCheckLogOr(this); + case TypeScript.NodeType.LogAnd: + return typeFlow.typeCheckLogAnd(this); + case TypeScript.NodeType.AsgAdd: + case TypeScript.NodeType.AsgSub: + case TypeScript.NodeType.AsgMul: + case TypeScript.NodeType.AsgDiv: + case TypeScript.NodeType.AsgMod: + case TypeScript.NodeType.AsgOr: + case TypeScript.NodeType.AsgAnd: + return typeFlow.typeCheckArithmeticOperator(this, true); + case TypeScript.NodeType.AsgXor: + return typeFlow.typeCheckBitwiseOperator(this, true); + case TypeScript.NodeType.Lsh: + case TypeScript.NodeType.Rsh: + case TypeScript.NodeType.Rs2: + return typeFlow.typeCheckShift(this, false); + case TypeScript.NodeType.AsgLsh: + case TypeScript.NodeType.AsgRsh: + case TypeScript.NodeType.AsgRs2: + return typeFlow.typeCheckShift(this, true); + case TypeScript.NodeType.Comma: + return typeFlow.typeCheckCommaOperator(this); + case TypeScript.NodeType.InstOf: + return typeFlow.typeCheckInstOf(this); + case TypeScript.NodeType.In: + return typeFlow.typeCheckInOperator(this); + case TypeScript.NodeType.From: + typeFlow.checker.errorReporter.simpleError(this, "Illegal use of 'from' keyword in binary expression"); + break; + default: + throw new Error("please implement in derived class"); + } + return this; + }; + BinaryExpression.prototype.emit = function (emitter, tokenId, startLine) { + var binTokenId = TypeScript.nodeTypeToTokTable[this.nodeType]; + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + if(binTokenId != undefined) { + emitter.emitJavascript(this.operand1, binTokenId, false); + if(TypeScript.tokenTable[binTokenId].text == "instanceof") { + emitter.writeToOutput(" instanceof "); + } else if(TypeScript.tokenTable[binTokenId].text == "in") { + emitter.writeToOutput(" in "); + } else { + emitter.writeToOutputTrimmable(" " + TypeScript.tokenTable[binTokenId].text + " "); + } + emitter.emitJavascript(this.operand2, binTokenId, false); + } else { + switch(this.nodeType) { + case TypeScript.NodeType.Dot: + if(!emitter.tryEmitConstant(this)) { + emitter.emitJavascript(this.operand1, TypeScript.TokenID.Dot, false); + emitter.writeToOutput("."); + emitter.emitJavascriptName(this.operand2, false); + } + break; + case TypeScript.NodeType.Index: + emitter.emitIndex(this.operand1, this.operand2); + break; + case TypeScript.NodeType.Member: + if(this.operand2.nodeType == TypeScript.NodeType.FuncDecl && (this.operand2).isAccessor()) { + var funcDecl = this.operand2; + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { + emitter.writeToOutput("get "); + } else { + emitter.writeToOutput("set "); + } + emitter.emitJavascript(this.operand1, TypeScript.TokenID.Colon, false); + } else { + emitter.emitJavascript(this.operand1, TypeScript.TokenID.Colon, false); + emitter.writeToOutputTrimmable(": "); + } + emitter.emitJavascript(this.operand2, TypeScript.TokenID.Comma, false); + break; + case TypeScript.NodeType.Comma: + emitter.emitJavascript(this.operand1, TypeScript.TokenID.Comma, false); + if(emitter.emitState.inObjectLiteral) { + emitter.writeLineToOutput(", "); + } else { + emitter.writeToOutput(","); + } + emitter.emitJavascript(this.operand2, TypeScript.TokenID.Comma, false); + break; + case TypeScript.NodeType.Is: + throw new Error("should be de-sugared during type check"); + default: + throw new Error("please implement in derived class"); + } + } + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return BinaryExpression; + })(Expression); + TypeScript.BinaryExpression = BinaryExpression; + var ConditionalExpression = (function (_super) { + __extends(ConditionalExpression, _super); + function ConditionalExpression(operand1, operand2, operand3) { + _super.call(this, TypeScript.NodeType.ConditionalExpression); + this.operand1 = operand1; + this.operand2 = operand2; + this.operand3 = operand3; + } + ConditionalExpression.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckQMark(this); + }; + ConditionalExpression.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.emitJavascript(this.operand1, TypeScript.TokenID.Question, false); + emitter.writeToOutput(" ? "); + emitter.emitJavascript(this.operand2, TypeScript.TokenID.Question, false); + emitter.writeToOutput(" : "); + emitter.emitJavascript(this.operand3, TypeScript.TokenID.Question, false); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return ConditionalExpression; + })(Expression); + TypeScript.ConditionalExpression = ConditionalExpression; + var NumberLiteral = (function (_super) { + __extends(NumberLiteral, _super); + function NumberLiteral(value, text) { + _super.call(this, TypeScript.NodeType.NumberLit); + this.value = value; + this.text = text; + } + NumberLiteral.prototype.typeCheck = function (typeFlow) { + this.type = typeFlow.doubleType; + return this; + }; + NumberLiteral.prototype.treeViewLabel = function () { + return "num: " + this.printLabel(); + }; + NumberLiteral.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput(this.text); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + NumberLiteral.prototype.printLabel = function () { + return this.text; + }; + return NumberLiteral; + })(Expression); + TypeScript.NumberLiteral = NumberLiteral; + var RegexLiteral = (function (_super) { + __extends(RegexLiteral, _super); + function RegexLiteral(text) { + _super.call(this, TypeScript.NodeType.Regex); + this.text = text; + } + RegexLiteral.prototype.typeCheck = function (typeFlow) { + this.type = typeFlow.regexType; + return this; + }; + RegexLiteral.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput(this.text); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return RegexLiteral; + })(Expression); + TypeScript.RegexLiteral = RegexLiteral; + var StringLiteral = (function (_super) { + __extends(StringLiteral, _super); + function StringLiteral(text) { + _super.call(this, TypeScript.NodeType.QString); + this.text = text; + } + StringLiteral.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.emitStringLiteral(this.text); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + StringLiteral.prototype.typeCheck = function (typeFlow) { + this.type = typeFlow.stringType; + return this; + }; + StringLiteral.prototype.treeViewLabel = function () { + return "st: " + this.text; + }; + StringLiteral.prototype.printLabel = function () { + return this.text; + }; + return StringLiteral; + })(Expression); + TypeScript.StringLiteral = StringLiteral; + var ModuleElement = (function (_super) { + __extends(ModuleElement, _super); + function ModuleElement(nodeType) { + _super.call(this, nodeType); + } + return ModuleElement; + })(AST); + TypeScript.ModuleElement = ModuleElement; + var ImportDeclaration = (function (_super) { + __extends(ImportDeclaration, _super); + function ImportDeclaration(id, alias) { + _super.call(this, TypeScript.NodeType.ImportDeclaration); + this.id = id; + this.alias = alias; + this.varFlags = TypeScript.VarFlags.None; + this.isDynamicImport = false; + } + ImportDeclaration.prototype.isStatementOrExpression = function () { + return true; + }; + ImportDeclaration.prototype.isDeclaration = function () { + return true; + }; + ImportDeclaration.prototype.emit = function (emitter, tokenId, startLine) { + var mod = this.alias.type; + if(!this.isDynamicImport || (this.id.sym && !(this.id.sym).onlyReferencedAsTypeRef)) { + var prevModAliasId = emitter.modAliasId; + var prevFirstModAlias = emitter.firstModAlias; + emitter.recordSourceMappingStart(this); + emitter.emitParensAndCommentsInPlace(this, true); + emitter.writeToOutput("var " + this.id.actualText + " = "); + emitter.modAliasId = this.id.actualText; + emitter.firstModAlias = this.firstAliasedModToString(); + emitter.emitJavascript(this.alias, TypeScript.TokenID.Tilde, false); + if(!this.isDynamicImport) { + emitter.writeToOutput(";"); + } + emitter.emitParensAndCommentsInPlace(this, false); + emitter.recordSourceMappingEnd(this); + emitter.modAliasId = prevModAliasId; + emitter.firstModAlias = prevFirstModAlias; + } + }; + ImportDeclaration.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckImportDecl(this); + }; + ImportDeclaration.prototype.getAliasName = function (aliasAST) { + if (typeof aliasAST === "undefined") { aliasAST = this.alias; } + if(aliasAST.nodeType == TypeScript.NodeType.Name) { + return (aliasAST).actualText; + } else { + var dotExpr = aliasAST; + return this.getAliasName(dotExpr.operand1) + "." + this.getAliasName(dotExpr.operand2); + } + }; + ImportDeclaration.prototype.firstAliasedModToString = function () { + if(this.alias.nodeType == TypeScript.NodeType.Name) { + return (this.alias).actualText; + } else { + var dotExpr = this.alias; + var firstMod = dotExpr.operand1; + return firstMod.actualText; + } + }; + return ImportDeclaration; + })(ModuleElement); + TypeScript.ImportDeclaration = ImportDeclaration; + var BoundDecl = (function (_super) { + __extends(BoundDecl, _super); + function BoundDecl(id, nodeType, nestingLevel) { + _super.call(this, nodeType); + this.id = id; + this.nestingLevel = nestingLevel; + this.init = null; + this.typeExpr = null; + this.varFlags = TypeScript.VarFlags.None; + this.sym = null; + } + BoundDecl.prototype.isDeclaration = function () { + return true; + }; + BoundDecl.prototype.isStatementOrExpression = function () { + return true; + }; + BoundDecl.prototype.isPrivate = function () { + return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Private); + }; + BoundDecl.prototype.isPublic = function () { + return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Public); + }; + BoundDecl.prototype.isProperty = function () { + return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Property); + }; + BoundDecl.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckBoundDecl(this); + }; + BoundDecl.prototype.printLabel = function () { + return this.treeViewLabel(); + }; + return BoundDecl; + })(AST); + TypeScript.BoundDecl = BoundDecl; + var VarDecl = (function (_super) { + __extends(VarDecl, _super); + function VarDecl(id, nest) { + _super.call(this, id, TypeScript.NodeType.VarDecl, nest); + } + VarDecl.prototype.isAmbient = function () { + return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Ambient); + }; + VarDecl.prototype.isExported = function () { + return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Exported); + }; + VarDecl.prototype.isStatic = function () { + return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Static); + }; + VarDecl.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitJavascriptVarDecl(this, tokenId); + }; + VarDecl.prototype.treeViewLabel = function () { + return "var " + this.id.actualText; + }; + return VarDecl; + })(BoundDecl); + TypeScript.VarDecl = VarDecl; + var ArgDecl = (function (_super) { + __extends(ArgDecl, _super); + function ArgDecl(id) { + _super.call(this, id, TypeScript.NodeType.ArgDecl, 0); + this.isOptional = false; + this.parameterPropertySym = null; + } + ArgDecl.prototype.isOptionalArg = function () { + return this.isOptional || this.init; + }; + ArgDecl.prototype.treeViewLabel = function () { + return "arg: " + this.id.actualText; + }; + ArgDecl.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput(this.id.actualText); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return ArgDecl; + })(BoundDecl); + TypeScript.ArgDecl = ArgDecl; + var internalId = 0; + var FuncDecl = (function (_super) { + __extends(FuncDecl, _super); + function FuncDecl(name, bod, isConstructor, arguments, vars, scopes, statics, nodeType) { + _super.call(this, nodeType); + this.name = name; + this.bod = bod; + this.isConstructor = isConstructor; + this.arguments = arguments; + this.vars = vars; + this.scopes = scopes; + this.statics = statics; + this.hint = null; + this.fncFlags = TypeScript.FncFlags.None; + this.returnTypeAnnotation = null; + this.variableArgList = false; + this.jumpRefs = null; + this.internalNameCache = null; + this.tmp1Declared = false; + this.enclosingFnc = null; + this.freeVariables = []; + this.unitIndex = -1; + this.classDecl = null; + this.boundToProperty = null; + this.isOverload = false; + this.innerStaticFuncs = []; + this.isInlineCallLiteral = false; + this.accessorSymbol = null; + this.leftCurlyCount = 0; + this.rightCurlyCount = 0; + this.returnStatementsWithExpressions = []; + this.scopeType = null; + this.endingToken = null; + this.constructorSpan = null; + } + FuncDecl.prototype.isDeclaration = function () { + return true; + }; + FuncDecl.prototype.internalName = function () { + if(this.internalNameCache == null) { + var extName = this.getNameText(); + if(extName) { + this.internalNameCache = "_internal_" + extName; + } else { + this.internalNameCache = "_internal_" + internalId++; + } + } + return this.internalNameCache; + }; + FuncDecl.prototype.hasSelfReference = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.HasSelfReference); + }; + FuncDecl.prototype.setHasSelfReference = function () { + this.fncFlags |= TypeScript.FncFlags.HasSelfReference; + }; + FuncDecl.prototype.hasSuperReferenceInFatArrowFunction = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.HasSuperReferenceInFatArrowFunction); + }; + FuncDecl.prototype.setHasSuperReferenceInFatArrowFunction = function () { + this.fncFlags |= TypeScript.FncFlags.HasSuperReferenceInFatArrowFunction; + }; + FuncDecl.prototype.addCloRef = function (id, sym) { + if(this.envids == null) { + this.envids = new Array(); + } + this.envids[this.envids.length] = id; + var outerFnc = this.enclosingFnc; + if(sym) { + while(outerFnc && (outerFnc.type.symbol != sym.container)) { + outerFnc.addJumpRef(sym); + outerFnc = outerFnc.enclosingFnc; + } + } + return this.envids.length - 1; + }; + FuncDecl.prototype.addJumpRef = function (sym) { + if(this.jumpRefs == null) { + this.jumpRefs = new Array(); + } + var id = new Identifier(sym.name); + this.jumpRefs[this.jumpRefs.length] = id; + id.sym = sym; + id.cloId = this.addCloRef(id, null); + }; + FuncDecl.prototype.buildControlFlow = function () { + var entry = new TypeScript.BasicBlock(); + var exit = new TypeScript.BasicBlock(); + var context = new TypeScript.ControlFlowContext(entry, exit); + var controlFlowPrefix = function (ast, parent, walker) { + ast.addToControlFlow(walker.state); + return ast; + }; + var walker = TypeScript.getAstWalkerFactory().getWalker(controlFlowPrefix, null, null, context); + context.walker = walker; + walker.walk(this.bod, this); + return context; + }; + FuncDecl.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckFunction(this); + }; + FuncDecl.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitJavascriptFunction(this); + }; + FuncDecl.prototype.getNameText = function () { + if(this.name) { + return this.name.actualText; + } else { + return this.hint; + } + }; + FuncDecl.prototype.isMethod = function () { + return (this.fncFlags & TypeScript.FncFlags.Method) != TypeScript.FncFlags.None; + }; + FuncDecl.prototype.isCallMember = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.CallMember); + }; + FuncDecl.prototype.isConstructMember = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.ConstructMember); + }; + FuncDecl.prototype.isIndexerMember = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.IndexerMember); + }; + FuncDecl.prototype.isSpecialFn = function () { + return this.isCallMember() || this.isIndexerMember() || this.isConstructMember(); + }; + FuncDecl.prototype.isAnonymousFn = function () { + return this.name === null; + }; + FuncDecl.prototype.isAccessor = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.GetAccessor) || TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.SetAccessor); + }; + FuncDecl.prototype.isGetAccessor = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.GetAccessor); + }; + FuncDecl.prototype.isSetAccessor = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.SetAccessor); + }; + FuncDecl.prototype.isAmbient = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Ambient); + }; + FuncDecl.prototype.isExported = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Exported); + }; + FuncDecl.prototype.isPrivate = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Private); + }; + FuncDecl.prototype.isPublic = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Public); + }; + FuncDecl.prototype.isStatic = function () { + return TypeScript.hasFlag(this.fncFlags, TypeScript.FncFlags.Static); + }; + FuncDecl.prototype.treeViewLabel = function () { + if(this.name == null) { + return "funcExpr"; + } else { + return "func: " + this.name.actualText; + } + }; + FuncDecl.prototype.ClearFlags = function () { + this.fncFlags = TypeScript.FncFlags.None; + }; + FuncDecl.prototype.isSignature = function () { + return (this.fncFlags & TypeScript.FncFlags.Signature) != TypeScript.FncFlags.None; + }; + return FuncDecl; + })(AST); + TypeScript.FuncDecl = FuncDecl; + var LocationInfo = (function () { + function LocationInfo(filename, lineMap, unitIndex) { + this.filename = filename; + this.lineMap = lineMap; + this.unitIndex = unitIndex; + } + return LocationInfo; + })(); + TypeScript.LocationInfo = LocationInfo; + TypeScript.unknownLocationInfo = new LocationInfo("unknown", null, -1); + var Script = (function (_super) { + __extends(Script, _super); + function Script(vars, scopes) { + _super.call(this, new Identifier("script"), null, false, null, vars, scopes, null, TypeScript.NodeType.Script); + this.locationInfo = null; + this.referencedFiles = []; + this.requiresGlobal = false; + this.requiresExtendsBlock = false; + this.isResident = false; + this.isDeclareFile = false; + this.hasBeenTypeChecked = false; + this.topLevelMod = null; + this.leftCurlyCount = 0; + this.rightCurlyCount = 0; + this.containsUnicodeChar = false; + this.containsUnicodeCharInComment = false; + this.externallyVisibleImportedSymbols = []; + this.vars = vars; + } + Script.prototype.setCachedEmitRequired = function (value) { + this.cachedEmitRequired = value; + return this.cachedEmitRequired; + }; + Script.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckScript(this); + }; + Script.prototype.treeViewLabel = function () { + return "Script"; + }; + Script.prototype.emitRequired = function (emitOptions) { + if(this.cachedEmitRequired != undefined) { + return this.cachedEmitRequired; + } + if(!this.isDeclareFile && !this.isResident && this.bod) { + if(this.bod.members.length == 0) { + return this.setCachedEmitRequired(true); + } + for(var i = 0, len = this.bod.members.length; i < len; i++) { + var stmt = this.bod.members[i]; + if(stmt.nodeType == TypeScript.NodeType.ModuleDeclaration) { + if(!TypeScript.hasFlag((stmt).modFlags, TypeScript.ModuleFlags.ShouldEmitModuleDecl | TypeScript.ModuleFlags.Ambient)) { + return this.setCachedEmitRequired(true); + } + } else if(stmt.nodeType == TypeScript.NodeType.ClassDeclaration) { + if(!TypeScript.hasFlag((stmt).varFlags, TypeScript.VarFlags.Ambient)) { + return this.setCachedEmitRequired(true); + } + } else if(stmt.nodeType == TypeScript.NodeType.VarDecl) { + if(!TypeScript.hasFlag((stmt).varFlags, TypeScript.VarFlags.Ambient)) { + return this.setCachedEmitRequired(true); + } + } else if(stmt.nodeType == TypeScript.NodeType.FuncDecl) { + if(!(stmt).isSignature()) { + return this.setCachedEmitRequired(true); + } + } else if(stmt.nodeType != TypeScript.NodeType.InterfaceDeclaration && stmt.nodeType != TypeScript.NodeType.Empty) { + return this.setCachedEmitRequired(true); + } + } + if(emitOptions.emitComments && ((this.bod.preComments && this.bod.preComments.length > 0) || (this.bod.postComments && this.bod.postComments.length > 0))) { + return this.setCachedEmitRequired(true); + } + } + return this.setCachedEmitRequired(false); + }; + Script.prototype.emit = function (emitter, tokenId, startLine) { + if(this.emitRequired(emitter.emitOptions)) { + emitter.emitJavascriptList(this.bod, null, TypeScript.TokenID.Semicolon, true, false, false, true, this.requiresExtendsBlock); + } + }; + Script.prototype.AddExternallyVisibleImportedSymbol = function (symbol, checker) { + if(this.isExternallyVisibleSymbol(symbol)) { + return; + } + if(!symbol.getType().symbol.isExternallyVisible(checker)) { + var quotes = ""; + var moduleName = symbol.getType().symbol.prettyName; + if(!TypeScript.isQuoted(moduleName)) { + quotes = "'"; + } + checker.errorReporter.simpleError(symbol.declAST, "Externally visible import statement uses non exported module " + quotes + moduleName + quotes); + } + this.externallyVisibleImportedSymbols.push(symbol); + }; + Script.prototype.isExternallyVisibleSymbol = function (symbol) { + for(var i = 0; i < this.externallyVisibleImportedSymbols.length; i++) { + if(this.externallyVisibleImportedSymbols[i] == symbol) { + return true; + } + } + return false; + }; + return Script; + })(FuncDecl); + TypeScript.Script = Script; + var NamedDeclaration = (function (_super) { + __extends(NamedDeclaration, _super); + function NamedDeclaration(nodeType, name, members) { + _super.call(this, nodeType); + this.name = name; + this.members = members; + this.leftCurlyCount = 0; + this.rightCurlyCount = 0; + } + NamedDeclaration.prototype.isDeclaration = function () { + return true; + }; + return NamedDeclaration; + })(ModuleElement); + TypeScript.NamedDeclaration = NamedDeclaration; + var ModuleDeclaration = (function (_super) { + __extends(ModuleDeclaration, _super); + function ModuleDeclaration(name, members, vars, endingToken) { + _super.call(this, TypeScript.NodeType.ModuleDeclaration, name, members); + this.endingToken = endingToken; + this.modFlags = TypeScript.ModuleFlags.ShouldEmitModuleDecl; + this.amdDependencies = []; + this.containsUnicodeChar = false; + this.containsUnicodeCharInComment = false; + this.vars = vars; + this.prettyName = this.name.actualText; + } + ModuleDeclaration.prototype.isExported = function () { + return TypeScript.hasFlag(this.modFlags, TypeScript.ModuleFlags.Exported); + }; + ModuleDeclaration.prototype.isAmbient = function () { + return TypeScript.hasFlag(this.modFlags, TypeScript.ModuleFlags.Ambient); + }; + ModuleDeclaration.prototype.isEnum = function () { + return TypeScript.hasFlag(this.modFlags, TypeScript.ModuleFlags.IsEnum); + }; + ModuleDeclaration.prototype.isWholeFile = function () { + return TypeScript.hasFlag(this.modFlags, TypeScript.ModuleFlags.IsWholeFile); + }; + ModuleDeclaration.prototype.recordNonInterface = function () { + this.modFlags &= ~TypeScript.ModuleFlags.ShouldEmitModuleDecl; + }; + ModuleDeclaration.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckModule(this); + }; + ModuleDeclaration.prototype.emit = function (emitter, tokenId, startLine) { + if(!TypeScript.hasFlag(this.modFlags, TypeScript.ModuleFlags.ShouldEmitModuleDecl)) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.emitJavascriptModule(this); + emitter.emitParensAndCommentsInPlace(this, false); + } + }; + return ModuleDeclaration; + })(NamedDeclaration); + TypeScript.ModuleDeclaration = ModuleDeclaration; + var TypeDeclaration = (function (_super) { + __extends(TypeDeclaration, _super); + function TypeDeclaration(nodeType, name, extendsList, implementsList, members) { + _super.call(this, nodeType, name, members); + this.extendsList = extendsList; + this.implementsList = implementsList; + this.varFlags = TypeScript.VarFlags.None; + } + TypeDeclaration.prototype.isExported = function () { + return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Exported); + }; + TypeDeclaration.prototype.isAmbient = function () { + return TypeScript.hasFlag(this.varFlags, TypeScript.VarFlags.Ambient); + }; + return TypeDeclaration; + })(NamedDeclaration); + TypeScript.TypeDeclaration = TypeDeclaration; + var ClassDeclaration = (function (_super) { + __extends(ClassDeclaration, _super); + function ClassDeclaration(name, members, extendsList, implementsList) { + _super.call(this, TypeScript.NodeType.ClassDeclaration, name, extendsList, implementsList, members); + this.knownMemberNames = { + }; + this.constructorDecl = null; + this.constructorNestingLevel = 0; + this.endingToken = null; + } + ClassDeclaration.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckClass(this); + }; + ClassDeclaration.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitJavascriptClass(this); + }; + return ClassDeclaration; + })(TypeDeclaration); + TypeScript.ClassDeclaration = ClassDeclaration; + var InterfaceDeclaration = (function (_super) { + __extends(InterfaceDeclaration, _super); + function InterfaceDeclaration(name, members, extendsList, implementsList) { + _super.call(this, TypeScript.NodeType.InterfaceDeclaration, name, extendsList, implementsList, members); + } + InterfaceDeclaration.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckInterface(this); + }; + InterfaceDeclaration.prototype.emit = function (emitter, tokenId, startLine) { + }; + return InterfaceDeclaration; + })(TypeDeclaration); + TypeScript.InterfaceDeclaration = InterfaceDeclaration; + var Statement = (function (_super) { + __extends(Statement, _super); + function Statement(nodeType) { + _super.call(this, nodeType); + this.flags |= TypeScript.ASTFlags.IsStatement; + } + Statement.prototype.isLoop = function () { + return false; + }; + Statement.prototype.isStatementOrExpression = function () { + return true; + }; + Statement.prototype.isCompoundStatement = function () { + return this.isLoop(); + }; + Statement.prototype.typeCheck = function (typeFlow) { + this.type = typeFlow.voidType; + return this; + }; + return Statement; + })(ModuleElement); + TypeScript.Statement = Statement; + var LabeledStatement = (function (_super) { + __extends(LabeledStatement, _super); + function LabeledStatement(labels, stmt) { + _super.call(this, TypeScript.NodeType.LabeledStatement); + this.labels = labels; + this.stmt = stmt; + } + LabeledStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + if(this.labels) { + var labelsLen = this.labels.members.length; + for(var i = 0; i < labelsLen; i++) { + this.labels.members[i].emit(emitter, tokenId, startLine); + } + } + this.stmt.emit(emitter, tokenId, true); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + LabeledStatement.prototype.typeCheck = function (typeFlow) { + typeFlow.typeCheck(this.labels); + this.stmt = this.stmt.typeCheck(typeFlow); + return this; + }; + LabeledStatement.prototype.addToControlFlow = function (context) { + var beforeBB = context.current; + var bb = new TypeScript.BasicBlock(); + context.current = bb; + beforeBB.addSuccessor(bb); + }; + return LabeledStatement; + })(Statement); + TypeScript.LabeledStatement = LabeledStatement; + var Block = (function (_super) { + __extends(Block, _super); + function Block(statements, isStatementBlock) { + _super.call(this, TypeScript.NodeType.Block); + this.statements = statements; + this.isStatementBlock = isStatementBlock; + } + Block.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + if(this.isStatementBlock) { + emitter.writeLineToOutput(" {"); + emitter.indenter.increaseIndent(); + } else { + emitter.setInVarBlock(this.statements.members.length); + } + var temp = emitter.setInObjectLiteral(false); + if(this.statements) { + emitter.emitJavascriptList(this.statements, null, TypeScript.TokenID.Semicolon, true, false, false); + } + if(this.isStatementBlock) { + emitter.indenter.decreaseIndent(); + emitter.emitIndent(); + emitter.writeToOutput("}"); + } + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + Block.prototype.addToControlFlow = function (context) { + var afterIfNeeded = new TypeScript.BasicBlock(); + context.pushStatement(this, context.current, afterIfNeeded); + if(this.statements) { + context.walk(this.statements, this); + } + context.walker.options.goChildren = false; + context.popStatement(); + if(afterIfNeeded.predecessors.length > 0) { + context.current.addSuccessor(afterIfNeeded); + context.current = afterIfNeeded; + } + }; + Block.prototype.typeCheck = function (typeFlow) { + if(!typeFlow.checker.styleSettings.emptyBlocks) { + if((this.statements === null) || (this.statements.members.length == 0)) { + typeFlow.checker.errorReporter.styleError(this, "empty block"); + } + } + typeFlow.typeCheck(this.statements); + return this; + }; + return Block; + })(Statement); + TypeScript.Block = Block; + var Jump = (function (_super) { + __extends(Jump, _super); + function Jump(nodeType) { + _super.call(this, nodeType); + this.target = null; + this.resolvedTarget = null; + } + Jump.prototype.hasExplicitTarget = function () { + return (this.target); + }; + Jump.prototype.setResolvedTarget = function (parser, stmt) { + if(stmt.isLoop()) { + this.resolvedTarget = stmt; + return true; + } + if(this.nodeType === TypeScript.NodeType.Continue) { + parser.reportParseError("continue statement applies only to loops"); + return false; + } else { + if((stmt.nodeType == TypeScript.NodeType.Switch) || this.hasExplicitTarget()) { + this.resolvedTarget = stmt; + return true; + } else { + parser.reportParseError("break statement with no label can apply only to a loop or switch statement"); + return false; + } + } + }; + Jump.prototype.addToControlFlow = function (context) { + _super.prototype.addToControlFlow.call(this, context); + context.unconditionalBranch(this.resolvedTarget, (this.nodeType == TypeScript.NodeType.Continue)); + }; + Jump.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + if(this.nodeType == TypeScript.NodeType.Break) { + emitter.writeToOutput("break"); + } else { + emitter.writeToOutput("continue"); + } + if(this.hasExplicitTarget()) { + emitter.writeToOutput(" " + this.target); + } + emitter.recordSourceMappingEnd(this); + emitter.writeToOutput(";"); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return Jump; + })(Statement); + TypeScript.Jump = Jump; + var WhileStatement = (function (_super) { + __extends(WhileStatement, _super); + function WhileStatement(cond) { + _super.call(this, TypeScript.NodeType.While); + this.cond = cond; + this.body = null; + } + WhileStatement.prototype.isLoop = function () { + return true; + }; + WhileStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + emitter.writeToOutput("while("); + emitter.emitJavascript(this.cond, TypeScript.TokenID.While, false); + emitter.writeToOutput(")"); + emitter.emitJavascriptStatements(this.body, false); + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + WhileStatement.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckWhile(this); + }; + WhileStatement.prototype.addToControlFlow = function (context) { + var loopHeader = context.current; + var loopStart = new TypeScript.BasicBlock(); + var afterLoop = new TypeScript.BasicBlock(); + loopHeader.addSuccessor(loopStart); + context.current = loopStart; + context.addContent(this.cond); + var condBlock = context.current; + var targetInfo = null; + if(this.body) { + context.current = new TypeScript.BasicBlock(); + condBlock.addSuccessor(context.current); + context.pushStatement(this, loopStart, afterLoop); + context.walk(this.body, this); + targetInfo = context.popStatement(); + } + if(!(context.noContinuation)) { + var loopEnd = context.current; + loopEnd.addSuccessor(loopStart); + } + context.current = afterLoop; + condBlock.addSuccessor(afterLoop); + context.noContinuation = false; + context.walker.options.goChildren = false; + }; + return WhileStatement; + })(Statement); + TypeScript.WhileStatement = WhileStatement; + var DoWhileStatement = (function (_super) { + __extends(DoWhileStatement, _super); + function DoWhileStatement() { + _super.call(this, TypeScript.NodeType.DoWhile); + this.body = null; + this.whileAST = null; + this.cond = null; + } + DoWhileStatement.prototype.isLoop = function () { + return true; + }; + DoWhileStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + emitter.writeToOutput("do"); + emitter.emitJavascriptStatements(this.body, true); + emitter.recordSourceMappingStart(this.whileAST); + emitter.writeToOutput("while"); + emitter.recordSourceMappingEnd(this.whileAST); + emitter.writeToOutput('('); + emitter.emitJavascript(this.cond, TypeScript.TokenID.CloseParen, false); + emitter.writeToOutput(")"); + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.writeToOutput(";"); + emitter.emitParensAndCommentsInPlace(this, false); + }; + DoWhileStatement.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckDoWhile(this); + }; + DoWhileStatement.prototype.addToControlFlow = function (context) { + var loopHeader = context.current; + var loopStart = new TypeScript.BasicBlock(); + var afterLoop = new TypeScript.BasicBlock(); + loopHeader.addSuccessor(loopStart); + context.current = loopStart; + var targetInfo = null; + if(this.body) { + context.pushStatement(this, loopStart, afterLoop); + context.walk(this.body, this); + targetInfo = context.popStatement(); + } + if(!(context.noContinuation)) { + var loopEnd = context.current; + loopEnd.addSuccessor(loopStart); + context.addContent(this.cond); + context.current = afterLoop; + loopEnd.addSuccessor(afterLoop); + } else { + context.addUnreachable(this.cond); + } + context.walker.options.goChildren = false; + }; + return DoWhileStatement; + })(Statement); + TypeScript.DoWhileStatement = DoWhileStatement; + var IfStatement = (function (_super) { + __extends(IfStatement, _super); + function IfStatement(cond) { + _super.call(this, TypeScript.NodeType.If); + this.cond = cond; + this.elseBod = null; + this.statement = new ASTSpan(); + } + IfStatement.prototype.isCompoundStatement = function () { + return true; + }; + IfStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + emitter.recordSourceMappingStart(this.statement); + emitter.writeToOutput("if("); + emitter.emitJavascript(this.cond, TypeScript.TokenID.If, false); + emitter.writeToOutput(")"); + emitter.recordSourceMappingEnd(this.statement); + emitter.emitJavascriptStatements(this.thenBod, true); + if(this.elseBod) { + if(this.elseBod.nodeType === TypeScript.NodeType.If) { + emitter.writeToOutput(" else "); + this.elseBod.emit(emitter, tokenId, false); + } else { + emitter.writeToOutput(" else"); + emitter.emitJavascriptStatements(this.elseBod, true); + } + } + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + IfStatement.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckIf(this); + }; + IfStatement.prototype.addToControlFlow = function (context) { + this.cond.addToControlFlow(context); + var afterIf = new TypeScript.BasicBlock(); + var beforeIf = context.current; + context.pushStatement(this, beforeIf, afterIf); + var hasContinuation = false; + context.current = new TypeScript.BasicBlock(); + beforeIf.addSuccessor(context.current); + context.walk(this.thenBod, this); + if(!context.noContinuation) { + hasContinuation = true; + context.current.addSuccessor(afterIf); + } + if(this.elseBod) { + context.current = new TypeScript.BasicBlock(); + context.noContinuation = false; + beforeIf.addSuccessor(context.current); + context.walk(this.elseBod, this); + if(!context.noContinuation) { + hasContinuation = true; + context.current.addSuccessor(afterIf); + } else { + if(hasContinuation) { + context.noContinuation = false; + } + } + } else { + beforeIf.addSuccessor(afterIf); + context.noContinuation = false; + hasContinuation = true; + } + var targetInfo = context.popStatement(); + if(afterIf.predecessors.length > 0) { + context.noContinuation = false; + hasContinuation = true; + } + if(hasContinuation) { + context.current = afterIf; + } + context.walker.options.goChildren = false; + }; + return IfStatement; + })(Statement); + TypeScript.IfStatement = IfStatement; + var ReturnStatement = (function (_super) { + __extends(ReturnStatement, _super); + function ReturnStatement() { + _super.call(this, TypeScript.NodeType.Return); + this.returnExpression = null; + } + ReturnStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + if(this.returnExpression) { + emitter.writeToOutput("return "); + emitter.emitJavascript(this.returnExpression, TypeScript.TokenID.Semicolon, false); + if(this.returnExpression.nodeType === TypeScript.NodeType.FuncDecl) { + emitter.writeToOutput(";"); + } + } else { + emitter.writeToOutput("return;"); + } + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + ReturnStatement.prototype.addToControlFlow = function (context) { + _super.prototype.addToControlFlow.call(this, context); + context.returnStmt(); + }; + ReturnStatement.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckReturn(this); + }; + return ReturnStatement; + })(Statement); + TypeScript.ReturnStatement = ReturnStatement; + var EndCode = (function (_super) { + __extends(EndCode, _super); + function EndCode() { + _super.call(this, TypeScript.NodeType.EndCode); + } + return EndCode; + })(AST); + TypeScript.EndCode = EndCode; + var ForInStatement = (function (_super) { + __extends(ForInStatement, _super); + function ForInStatement(lval, obj) { + _super.call(this, TypeScript.NodeType.ForIn); + this.lval = lval; + this.obj = obj; + this.statement = new ASTSpan(); + if(this.lval && (this.lval.nodeType == TypeScript.NodeType.VarDecl)) { + (this.lval).varFlags |= TypeScript.VarFlags.AutoInit; + } + } + ForInStatement.prototype.isLoop = function () { + return true; + }; + ForInStatement.prototype.isFiltered = function () { + if(this.body) { + var singleItem = null; + if(this.body.nodeType == TypeScript.NodeType.List) { + var stmts = this.body; + if(stmts.members.length == 1) { + singleItem = stmts.members[0]; + } + } else { + singleItem = this.body; + } + if(singleItem !== null) { + if(singleItem.nodeType == TypeScript.NodeType.Block) { + var block = singleItem; + if((block.statements !== null) && (block.statements.members.length == 1)) { + singleItem = block.statements.members[0]; + } + } + if(singleItem.nodeType == TypeScript.NodeType.If) { + var cond = (singleItem).cond; + if(cond.nodeType == TypeScript.NodeType.Call) { + var target = (cond).target; + if(target.nodeType == TypeScript.NodeType.Dot) { + var binex = target; + if((binex.operand1.nodeType == TypeScript.NodeType.Name) && (this.obj.nodeType == TypeScript.NodeType.Name) && ((binex.operand1).actualText == (this.obj).actualText)) { + var prop = binex.operand2; + if(prop.actualText == "hasOwnProperty") { + var args = (cond).arguments; + if((args !== null) && (args.members.length == 1)) { + var arg = args.members[0]; + if((arg.nodeType == TypeScript.NodeType.Name) && (this.lval.nodeType == TypeScript.NodeType.Name)) { + if(((this.lval).actualText) == (arg).actualText) { + return true; + } + } + } + } + } + } + } + } + } + } + return false; + }; + ForInStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + emitter.recordSourceMappingStart(this.statement); + emitter.writeToOutput("for("); + emitter.emitJavascript(this.lval, TypeScript.TokenID.For, false); + emitter.writeToOutput(" in "); + emitter.emitJavascript(this.obj, TypeScript.TokenID.For, false); + emitter.writeToOutput(")"); + emitter.recordSourceMappingEnd(this.statement); + emitter.emitJavascriptStatements(this.body, true); + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + ForInStatement.prototype.typeCheck = function (typeFlow) { + if(typeFlow.checker.styleSettings.forin) { + if(!this.isFiltered()) { + typeFlow.checker.errorReporter.styleError(this, "no hasOwnProperty filter"); + } + } + return typeFlow.typeCheckForIn(this); + }; + ForInStatement.prototype.addToControlFlow = function (context) { + if(this.lval) { + context.addContent(this.lval); + } + if(this.obj) { + context.addContent(this.obj); + } + var loopHeader = context.current; + var loopStart = new TypeScript.BasicBlock(); + var afterLoop = new TypeScript.BasicBlock(); + loopHeader.addSuccessor(loopStart); + context.current = loopStart; + if(this.body) { + context.pushStatement(this, loopStart, afterLoop); + context.walk(this.body, this); + context.popStatement(); + } + if(!(context.noContinuation)) { + var loopEnd = context.current; + loopEnd.addSuccessor(loopStart); + } + context.current = afterLoop; + context.noContinuation = false; + loopHeader.addSuccessor(afterLoop); + context.walker.options.goChildren = false; + }; + return ForInStatement; + })(Statement); + TypeScript.ForInStatement = ForInStatement; + var ForStatement = (function (_super) { + __extends(ForStatement, _super); + function ForStatement(init) { + _super.call(this, TypeScript.NodeType.For); + this.init = init; + } + ForStatement.prototype.isLoop = function () { + return true; + }; + ForStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + emitter.writeToOutput("for("); + if(this.init) { + if(this.init.nodeType != TypeScript.NodeType.List) { + emitter.emitJavascript(this.init, TypeScript.TokenID.For, false); + } else { + emitter.setInVarBlock((this.init).members.length); + emitter.emitJavascriptList(this.init, null, TypeScript.TokenID.For, false, false, false); + } + } + emitter.writeToOutput("; "); + emitter.emitJavascript(this.cond, TypeScript.TokenID.For, false); + emitter.writeToOutput("; "); + emitter.emitJavascript(this.incr, TypeScript.TokenID.For, false); + emitter.writeToOutput(")"); + emitter.emitJavascriptStatements(this.body, true); + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + ForStatement.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckFor(this); + }; + ForStatement.prototype.addToControlFlow = function (context) { + if(this.init) { + context.addContent(this.init); + } + var loopHeader = context.current; + var loopStart = new TypeScript.BasicBlock(); + var afterLoop = new TypeScript.BasicBlock(); + loopHeader.addSuccessor(loopStart); + context.current = loopStart; + var condBlock = null; + var continueTarget = loopStart; + var incrBB = null; + if(this.incr) { + incrBB = new TypeScript.BasicBlock(); + continueTarget = incrBB; + } + if(this.cond) { + condBlock = context.current; + context.addContent(this.cond); + context.current = new TypeScript.BasicBlock(); + condBlock.addSuccessor(context.current); + } + var targetInfo = null; + if(this.body) { + context.pushStatement(this, continueTarget, afterLoop); + context.walk(this.body, this); + targetInfo = context.popStatement(); + } + if(this.incr) { + if(context.noContinuation) { + if(incrBB.predecessors.length == 0) { + context.addUnreachable(this.incr); + } + } else { + context.current.addSuccessor(incrBB); + context.current = incrBB; + context.addContent(this.incr); + } + } + var loopEnd = context.current; + if(!(context.noContinuation)) { + loopEnd.addSuccessor(loopStart); + } + if(condBlock) { + condBlock.addSuccessor(afterLoop); + context.noContinuation = false; + } + if(afterLoop.predecessors.length > 0) { + context.noContinuation = false; + context.current = afterLoop; + } + context.walker.options.goChildren = false; + }; + return ForStatement; + })(Statement); + TypeScript.ForStatement = ForStatement; + var WithStatement = (function (_super) { + __extends(WithStatement, _super); + function WithStatement(expr) { + _super.call(this, TypeScript.NodeType.With); + this.expr = expr; + this.withSym = null; + } + WithStatement.prototype.isCompoundStatement = function () { + return true; + }; + WithStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("with ("); + if(this.expr) { + emitter.emitJavascript(this.expr, TypeScript.TokenID.With, false); + } + emitter.writeToOutput(")"); + emitter.emitJavascriptStatements(this.body, true); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + WithStatement.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckWith(this); + }; + return WithStatement; + })(Statement); + TypeScript.WithStatement = WithStatement; + var SwitchStatement = (function (_super) { + __extends(SwitchStatement, _super); + function SwitchStatement(val) { + _super.call(this, TypeScript.NodeType.Switch); + this.val = val; + this.defaultCase = null; + this.statement = new ASTSpan(); + } + SwitchStatement.prototype.isCompoundStatement = function () { + return true; + }; + SwitchStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + emitter.recordSourceMappingStart(this.statement); + emitter.writeToOutput("switch("); + emitter.emitJavascript(this.val, TypeScript.TokenID.Identifier, false); + emitter.writeToOutput(")"); + emitter.recordSourceMappingEnd(this.statement); + emitter.writeLineToOutput(" {"); + emitter.indenter.increaseIndent(); + var casesLen = this.caseList.members.length; + for(var i = 0; i < casesLen; i++) { + var caseExpr = this.caseList.members[i]; + emitter.emitJavascript(caseExpr, TypeScript.TokenID.Case, true); + } + emitter.indenter.decreaseIndent(); + emitter.emitIndent(); + emitter.writeToOutput("}"); + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + SwitchStatement.prototype.typeCheck = function (typeFlow) { + var len = this.caseList.members.length; + this.val = typeFlow.typeCheck(this.val); + for(var i = 0; i < len; i++) { + this.caseList.members[i] = typeFlow.typeCheck(this.caseList.members[i]); + } + this.defaultCase = typeFlow.typeCheck(this.defaultCase); + this.type = typeFlow.voidType; + return this; + }; + SwitchStatement.prototype.addToControlFlow = function (context) { + var condBlock = context.current; + context.addContent(this.val); + var execBlock = new TypeScript.BasicBlock(); + var afterSwitch = new TypeScript.BasicBlock(); + condBlock.addSuccessor(execBlock); + context.pushSwitch(execBlock); + context.current = execBlock; + context.pushStatement(this, execBlock, afterSwitch); + context.walk(this.caseList, this); + context.popSwitch(); + var targetInfo = context.popStatement(); + var hasCondContinuation = (this.defaultCase == null); + if(this.defaultCase == null) { + condBlock.addSuccessor(afterSwitch); + } + if(afterSwitch.predecessors.length > 0) { + context.noContinuation = false; + context.current = afterSwitch; + } else { + context.noContinuation = true; + } + context.walker.options.goChildren = false; + }; + return SwitchStatement; + })(Statement); + TypeScript.SwitchStatement = SwitchStatement; + var CaseStatement = (function (_super) { + __extends(CaseStatement, _super); + function CaseStatement() { + _super.call(this, TypeScript.NodeType.Case); + this.expr = null; + this.colonSpan = new ASTSpan(); + } + CaseStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + if(this.expr) { + emitter.writeToOutput("case "); + emitter.emitJavascript(this.expr, TypeScript.TokenID.Identifier, false); + } else { + emitter.writeToOutput("default"); + } + emitter.recordSourceMappingStart(this.colonSpan); + emitter.writeToOutput(":"); + emitter.recordSourceMappingEnd(this.colonSpan); + if(this.body.members.length == 1 && this.body.members[0].nodeType == TypeScript.NodeType.Block) { + emitter.emitJavascriptStatements(this.body, false); + } else { + emitter.writeLineToOutput(""); + emitter.indenter.increaseIndent(); + emitter.emitBareJavascriptStatements(this.body); + emitter.indenter.decreaseIndent(); + } + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + CaseStatement.prototype.typeCheck = function (typeFlow) { + this.expr = typeFlow.typeCheck(this.expr); + typeFlow.typeCheck(this.body); + this.type = typeFlow.voidType; + return this; + }; + CaseStatement.prototype.addToControlFlow = function (context) { + var execBlock = new TypeScript.BasicBlock(); + var sw = context.currentSwitch[context.currentSwitch.length - 1]; + if(this.expr) { + var exprBlock = new TypeScript.BasicBlock(); + context.current = exprBlock; + sw.addSuccessor(exprBlock); + context.addContent(this.expr); + exprBlock.addSuccessor(execBlock); + } else { + sw.addSuccessor(execBlock); + } + context.current = execBlock; + if(this.body) { + context.walk(this.body, this); + } + context.noContinuation = false; + context.walker.options.goChildren = false; + }; + return CaseStatement; + })(Statement); + TypeScript.CaseStatement = CaseStatement; + var TypeReference = (function (_super) { + __extends(TypeReference, _super); + function TypeReference(term, arrayCount) { + _super.call(this, TypeScript.NodeType.TypeRef); + this.term = term; + this.arrayCount = arrayCount; + } + TypeReference.prototype.emit = function (emitter, tokenId, startLine) { + throw new Error("should not emit a type ref"); + }; + TypeReference.prototype.typeCheck = function (typeFlow) { + var prevInTCTR = typeFlow.inTypeRefTypeCheck; + typeFlow.inTypeRefTypeCheck = true; + var typeLink = TypeScript.getTypeLink(this, typeFlow.checker, true); + typeFlow.checker.resolveTypeLink(typeFlow.scope, typeLink, false); + if(this.term) { + typeFlow.typeCheck(this.term); + } + typeFlow.checkForVoidConstructor(typeLink.type, this); + this.type = typeLink.type; + if(this.term) { + this.term.type = this.type; + } + typeFlow.inTypeRefTypeCheck = prevInTCTR; + return this; + }; + return TypeReference; + })(AST); + TypeScript.TypeReference = TypeReference; + var TryFinally = (function (_super) { + __extends(TryFinally, _super); + function TryFinally(tryNode, finallyNode) { + _super.call(this, TypeScript.NodeType.TryFinally); + this.tryNode = tryNode; + this.finallyNode = finallyNode; + } + TryFinally.prototype.isCompoundStatement = function () { + return true; + }; + TryFinally.prototype.emit = function (emitter, tokenId, startLine) { + emitter.recordSourceMappingStart(this); + emitter.emitJavascript(this.tryNode, TypeScript.TokenID.Try, false); + emitter.emitJavascript(this.finallyNode, TypeScript.TokenID.Finally, false); + emitter.recordSourceMappingEnd(this); + }; + TryFinally.prototype.typeCheck = function (typeFlow) { + this.tryNode = typeFlow.typeCheck(this.tryNode); + this.finallyNode = typeFlow.typeCheck(this.finallyNode); + this.type = typeFlow.voidType; + return this; + }; + TryFinally.prototype.addToControlFlow = function (context) { + var afterFinally = new TypeScript.BasicBlock(); + context.walk(this.tryNode, this); + var finBlock = new TypeScript.BasicBlock(); + if(context.current) { + context.current.addSuccessor(finBlock); + } + context.current = finBlock; + context.pushStatement(this, null, afterFinally); + context.walk(this.finallyNode, this); + if(!context.noContinuation && context.current) { + context.current.addSuccessor(afterFinally); + } + if(afterFinally.predecessors.length > 0) { + context.current = afterFinally; + } else { + context.noContinuation = true; + } + context.popStatement(); + context.walker.options.goChildren = false; + }; + return TryFinally; + })(Statement); + TypeScript.TryFinally = TryFinally; + var TryCatch = (function (_super) { + __extends(TryCatch, _super); + function TryCatch(tryNode, catchNode) { + _super.call(this, TypeScript.NodeType.TryCatch); + this.tryNode = tryNode; + this.catchNode = catchNode; + } + TryCatch.prototype.isCompoundStatement = function () { + return true; + }; + TryCatch.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.emitJavascript(this.tryNode, TypeScript.TokenID.Try, false); + emitter.emitJavascript(this.catchNode, TypeScript.TokenID.Catch, false); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + TryCatch.prototype.addToControlFlow = function (context) { + var beforeTry = context.current; + var tryBlock = new TypeScript.BasicBlock(); + beforeTry.addSuccessor(tryBlock); + context.current = tryBlock; + var afterTryCatch = new TypeScript.BasicBlock(); + context.pushStatement(this, null, afterTryCatch); + context.walk(this.tryNode, this); + if(!context.noContinuation) { + if(context.current) { + context.current.addSuccessor(afterTryCatch); + } + } + context.current = new TypeScript.BasicBlock(); + beforeTry.addSuccessor(context.current); + context.walk(this.catchNode, this); + context.popStatement(); + if(!context.noContinuation) { + if(context.current) { + context.current.addSuccessor(afterTryCatch); + } + } + context.current = afterTryCatch; + context.walker.options.goChildren = false; + }; + TryCatch.prototype.typeCheck = function (typeFlow) { + this.tryNode = typeFlow.typeCheck(this.tryNode); + this.catchNode = typeFlow.typeCheck(this.catchNode); + this.type = typeFlow.voidType; + return this; + }; + return TryCatch; + })(Statement); + TypeScript.TryCatch = TryCatch; + var Try = (function (_super) { + __extends(Try, _super); + function Try(body) { + _super.call(this, TypeScript.NodeType.Try); + this.body = body; + } + Try.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("try "); + emitter.emitJavascript(this.body, TypeScript.TokenID.Try, false); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + Try.prototype.typeCheck = function (typeFlow) { + this.body = typeFlow.typeCheck(this.body); + return this; + }; + Try.prototype.addToControlFlow = function (context) { + if(this.body) { + context.walk(this.body, this); + } + context.walker.options.goChildren = false; + context.noContinuation = false; + }; + return Try; + })(Statement); + TypeScript.Try = Try; + var Catch = (function (_super) { + __extends(Catch, _super); + function Catch(param, body) { + _super.call(this, TypeScript.NodeType.Catch); + this.param = param; + this.body = body; + this.statement = new ASTSpan(); + this.containedScope = null; + if(this.param) { + this.param.varFlags |= TypeScript.VarFlags.AutoInit; + } + } + Catch.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput(" "); + emitter.recordSourceMappingStart(this.statement); + emitter.writeToOutput("catch ("); + emitter.emitJavascript(this.param, TypeScript.TokenID.OpenParen, false); + emitter.writeToOutput(")"); + emitter.recordSourceMappingEnd(this.statement); + emitter.emitJavascript(this.body, TypeScript.TokenID.Catch, false); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + Catch.prototype.addToControlFlow = function (context) { + if(this.param) { + context.addContent(this.param); + var bodBlock = new TypeScript.BasicBlock(); + context.current.addSuccessor(bodBlock); + context.current = bodBlock; + } + if(this.body) { + context.walk(this.body, this); + } + context.noContinuation = false; + context.walker.options.goChildren = false; + }; + Catch.prototype.typeCheck = function (typeFlow) { + var prevScope = typeFlow.scope; + typeFlow.scope = this.containedScope; + this.param = typeFlow.typeCheck(this.param); + var exceptVar = new TypeScript.ValueLocation(); + var varSym = new TypeScript.VariableSymbol((this.param).id.text, this.param.minChar, typeFlow.checker.locationInfo.unitIndex, exceptVar); + exceptVar.symbol = varSym; + exceptVar.typeLink = new TypeScript.TypeLink(); + exceptVar.typeLink.type = typeFlow.anyType; + var thisFnc = typeFlow.thisFnc; + if(thisFnc && thisFnc.type) { + exceptVar.symbol.container = thisFnc.type.symbol; + } else { + exceptVar.symbol.container = null; + } + this.param.sym = exceptVar.symbol; + typeFlow.scope.enter(exceptVar.symbol.container, this.param, exceptVar.symbol, typeFlow.checker.errorReporter, false, false, false); + this.body = typeFlow.typeCheck(this.body); + if(typeFlow.checker.inProvisionalTypecheckMode()) { + var table = typeFlow.scope.getTable(); + (table).secondaryTable.table[exceptVar.symbol.name] = undefined; + } + this.type = typeFlow.voidType; + typeFlow.scope = prevScope; + return this; + }; + return Catch; + })(Statement); + TypeScript.Catch = Catch; + var Finally = (function (_super) { + __extends(Finally, _super); + function Finally(body) { + _super.call(this, TypeScript.NodeType.Finally); + this.body = body; + } + Finally.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("finally"); + emitter.emitJavascript(this.body, TypeScript.TokenID.Finally, false); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + Finally.prototype.addToControlFlow = function (context) { + if(this.body) { + context.walk(this.body, this); + } + context.walker.options.goChildren = false; + context.noContinuation = false; + }; + Finally.prototype.typeCheck = function (typeFlow) { + this.body = typeFlow.typeCheck(this.body); + return this; + }; + return Finally; + })(Statement); + TypeScript.Finally = Finally; + var Comment = (function (_super) { + __extends(Comment, _super); + function Comment(content, isBlockComment, endsLine) { + _super.call(this, TypeScript.NodeType.Comment); + this.content = content; + this.isBlockComment = isBlockComment; + this.endsLine = endsLine; + this.text = null; + this.docCommentText = null; + } + Comment.prototype.getText = function () { + if(this.text == null) { + if(this.isBlockComment) { + this.text = this.content.split("\n"); + for(var i = 0; i < this.text.length; i++) { + this.text[i] = this.text[i].replace(/^\s+|\s+$/g, ''); + } + } else { + this.text = [ + (this.content.replace(/^\s+|\s+$/g, '')) + ]; + } + } + return this.text; + }; + Comment.prototype.isDocComment = function () { + if(this.isBlockComment) { + return this.content.charAt(2) == "*" && this.content.charAt(3) != "/"; + } + return false; + }; + Comment.prototype.getDocCommentText = function () { + if(this.docCommentText == null) { + this.docCommentText = Comment.cleanJSDocComment(this.content); + } + return this.docCommentText; + }; + Comment.consumeLeadingSpace = function consumeLeadingSpace(line, startIndex, maxSpacesToRemove) { + var endIndex = line.length; + if(maxSpacesToRemove != undefined) { + endIndex = TypeScript.min(startIndex + maxSpacesToRemove, endIndex); + } + for(; startIndex < endIndex; startIndex++) { + var charCode = line.charCodeAt(startIndex); + if(charCode != TypeScript.LexCodeSpace && charCode != TypeScript.LexCodeTAB) { + return startIndex; + } + } + if(endIndex != line.length) { + return endIndex; + } + return -1; + }; + Comment.isSpaceChar = function isSpaceChar(line, index) { + var length = line.length; + if(index < length) { + var charCode = line.charCodeAt(index); + return charCode == TypeScript.LexCodeSpace || charCode == TypeScript.LexCodeTAB; + } + return index == length; + }; + Comment.cleanDocCommentLine = function cleanDocCommentLine(line, jsDocStyleComment, jsDocLineSpaceToRemove) { + var nonSpaceIndex = Comment.consumeLeadingSpace(line, 0); + if(nonSpaceIndex != -1) { + var jsDocSpacesRemoved = nonSpaceIndex; + if(jsDocStyleComment && line.charAt(nonSpaceIndex) == '*') { + var startIndex = nonSpaceIndex + 1; + nonSpaceIndex = Comment.consumeLeadingSpace(line, startIndex, jsDocLineSpaceToRemove); + if(nonSpaceIndex != -1) { + jsDocSpacesRemoved = nonSpaceIndex - startIndex; + } else { + return null; + } + } + return { + minChar: nonSpaceIndex, + limChar: line.charAt(line.length - 1) == "\r" ? line.length - 1 : line.length, + jsDocSpacesRemoved: jsDocSpacesRemoved + }; + } + return null; + }; + Comment.cleanJSDocComment = function cleanJSDocComment(content, spacesToRemove) { + var docCommentLines = []; + content = content.replace("/**", ""); + if(content.length >= 2 && content.charAt(content.length - 1) == "/" && content.charAt(content.length - 2) == "*") { + content = content.substring(0, content.length - 2); + } + var lines = content.split("\n"); + var inParamTag = false; + for(var l = 0; l < lines.length; l++) { + var line = lines[l]; + var cleanLinePos = Comment.cleanDocCommentLine(line, true, spacesToRemove); + if(!cleanLinePos) { + continue; + } + var docCommentText = ""; + var prevPos = cleanLinePos.minChar; + for(var i = line.indexOf("@", cleanLinePos.minChar); 0 <= i && i < cleanLinePos.limChar; i = line.indexOf("@", i + 1)) { + var wasInParamtag = inParamTag; + if(line.indexOf("param", i + 1) == i + 1 && Comment.isSpaceChar(line, i + 6)) { + if(!wasInParamtag) { + docCommentText += line.substring(prevPos, i); + } + prevPos = i; + inParamTag = true; + } else if(wasInParamtag) { + prevPos = i; + inParamTag = false; + } + } + if(!inParamTag) { + docCommentText += line.substring(prevPos, cleanLinePos.limChar); + } + var newCleanPos = Comment.cleanDocCommentLine(docCommentText, false); + if(newCleanPos) { + if(spacesToRemove == undefined) { + spacesToRemove = cleanLinePos.jsDocSpacesRemoved; + } + docCommentLines.push(docCommentText); + } + } + return docCommentLines.join("\n"); + }; + Comment.getDocCommentText = function getDocCommentText(comments) { + var docCommentText = []; + for(var c = 0; c < comments.length; c++) { + var commentText = comments[c].getDocCommentText(); + if(commentText != "") { + docCommentText.push(commentText); + } + } + return docCommentText.join("\n"); + }; + Comment.getParameterDocCommentText = function getParameterDocCommentText(param, fncDocComments) { + if(fncDocComments.length == 0 || !fncDocComments[0].isBlockComment) { + return ""; + } + for(var i = 0; i < fncDocComments.length; i++) { + var commentContents = fncDocComments[i].content; + for(var j = commentContents.indexOf("@param", 0); 0 <= j; j = commentContents.indexOf("@param", j)) { + j += 6; + if(!Comment.isSpaceChar(commentContents, j)) { + continue; + } + j = Comment.consumeLeadingSpace(commentContents, j); + if(j == -1) { + break; + } + if(commentContents.charCodeAt(j) == TypeScript.LexCodeLC) { + j++; + var charCode = 0; + for(var curlies = 1; j < commentContents.length; j++) { + charCode = commentContents.charCodeAt(j); + if(charCode == TypeScript.LexCodeLC) { + curlies++; + continue; + } + if(charCode == TypeScript.LexCodeRC) { + curlies--; + if(curlies == 0) { + break; + } else { + continue; + } + } + if(charCode == TypeScript.LexCodeAtSign) { + break; + } + } + if(j == commentContents.length) { + break; + } + if(charCode == TypeScript.LexCodeAtSign) { + continue; + } + j = Comment.consumeLeadingSpace(commentContents, j + 1); + if(j == -1) { + break; + } + } + if(param != commentContents.substr(j, param.length) || !Comment.isSpaceChar(commentContents, j + param.length)) { + continue; + } + j = Comment.consumeLeadingSpace(commentContents, j + param.length); + if(j == -1) { + return ""; + } + var endOfParam = commentContents.indexOf("@", j); + var paramHelpString = commentContents.substring(j, endOfParam < 0 ? commentContents.length : endOfParam); + var paramSpacesToRemove = undefined; + var paramLineIndex = commentContents.substring(0, j).lastIndexOf("\n") + 1; + if(paramLineIndex != 0) { + if(paramLineIndex < j && commentContents.charAt(paramLineIndex + 1) == "\r") { + paramLineIndex++; + } + } + var startSpaceRemovalIndex = Comment.consumeLeadingSpace(commentContents, paramLineIndex); + if(startSpaceRemovalIndex != j && commentContents.charAt(startSpaceRemovalIndex) == "*") { + paramSpacesToRemove = j - startSpaceRemovalIndex - 1; + } + return Comment.cleanJSDocComment(paramHelpString, paramSpacesToRemove); + } + } + return ""; + }; + Comment.getDocCommentFirstOverloadSignature = function getDocCommentFirstOverloadSignature(signatureGroup) { + for(var i = 0; i < signatureGroup.signatures.length; i++) { + var signature = signatureGroup.signatures[i]; + if(signature == signatureGroup.definitionSignature) { + continue; + } + return TypeScript.Comment.getDocCommentText(signature.declAST.getDocComments()); + } + return ""; + }; + return Comment; + })(AST); + TypeScript.Comment = Comment; + var DebuggerStatement = (function (_super) { + __extends(DebuggerStatement, _super); + function DebuggerStatement() { + _super.call(this, TypeScript.NodeType.Debugger); + } + DebuggerStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("debugger"); + emitter.recordSourceMappingEnd(this); + emitter.writeLineToOutput(";"); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return DebuggerStatement; + })(Statement); + TypeScript.DebuggerStatement = DebuggerStatement; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var AstWalkOptions = (function () { + function AstWalkOptions() { + this.goChildren = true; + this.goNextSibling = true; + this.reverseSiblings = false; + } + AstWalkOptions.prototype.stopWalk = function (stop) { + if (typeof stop === "undefined") { stop = true; } + this.goChildren = !stop; + this.goNextSibling = !stop; + }; + return AstWalkOptions; + })(); + TypeScript.AstWalkOptions = AstWalkOptions; + var AstWalker = (function () { + function AstWalker(childrenWalkers, pre, post, options, state) { + this.childrenWalkers = childrenWalkers; + this.pre = pre; + this.post = post; + this.options = options; + this.state = state; + } + AstWalker.prototype.walk = function (ast, parent) { + var preAst = this.pre(ast, parent, this); + if(preAst === undefined) { + preAst = ast; + } + if(this.options.goChildren) { + var svGoSib = this.options.goNextSibling; + this.options.goNextSibling = true; + this.childrenWalkers[ast.nodeType](ast, parent, this); + this.options.goNextSibling = svGoSib; + } else { + this.options.goChildren = true; + } + if(this.post) { + var postAst = this.post(preAst, parent, this); + if(postAst === undefined) { + postAst = preAst; + } + return postAst; + } else { + return preAst; + } + }; + return AstWalker; + })(); + var AstWalkerFactory = (function () { + function AstWalkerFactory() { + this.childrenWalkers = []; + this.initChildrenWalkers(); + } + AstWalkerFactory.prototype.walk = function (ast, pre, post, options, state) { + return this.getWalker(pre, post, options, state).walk(ast, null); + }; + AstWalkerFactory.prototype.getWalker = function (pre, post, options, state) { + return this.getSlowWalker(pre, post, options, state); + }; + AstWalkerFactory.prototype.getSlowWalker = function (pre, post, options, state) { + if(!options) { + options = new AstWalkOptions(); + } + return new AstWalker(this.childrenWalkers, pre, post, options, state); + }; + AstWalkerFactory.prototype.initChildrenWalkers = function () { + this.childrenWalkers[TypeScript.NodeType.None] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Empty] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.EmptyExpr] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.True] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.False] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.This] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Super] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.QString] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Regex] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Null] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.ArrayLit] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.ObjectLit] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Void] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Comma] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Pos] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Neg] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Delete] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Await] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.In] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Dot] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.From] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Is] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.InstOf] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Typeof] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.NumberLit] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Name] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.TypeRef] = ChildrenWalkers.walkTypeReferenceChildren; + this.childrenWalkers[TypeScript.NodeType.Index] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Call] = ChildrenWalkers.walkCallExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.New] = ChildrenWalkers.walkCallExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Asg] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgAdd] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgSub] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgDiv] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgMul] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgMod] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgAnd] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgXor] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgOr] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgLsh] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgRsh] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.AsgRs2] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.ConditionalExpression] = ChildrenWalkers.walkTrinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.LogOr] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.LogAnd] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Or] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Xor] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.And] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Eq] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Ne] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Eqv] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.NEqv] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Lt] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Le] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Gt] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Ge] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Add] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Sub] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Mul] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Div] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Mod] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Lsh] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Rsh] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Rs2] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.Not] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.LogNot] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.IncPre] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.DecPre] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.IncPost] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.DecPost] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.TypeAssertion] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.FuncDecl] = ChildrenWalkers.walkFuncDeclChildren; + this.childrenWalkers[TypeScript.NodeType.Member] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.VarDecl] = ChildrenWalkers.walkBoundDeclChildren; + this.childrenWalkers[TypeScript.NodeType.ArgDecl] = ChildrenWalkers.walkBoundDeclChildren; + this.childrenWalkers[TypeScript.NodeType.Return] = ChildrenWalkers.walkReturnStatementChildren; + this.childrenWalkers[TypeScript.NodeType.Break] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Continue] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Throw] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[TypeScript.NodeType.For] = ChildrenWalkers.walkForStatementChildren; + this.childrenWalkers[TypeScript.NodeType.ForIn] = ChildrenWalkers.walkForInStatementChildren; + this.childrenWalkers[TypeScript.NodeType.If] = ChildrenWalkers.walkIfStatementChildren; + this.childrenWalkers[TypeScript.NodeType.While] = ChildrenWalkers.walkWhileStatementChildren; + this.childrenWalkers[TypeScript.NodeType.DoWhile] = ChildrenWalkers.walkDoWhileStatementChildren; + this.childrenWalkers[TypeScript.NodeType.Block] = ChildrenWalkers.walkBlockChildren; + this.childrenWalkers[TypeScript.NodeType.Case] = ChildrenWalkers.walkCaseStatementChildren; + this.childrenWalkers[TypeScript.NodeType.Switch] = ChildrenWalkers.walkSwitchStatementChildren; + this.childrenWalkers[TypeScript.NodeType.Try] = ChildrenWalkers.walkTryChildren; + this.childrenWalkers[TypeScript.NodeType.TryCatch] = ChildrenWalkers.walkTryCatchChildren; + this.childrenWalkers[TypeScript.NodeType.TryFinally] = ChildrenWalkers.walkTryFinallyChildren; + this.childrenWalkers[TypeScript.NodeType.Finally] = ChildrenWalkers.walkFinallyChildren; + this.childrenWalkers[TypeScript.NodeType.Catch] = ChildrenWalkers.walkCatchChildren; + this.childrenWalkers[TypeScript.NodeType.List] = ChildrenWalkers.walkListChildren; + this.childrenWalkers[TypeScript.NodeType.Script] = ChildrenWalkers.walkScriptChildren; + this.childrenWalkers[TypeScript.NodeType.ClassDeclaration] = ChildrenWalkers.walkClassDeclChildren; + this.childrenWalkers[TypeScript.NodeType.InterfaceDeclaration] = ChildrenWalkers.walkTypeDeclChildren; + this.childrenWalkers[TypeScript.NodeType.ModuleDeclaration] = ChildrenWalkers.walkModuleDeclChildren; + this.childrenWalkers[TypeScript.NodeType.ImportDeclaration] = ChildrenWalkers.walkImportDeclChildren; + this.childrenWalkers[TypeScript.NodeType.With] = ChildrenWalkers.walkWithStatementChildren; + this.childrenWalkers[TypeScript.NodeType.Label] = ChildrenWalkers.walkLabelChildren; + this.childrenWalkers[TypeScript.NodeType.LabeledStatement] = ChildrenWalkers.walkLabeledStatementChildren; + this.childrenWalkers[TypeScript.NodeType.EBStart] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.GotoEB] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.EndCode] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Error] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Comment] = ChildrenWalkers.walkNone; + this.childrenWalkers[TypeScript.NodeType.Debugger] = ChildrenWalkers.walkNone; + for(var e in (TypeScript.NodeType)._map) { + if((this.childrenWalkers)[e] === undefined) { + throw new Error("initWalkers function is not up to date with enum content!"); + } + } + }; + return AstWalkerFactory; + })(); + TypeScript.AstWalkerFactory = AstWalkerFactory; + var globalAstWalkerFactory; + function getAstWalkerFactory() { + if(!globalAstWalkerFactory) { + globalAstWalkerFactory = new AstWalkerFactory(); + } + return globalAstWalkerFactory; + } + TypeScript.getAstWalkerFactory = getAstWalkerFactory; + var ChildrenWalkers; + (function (ChildrenWalkers) { + function walkNone(preAst, parent, walker) { + } + ChildrenWalkers.walkNone = walkNone; + function walkListChildren(preAst, parent, walker) { + var len = preAst.members.length; + if(walker.options.reverseSiblings) { + for(var i = len - 1; i >= 0; i--) { + if(walker.options.goNextSibling) { + preAst.members[i] = walker.walk(preAst.members[i], preAst); + } + } + } else { + for(var i = 0; i < len; i++) { + if(walker.options.goNextSibling) { + preAst.members[i] = walker.walk(preAst.members[i], preAst); + } + } + } + } + ChildrenWalkers.walkListChildren = walkListChildren; + function walkUnaryExpressionChildren(preAst, parent, walker) { + if(preAst.castTerm) { + preAst.castTerm = walker.walk(preAst.castTerm, preAst); + } + if(preAst.operand) { + preAst.operand = walker.walk(preAst.operand, preAst); + } + } + ChildrenWalkers.walkUnaryExpressionChildren = walkUnaryExpressionChildren; + function walkBinaryExpressionChildren(preAst, parent, walker) { + if(walker.options.reverseSiblings) { + if(preAst.operand2) { + preAst.operand2 = walker.walk(preAst.operand2, preAst); + } + if((preAst.operand1) && (walker.options.goNextSibling)) { + preAst.operand1 = walker.walk(preAst.operand1, preAst); + } + } else { + if(preAst.operand1) { + preAst.operand1 = walker.walk(preAst.operand1, preAst); + } + if((preAst.operand2) && (walker.options.goNextSibling)) { + preAst.operand2 = walker.walk(preAst.operand2, preAst); + } + } + } + ChildrenWalkers.walkBinaryExpressionChildren = walkBinaryExpressionChildren; + function walkTypeReferenceChildren(preAst, parent, walker) { + if(preAst.term) { + preAst.term = walker.walk(preAst.term, preAst); + } + } + ChildrenWalkers.walkTypeReferenceChildren = walkTypeReferenceChildren; + function walkCallExpressionChildren(preAst, parent, walker) { + if(!walker.options.reverseSiblings) { + preAst.target = walker.walk(preAst.target, preAst); + } + if(preAst.arguments && (walker.options.goNextSibling)) { + preAst.arguments = walker.walk(preAst.arguments, preAst); + } + if((walker.options.reverseSiblings) && (walker.options.goNextSibling)) { + preAst.target = walker.walk(preAst.target, preAst); + } + } + ChildrenWalkers.walkCallExpressionChildren = walkCallExpressionChildren; + function walkTrinaryExpressionChildren(preAst, parent, walker) { + if(preAst.operand1) { + preAst.operand1 = walker.walk(preAst.operand1, preAst); + } + if(preAst.operand2 && (walker.options.goNextSibling)) { + preAst.operand2 = walker.walk(preAst.operand2, preAst); + } + if(preAst.operand3 && (walker.options.goNextSibling)) { + preAst.operand3 = walker.walk(preAst.operand3, preAst); + } + } + ChildrenWalkers.walkTrinaryExpressionChildren = walkTrinaryExpressionChildren; + function walkFuncDeclChildren(preAst, parent, walker) { + if(preAst.name) { + preAst.name = walker.walk(preAst.name, preAst); + } + if(preAst.arguments && (walker.options.goNextSibling)) { + preAst.arguments = walker.walk(preAst.arguments, preAst); + } + if(preAst.returnTypeAnnotation && (walker.options.goNextSibling)) { + preAst.returnTypeAnnotation = walker.walk(preAst.returnTypeAnnotation, preAst); + } + if(preAst.bod && (walker.options.goNextSibling)) { + preAst.bod = walker.walk(preAst.bod, preAst); + } + } + ChildrenWalkers.walkFuncDeclChildren = walkFuncDeclChildren; + function walkBoundDeclChildren(preAst, parent, walker) { + if(preAst.id) { + preAst.id = walker.walk(preAst.id, preAst); + } + if(preAst.init) { + preAst.init = walker.walk(preAst.init, preAst); + } + if((preAst.typeExpr) && (walker.options.goNextSibling)) { + preAst.typeExpr = walker.walk(preAst.typeExpr, preAst); + } + } + ChildrenWalkers.walkBoundDeclChildren = walkBoundDeclChildren; + function walkReturnStatementChildren(preAst, parent, walker) { + if(preAst.returnExpression) { + preAst.returnExpression = walker.walk(preAst.returnExpression, preAst); + } + } + ChildrenWalkers.walkReturnStatementChildren = walkReturnStatementChildren; + function walkForStatementChildren(preAst, parent, walker) { + if(preAst.init) { + preAst.init = walker.walk(preAst.init, preAst); + } + if(preAst.cond && walker.options.goNextSibling) { + preAst.cond = walker.walk(preAst.cond, preAst); + } + if(preAst.incr && walker.options.goNextSibling) { + preAst.incr = walker.walk(preAst.incr, preAst); + } + if(preAst.body && walker.options.goNextSibling) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkForStatementChildren = walkForStatementChildren; + function walkForInStatementChildren(preAst, parent, walker) { + preAst.lval = walker.walk(preAst.lval, preAst); + if(walker.options.goNextSibling) { + preAst.obj = walker.walk(preAst.obj, preAst); + } + if(preAst.body && (walker.options.goNextSibling)) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkForInStatementChildren = walkForInStatementChildren; + function walkIfStatementChildren(preAst, parent, walker) { + preAst.cond = walker.walk(preAst.cond, preAst); + if(preAst.thenBod && (walker.options.goNextSibling)) { + preAst.thenBod = walker.walk(preAst.thenBod, preAst); + } + if(preAst.elseBod && (walker.options.goNextSibling)) { + preAst.elseBod = walker.walk(preAst.elseBod, preAst); + } + } + ChildrenWalkers.walkIfStatementChildren = walkIfStatementChildren; + function walkWhileStatementChildren(preAst, parent, walker) { + preAst.cond = walker.walk(preAst.cond, preAst); + if(preAst.body && (walker.options.goNextSibling)) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkWhileStatementChildren = walkWhileStatementChildren; + function walkDoWhileStatementChildren(preAst, parent, walker) { + preAst.cond = walker.walk(preAst.cond, preAst); + if(preAst.body && (walker.options.goNextSibling)) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkDoWhileStatementChildren = walkDoWhileStatementChildren; + function walkBlockChildren(preAst, parent, walker) { + if(preAst.statements) { + preAst.statements = walker.walk(preAst.statements, preAst); + } + } + ChildrenWalkers.walkBlockChildren = walkBlockChildren; + function walkCaseStatementChildren(preAst, parent, walker) { + if(preAst.expr) { + preAst.expr = walker.walk(preAst.expr, preAst); + } + if(preAst.body && walker.options.goNextSibling) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkCaseStatementChildren = walkCaseStatementChildren; + function walkSwitchStatementChildren(preAst, parent, walker) { + if(preAst.val) { + preAst.val = walker.walk(preAst.val, preAst); + } + if((preAst.caseList) && walker.options.goNextSibling) { + preAst.caseList = walker.walk(preAst.caseList, preAst); + } + } + ChildrenWalkers.walkSwitchStatementChildren = walkSwitchStatementChildren; + function walkTryChildren(preAst, parent, walker) { + if(preAst.body) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkTryChildren = walkTryChildren; + function walkTryCatchChildren(preAst, parent, walker) { + if(preAst.tryNode) { + preAst.tryNode = walker.walk(preAst.tryNode, preAst); + } + if((preAst.catchNode) && walker.options.goNextSibling) { + preAst.catchNode = walker.walk(preAst.catchNode, preAst); + } + } + ChildrenWalkers.walkTryCatchChildren = walkTryCatchChildren; + function walkTryFinallyChildren(preAst, parent, walker) { + if(preAst.tryNode) { + preAst.tryNode = walker.walk(preAst.tryNode, preAst); + } + if(preAst.finallyNode && walker.options.goNextSibling) { + preAst.finallyNode = walker.walk(preAst.finallyNode, preAst); + } + } + ChildrenWalkers.walkTryFinallyChildren = walkTryFinallyChildren; + function walkFinallyChildren(preAst, parent, walker) { + if(preAst.body) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkFinallyChildren = walkFinallyChildren; + function walkCatchChildren(preAst, parent, walker) { + if(preAst.param) { + preAst.param = walker.walk(preAst.param, preAst); + } + if((preAst.body) && walker.options.goNextSibling) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkCatchChildren = walkCatchChildren; + function walkRecordChildren(preAst, parent, walker) { + preAst.name = walker.walk(preAst.name, preAst); + if(walker.options.goNextSibling && preAst.members) { + preAst.members = walker.walk(preAst.members, preAst); + } + } + ChildrenWalkers.walkRecordChildren = walkRecordChildren; + function walkNamedTypeChildren(preAst, parent, walker) { + walkRecordChildren(preAst, parent, walker); + } + ChildrenWalkers.walkNamedTypeChildren = walkNamedTypeChildren; + function walkClassDeclChildren(preAst, parent, walker) { + walkNamedTypeChildren(preAst, parent, walker); + if(walker.options.goNextSibling && preAst.extendsList) { + preAst.extendsList = walker.walk(preAst.extendsList, preAst); + } + if(walker.options.goNextSibling && preAst.implementsList) { + preAst.implementsList = walker.walk(preAst.implementsList, preAst); + } + } + ChildrenWalkers.walkClassDeclChildren = walkClassDeclChildren; + function walkScriptChildren(preAst, parent, walker) { + if(preAst.bod) { + preAst.bod = walker.walk(preAst.bod, preAst); + } + } + ChildrenWalkers.walkScriptChildren = walkScriptChildren; + function walkTypeDeclChildren(preAst, parent, walker) { + walkNamedTypeChildren(preAst, parent, walker); + if(walker.options.goNextSibling && preAst.extendsList) { + preAst.extendsList = walker.walk(preAst.extendsList, preAst); + } + if(walker.options.goNextSibling && preAst.implementsList) { + preAst.implementsList = walker.walk(preAst.implementsList, preAst); + } + } + ChildrenWalkers.walkTypeDeclChildren = walkTypeDeclChildren; + function walkModuleDeclChildren(preAst, parent, walker) { + walkRecordChildren(preAst, parent, walker); + } + ChildrenWalkers.walkModuleDeclChildren = walkModuleDeclChildren; + function walkImportDeclChildren(preAst, parent, walker) { + if(preAst.id) { + preAst.id = walker.walk(preAst.id, preAst); + } + if(preAst.alias) { + preAst.alias = walker.walk(preAst.alias, preAst); + } + } + ChildrenWalkers.walkImportDeclChildren = walkImportDeclChildren; + function walkWithStatementChildren(preAst, parent, walker) { + if(preAst.expr) { + preAst.expr = walker.walk(preAst.expr, preAst); + } + if(preAst.body && walker.options.goNextSibling) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkWithStatementChildren = walkWithStatementChildren; + function walkLabelChildren(preAst, parent, walker) { + } + ChildrenWalkers.walkLabelChildren = walkLabelChildren; + function walkLabeledStatementChildren(preAst, parent, walker) { + preAst.labels = walker.walk(preAst.labels, preAst); + if(walker.options.goNextSibling) { + preAst.stmt = walker.walk(preAst.stmt, preAst); + } + } + ChildrenWalkers.walkLabeledStatementChildren = walkLabeledStatementChildren; + })(ChildrenWalkers || (ChildrenWalkers = {})); +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (AstWalkerWithDetailCallback) { + function walk(script, callback) { + var pre = function (cur, parent) { + walker.options.goChildren = AstWalkerCallback(true, cur, callback); + return cur; + }; + var post = function (cur, parent) { + AstWalkerCallback(false, cur, callback); + return cur; + }; + var walker = TypeScript.getAstWalkerFactory().getWalker(pre, post); + walker.walk(script, null); + } + AstWalkerWithDetailCallback.walk = walk; + function AstWalkerCallback(pre, ast, callback) { + var nodeType = ast.nodeType; + var callbackString = (TypeScript.NodeType)._map[nodeType] + "Callback"; + if(callback[callbackString]) { + return callback[callbackString](pre, ast); + } + if(callback.DefaultCallback) { + return callback.DefaultCallback(pre, ast); + } + return true; + } + })(TypeScript.AstWalkerWithDetailCallback || (TypeScript.AstWalkerWithDetailCallback = {})); + var AstWalkerWithDetailCallback = TypeScript.AstWalkerWithDetailCallback; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + function lastOf(items) { + return (items === null || items.length === 0) ? null : items[items.length - 1]; + } + TypeScript.lastOf = lastOf; + function max(a, b) { + return a >= b ? a : b; + } + TypeScript.max = max; + function min(a, b) { + return a <= b ? a : b; + } + TypeScript.min = min; + var AstPath = (function () { + function AstPath() { + this.asts = []; + this.top = -1; + } + AstPath.reverseIndexOf = function reverseIndexOf(items, index) { + return (items === null || items.length <= index) ? null : items[items.length - index - 1]; + }; + AstPath.prototype.clone = function () { + var clone = new AstPath(); + clone.asts = this.asts.map(function (value) { + return value; + }); + clone.top = this.top; + return clone; + }; + AstPath.prototype.pop = function () { + var head = this.ast(); + this.up(); + while(this.asts.length > this.count()) { + this.asts.pop(); + } + return head; + }; + AstPath.prototype.push = function (ast) { + while(this.asts.length > this.count()) { + this.asts.pop(); + } + this.top = this.asts.length; + this.asts.push(ast); + }; + AstPath.prototype.up = function () { + if(this.top <= -1) { + throw new Error("Invalid call to 'up'"); + } + this.top--; + }; + AstPath.prototype.down = function () { + if(this.top == this.ast.length - 1) { + throw new Error("Invalid call to 'down'"); + } + this.top++; + }; + AstPath.prototype.nodeType = function () { + if(this.ast() == null) { + return TypeScript.NodeType.None; + } + return this.ast().nodeType; + }; + AstPath.prototype.ast = function () { + return AstPath.reverseIndexOf(this.asts, this.asts.length - (this.top + 1)); + }; + AstPath.prototype.parent = function () { + return AstPath.reverseIndexOf(this.asts, this.asts.length - this.top); + }; + AstPath.prototype.count = function () { + return this.top + 1; + }; + AstPath.prototype.get = function (index) { + return this.asts[index]; + }; + AstPath.prototype.isNameOfClass = function () { + if(this.ast() === null || this.parent() === null) { + return false; + } + return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.ClassDeclaration) && ((this.parent()).name === this.ast()); + }; + AstPath.prototype.isNameOfInterface = function () { + if(this.ast() === null || this.parent() === null) { + return false; + } + return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.InterfaceDeclaration) && ((this.parent()).name === this.ast()); + }; + AstPath.prototype.isNameOfArgument = function () { + if(this.ast() === null || this.parent() === null) { + return false; + } + return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.ArgDecl) && ((this.parent()).id === this.ast()); + }; + AstPath.prototype.isNameOfVariable = function () { + if(this.ast() === null || this.parent() === null) { + return false; + } + return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.VarDecl) && ((this.parent()).id === this.ast()); + }; + AstPath.prototype.isNameOfModule = function () { + if(this.ast() === null || this.parent() === null) { + return false; + } + return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.ModuleDeclaration) && ((this.parent()).name === this.ast()); + }; + AstPath.prototype.isNameOfFunction = function () { + if(this.ast() === null || this.parent() === null) { + return false; + } + return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.FuncDecl) && ((this.parent()).name === this.ast()); + }; + AstPath.prototype.isChildOfScript = function () { + var ast = lastOf(this.asts); + return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.Script; + }; + AstPath.prototype.isChildOfModule = function () { + var ast = lastOf(this.asts); + return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.ModuleDeclaration; + }; + AstPath.prototype.isChildOfClass = function () { + var ast = lastOf(this.asts); + return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.ClassDeclaration; + }; + AstPath.prototype.isArgumentOfClassConstructor = function () { + var ast = lastOf(this.asts); + return this.count() >= 5 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.FuncDecl && this.asts[this.top - 3].nodeType === TypeScript.NodeType.List && this.asts[this.top - 4].nodeType === TypeScript.NodeType.ClassDeclaration && ((this.asts[this.top - 2]).isConstructor) && ((this.asts[this.top - 2]).arguments === this.asts[this.top - 1]) && ((this.asts[this.top - 4]).constructorDecl === this.asts[this.top - 2]); + }; + AstPath.prototype.isChildOfInterface = function () { + var ast = lastOf(this.asts); + return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.InterfaceDeclaration; + }; + AstPath.prototype.isTopLevelImplicitModule = function () { + return this.count() >= 1 && this.asts[this.top].nodeType === TypeScript.NodeType.ModuleDeclaration && TypeScript.hasFlag((this.asts[this.top]).modFlags, TypeScript.ModuleFlags.IsWholeFile); + }; + AstPath.prototype.isBodyOfTopLevelImplicitModule = function () { + return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ModuleDeclaration && (this.asts[this.top - 1]).members == this.asts[this.top - 0] && TypeScript.hasFlag((this.asts[this.top - 1]).modFlags, TypeScript.ModuleFlags.IsWholeFile); + }; + AstPath.prototype.isBodyOfScript = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Script && (this.asts[this.top - 1]).bod == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfSwitch = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Switch && (this.asts[this.top - 1]).caseList == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfModule = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ModuleDeclaration && (this.asts[this.top - 1]).members == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfClass = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ClassDeclaration && (this.asts[this.top - 1]).members == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfFunction = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.FuncDecl && (this.asts[this.top - 1]).bod == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfInterface = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.InterfaceDeclaration && (this.asts[this.top - 1]).members == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfBlock = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Block && (this.asts[this.top - 1]).statements == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfFor = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.For && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfCase = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Case && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfTry = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Try && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfCatch = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Catch && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfDoWhile = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.DoWhile && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfWhile = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.While && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfForIn = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ForIn && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfWith = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.With && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfFinally = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Finally && (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + }; + AstPath.prototype.isCaseOfSwitch = function () { + return this.count() >= 3 && this.asts[this.top - 2].nodeType === TypeScript.NodeType.Switch && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 2]).caseList == this.asts[this.top - 1]; + }; + AstPath.prototype.isDefaultCaseOfSwitch = function () { + return this.count() >= 3 && this.asts[this.top - 2].nodeType === TypeScript.NodeType.Switch && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 2]).caseList == this.asts[this.top - 1] && (this.asts[this.top - 2]).defaultCase == this.asts[this.top - 0]; + }; + AstPath.prototype.isListOfObjectLit = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 1]).operand == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfObjectLit = function () { + return this.isListOfObjectLit(); + }; + AstPath.prototype.isEmptyListOfObjectLit = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 1]).operand == this.asts[this.top - 0] && (this.asts[this.top - 0]).members.length == 0; + }; + AstPath.prototype.isMemberOfObjectLit = function () { + return this.count() >= 3 && this.asts[this.top - 2].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 0].nodeType === TypeScript.NodeType.Member && (this.asts[this.top - 2]).operand == this.asts[this.top - 1]; + }; + AstPath.prototype.isNameOfMemberOfObjectLit = function () { + return this.count() >= 4 && this.asts[this.top - 3].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 2].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Member && this.asts[this.top - 0].nodeType === TypeScript.NodeType.Name && (this.asts[this.top - 3]).operand == this.asts[this.top - 2]; + }; + AstPath.prototype.isListOfArrayLit = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ArrayLit && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && (this.asts[this.top - 1]).operand == this.asts[this.top - 0]; + }; + AstPath.prototype.isTargetOfMember = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Member && (this.asts[this.top - 1]).operand1 === this.asts[this.top - 0]; + }; + AstPath.prototype.isMemberOfMember = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Member && (this.asts[this.top - 1]).operand2 === this.asts[this.top - 0]; + }; + AstPath.prototype.isItemOfList = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List; + }; + AstPath.prototype.isThenOfIf = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.If && (this.asts[this.top - 1]).thenBod == this.asts[this.top - 0]; + }; + AstPath.prototype.isElseOfIf = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.If && (this.asts[this.top - 1]).elseBod == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfDefaultCase = function () { + return this.isBodyOfCase(); + }; + AstPath.prototype.isSingleStatementList = function () { + return this.count() >= 1 && this.asts[this.top].nodeType === TypeScript.NodeType.List && (this.asts[this.top]).members.length === 1; + }; + AstPath.prototype.isArgumentListOfFunction = function () { + return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.FuncDecl && (this.asts[this.top - 1]).arguments === this.asts[this.top - 0]; + }; + AstPath.prototype.isArgumentOfFunction = function () { + return this.count() >= 3 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.FuncDecl && (this.asts[this.top - 2]).arguments === this.asts[this.top - 1]; + }; + AstPath.prototype.isArgumentListOfCall = function () { + return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Call && (this.asts[this.top - 1]).arguments === this.asts[this.top - 0]; + }; + AstPath.prototype.isArgumentListOfNew = function () { + return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.New && (this.asts[this.top - 1]).arguments === this.asts[this.top - 0]; + }; + AstPath.prototype.isSynthesizedBlock = function () { + return this.count() >= 1 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.Block && (this.asts[this.top - 0]).isStatementBlock === false; + }; + return AstPath; + })(); + TypeScript.AstPath = AstPath; + function isValidAstNode(ast) { + if(ast === null) { + return false; + } + if(ast.minChar === -1 || ast.limChar === -1) { + return false; + } + return true; + } + TypeScript.isValidAstNode = isValidAstNode; + var AstPathContext = (function () { + function AstPathContext() { + this.path = new TypeScript.AstPath(); + } + return AstPathContext; + })(); + TypeScript.AstPathContext = AstPathContext; + (function (GetAstPathOptions) { + GetAstPathOptions._map = []; + GetAstPathOptions.Default = 0; + GetAstPathOptions.EdgeInclusive = 1; + GetAstPathOptions.DontPruneSearchBasedOnPosition = 1 << 1; + })(TypeScript.GetAstPathOptions || (TypeScript.GetAstPathOptions = {})); + var GetAstPathOptions = TypeScript.GetAstPathOptions; + function getAstPathToPosition(script, pos, options) { + if (typeof options === "undefined") { options = GetAstPathOptions.Default; } + var lookInComments = function (comments) { + if(comments && comments.length > 0) { + for(var i = 0; i < comments.length; i++) { + var minChar = comments[i].minChar; + var limChar = comments[i].limChar; + if(!comments[i].isBlockComment) { + limChar++; + } + if(pos >= minChar && pos < limChar) { + ctx.path.push(comments[i]); + } + } + } + }; + var pre = function (cur, parent, walker) { + if(isValidAstNode(cur)) { + var inclusive = TypeScript.hasFlag(options, GetAstPathOptions.EdgeInclusive) || cur.nodeType === TypeScript.NodeType.Name || pos === script.limChar; + var minChar = cur.minChar; + var limChar = cur.limChar + (inclusive ? 1 : 0); + if(pos >= minChar && pos < limChar) { + var previous = ctx.path.ast(); + if(previous == null || (cur.minChar >= previous.minChar && cur.limChar <= previous.limChar)) { + ctx.path.push(cur); + } else { + } + } + if(pos < limChar) { + lookInComments(cur.preComments); + } + if(pos >= minChar) { + lookInComments(cur.postComments); + } + if(!TypeScript.hasFlag(options, GetAstPathOptions.DontPruneSearchBasedOnPosition)) { + walker.options.goChildren = (minChar <= pos && pos <= limChar); + } + } + return cur; + }; + var ctx = new AstPathContext(); + TypeScript.getAstWalkerFactory().walk(script, pre, null, null, ctx); + return ctx.path; + } + TypeScript.getAstPathToPosition = getAstPathToPosition; + function getTokenizationOffset(script, position) { + var bestOffset = 0; + var pre = function (cur, parent, walker) { + if(TypeScript.isValidAstNode(cur)) { + if(cur.minChar <= position) { + bestOffset = max(bestOffset, cur.minChar); + } + if(cur.minChar > position || cur.limChar < bestOffset) { + walker.options.goChildren = false; + } + } + return cur; + }; + TypeScript.getAstWalkerFactory().walk(script, pre); + return bestOffset; + } + TypeScript.getTokenizationOffset = getTokenizationOffset; + function walkAST(ast, callback) { + var pre = function (cur, parent, walker) { + var path = walker.state; + path.push(cur); + callback(path, walker); + return cur; + }; + var post = function (cur, parent, walker) { + var path = walker.state; + path.pop(); + return cur; + }; + var path = new AstPath(); + TypeScript.getAstWalkerFactory().walk(ast, pre, post, null, path); + } + TypeScript.walkAST = walkAST; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var AstLogger = (function () { + function AstLogger(logger) { + this.logger = logger; + } + AstLogger.prototype.logScript = function (script) { + var _this = this; + this.logLinemap(script.locationInfo.lineMap); + var stack = []; + var pre = function (cur, parent) { + stack.push(cur); + var indent = (stack.length - 1) * 2; + _this.logComments(script, cur.preComments, indent); + _this.logNode(script, cur, indent); + _this.logComments(script, cur.postComments, indent); + return cur; + }; + var post = function (cur, parent) { + stack.pop(); + return cur; + }; + TypeScript.getAstWalkerFactory().walk(script, pre, post); + }; + AstLogger.prototype.logNode = function (script, cur, indent) { + var msg = this.addPadding("", indent, "| ", true); + msg = msg.concat("+ " + cur.treeViewLabel()); + msg = this.addPadding(msg, 70, " ", false); + msg = msg + this.addLineColumn(script, cur.minChar); + msg = this.addPadding(msg, 80, " ", false); + msg = msg + "=> "; + msg = msg + this.addLineColumn(script, cur.limChar); + msg = this.addPadding(msg, 102, " ", false); + msg = msg.concat("[" + this.addPadding(cur.minChar.toString(), 1, " ", true) + ", " + this.addPadding(cur.limChar.toString(), 1, " ", true) + "]"); + msg = this.addPadding(msg, 115, " ", false); + msg = msg.concat("sym=" + (cur).sym); + msg = this.addPadding(msg, 135, " ", false); + msg = msg.concat("type=" + (cur.type === null ? "null" : cur.type.getTypeName())); + this.logger.log(msg); + }; + AstLogger.prototype.logComments = function (script, comments, indent) { + if(comments == null) { + return; + } + for(var i = 0; i < comments.length; i++) { + this.logNode(script, comments[i], indent); + } + }; + AstLogger.prototype.logLinemap = function (linemap) { + var result = "["; + for(var i = 0; i < linemap.length; i++) { + if(i > 0) { + result += ","; + } + result += linemap[i]; + } + result += "]"; + this.logger.log("linemap: " + result); + }; + AstLogger.prototype.addPadding = function (s, targetLength, paddingString, leftPadding) { + var result = (leftPadding ? "" : s); + for(var i = s.length; i < targetLength; i++) { + result = result + paddingString; + } + result = result + (leftPadding ? s : ""); + return result; + }; + AstLogger.prototype.addLineColumn = function (script, position) { + var lineInfo = { + line: -1, + col: -1 + }; + TypeScript.getSourceLineColFromMap(lineInfo, position, script.locationInfo.lineMap); + if(lineInfo.col !== -1) { + lineInfo.col++; + } + return "(" + lineInfo.line + ", " + lineInfo.col + ")"; + }; + return AstLogger; + })(); + TypeScript.AstLogger = AstLogger; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Binder = (function () { + function Binder(checker) { + this.checker = checker; + } + Binder.prototype.resolveBaseTypeLinks = function (typeLinks, scope) { + var extendsList = null; + if(typeLinks) { + extendsList = new Array(); + for(var i = 0, len = typeLinks.length; i < len; i++) { + extendsList[i] = this.checker.resolveBaseTypeLink(typeLinks[i], scope); + } + } + return extendsList; + }; + Binder.prototype.resolveBases = function (scope, type) { + type.extendsList = this.resolveBaseTypeLinks(type.extendsTypeLinks, scope); + var i = 0, len = type.extendsList.length; + var derivedIsClass = type.isClassInstance(); + for(; i < len; i++) { + var baseIsClass = type.extendsList[i].isClassInstance(); + if(type.extendsList[i] != this.checker.anyType) { + var baseRef = type.extendsTypeLinks[i].ast; + if(derivedIsClass) { + if(!baseIsClass) { + this.checker.errorReporter.simpleError(baseRef, "A class may only extend other classes, " + type.extendsList[i].symbol.fullName() + " is not a class."); + } + } else { + if(baseIsClass) { + this.checker.errorReporter.simpleError(baseRef, "An interface may only extend other interfaces, " + type.extendsList[i].symbol.fullName() + " is a class."); + } + } + } + } + type.implementsList = this.resolveBaseTypeLinks(type.implementsTypeLinks, scope); + if(type.implementsList) { + for(i = 0 , len = type.implementsList.length; i < len; i++) { + var iface = type.implementsList[i]; + var baseRef = type.implementsTypeLinks[i].ast; + if(iface.isClassInstance()) { + if(derivedIsClass) { + this.checker.errorReporter.simpleError(baseRef, "A class may only implement an interface; " + iface.symbol.fullName() + " is a class."); + } + } + } + } + }; + Binder.prototype.resolveSignatureGroup = function (signatureGroup, scope, instanceType) { + var supplyVar = !(signatureGroup.hasImplementation); + for(var i = 0, len = signatureGroup.signatures.length; i < len; i++) { + var signature = signatureGroup.signatures[i]; + if(instanceType) { + signature.returnType.type = instanceType; + } else { + this.checker.resolveTypeLink(scope, signature.returnType, supplyVar); + } + var paramLen = signature.parameters.length; + for(var j = 0; j < paramLen; j++) { + this.bindSymbol(scope, signature.parameters[j]); + } + if(signature.hasVariableArgList) { + var lastParam = signature.parameters[paramLen - 1]; + lastParam.argsOffset = paramLen - 1; + if(!lastParam.getType().isArray()) { + this.checker.errorReporter.simpleErrorFromSym(lastParam, "... parameter must have array type"); + lastParam.parameter.typeLink.type = this.checker.makeArrayType(lastParam.parameter.typeLink.type); + } + } + } + }; + Binder.prototype.bindType = function (scope, type, instanceType) { + if(instanceType) { + this.bindType(scope, instanceType, null); + } + var callAndConstructScope = scope; + if(type.hasMembers()) { + var members = type.members; + var ambientMembers = type.ambientMembers; + var typeMembers = type.getAllEnclosedTypes(); + var ambientTypeMembers = type.getAllAmbientEnclosedTypes(); + var memberScope = new TypeScript.SymbolTableScope(members, ambientMembers, typeMembers, ambientTypeMembers, type.symbol); + var agg = new TypeScript.SymbolAggregateScope(type.symbol); + var prevCurrentModDecl = this.checker.currentModDecl; + var prevBindStatus = this.checker.inBind; + agg.addParentScope(memberScope); + agg.addParentScope(scope); + if(type.isModuleType()) { + this.checker.currentModDecl = type.symbol.declAST; + this.checker.inBind = true; + } + if(members) { + this.bind(agg, type.members.allMembers); + } + if(typeMembers) { + this.bind(agg, typeMembers.allMembers); + } + if(ambientMembers) { + this.bind(agg, ambientMembers.allMembers); + } + if(ambientTypeMembers) { + this.bind(agg, ambientTypeMembers.allMembers); + } + if(type.isModuleType()) { + callAndConstructScope = agg; + } + this.checker.currentModDecl = prevCurrentModDecl; + this.checker.inBind = prevBindStatus; + } + if(type.extendsTypeLinks) { + this.resolveBases(scope, type); + } + if(type.construct) { + this.resolveSignatureGroup(type.construct, callAndConstructScope, instanceType); + } + if(type.call) { + this.resolveSignatureGroup(type.call, callAndConstructScope, null); + } + if(type.index) { + this.resolveSignatureGroup(type.index, scope, null); + } + if(type.elementType) { + this.bindType(scope, type.elementType, null); + } + }; + Binder.prototype.bindSymbol = function (scope, symbol) { + if(!symbol.bound) { + var prevLocationInfo = this.checker.locationInfo; + if((this.checker.units) && (symbol.unitIndex >= 0) && (symbol.unitIndex < this.checker.units.length)) { + this.checker.locationInfo = this.checker.units[symbol.unitIndex]; + } + switch(symbol.kind()) { + case TypeScript.SymbolKind.Type: + if(symbol.flags & TypeScript.SymbolFlags.Bound) { + break; + } + var typeSymbol = symbol; + typeSymbol.flags |= TypeScript.SymbolFlags.Bound; + if(typeSymbol.aliasLink && !typeSymbol.type && typeSymbol.aliasLink.alias.nodeType == TypeScript.NodeType.Name) { + var modPath = (typeSymbol.aliasLink.alias).text; + var modSym = this.checker.findSymbolForDynamicModule(modPath, this.checker.locationInfo.filename, function (id) { + return scope.find(id, false, true); + }); + if(modSym) { + typeSymbol.type = modSym.getType(); + } + } + if(typeSymbol.type && typeSymbol.type != this.checker.gloModType) { + this.bindType(scope, typeSymbol.type, typeSymbol.instanceType); + if(typeSymbol.type.isModuleType()) { + for(var i = 0; i < typeSymbol.expansions.length; i++) { + this.bindType(scope, typeSymbol.expansions[i], typeSymbol.instanceType); + } + } + } + break; + case TypeScript.SymbolKind.Field: + this.checker.resolveTypeLink(scope, (symbol).field.typeLink, false); + break; + case TypeScript.SymbolKind.Parameter: + this.checker.resolveTypeLink(scope, (symbol).parameter.typeLink, true); + break; + } + this.checker.locationInfo = prevLocationInfo; + } + symbol.bound = true; + }; + Binder.prototype.bind = function (scope, table) { + table.map(function (key, sym, binder) { + binder.bindSymbol(scope, sym); + }, this); + }; + return Binder; + })(); + TypeScript.Binder = Binder; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Base64Format = (function () { + function Base64Format() { } + Base64Format.encodedValues = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + Base64Format.encode = function encode(inValue) { + if(inValue < 64) { + return Base64Format.encodedValues.charAt(inValue); + } + throw TypeError(inValue + ": not a 64 based value"); + }; + Base64Format.decodeChar = function decodeChar(inChar) { + if(inChar.length === 1) { + return Base64Format.encodedValues.indexOf(inChar); + } else { + throw TypeError('"' + inChar + '" must have length 1'); + } + }; + return Base64Format; + })(); + var Base64VLQFormat = (function () { + function Base64VLQFormat() { } + Base64VLQFormat.encode = function encode(inValue) { + if(inValue < 0) { + inValue = ((-inValue) << 1) + 1; + } else { + inValue = inValue << 1; + } + var encodedStr = ""; + do { + var currentDigit = inValue & 31; + inValue = inValue >> 5; + if(inValue > 0) { + currentDigit = currentDigit | 32; + } + encodedStr = encodedStr + Base64Format.encode(currentDigit); + }while(inValue > 0); + return encodedStr; + }; + Base64VLQFormat.decode = function decode(inString) { + var result = 0; + var negative = false; + var shift = 0; + for(var i = 0; i < inString.length; i++) { + var byte = Base64Format.decodeChar(inString[i]); + if(i === 0) { + if((byte & 1) === 1) { + negative = true; + } + result = (byte >> 1) & 15; + } else { + result = result | ((byte & 31) << shift); + } + shift += (i == 0) ? 4 : 5; + if((byte & 32) === 32) { + } else { + return { + value: negative ? -(result) : result, + rest: inString.substr(i + 1) + }; + } + } + throw new Error('Base64 value "' + inString + '" finished with a continuation bit'); + }; + return Base64VLQFormat; + })(); + TypeScript.Base64VLQFormat = Base64VLQFormat; +})(TypeScript || (TypeScript = {})); +var JSON2 = { +}; +((function () { + 'use strict'; + function f(n) { + return n < 10 ? '0' + n : n; + } + if(typeof Date.prototype.toJSON !== 'function') { + Date.prototype.toJSON = function (key) { + return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; + }; + var strProto = String.prototype; + var numProto = Number.prototype; + numProto.JSON = strProto.JSON = (Boolean).prototype.toJSON = function (key) { + return this.valueOf(); + }; + } + var escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { + '\b': '\\b', + '\t': '\\t', + '\n': '\\n', + '\f': '\\f', + '\r': '\\r', + '"': '\\"', + '\\': '\\\\' + }, rep; + function quote(string) { + escapable.lastIndex = 0; + return escapable.test(string) ? '"' + string.replace(escapable, function (a) { + var c = meta[a]; + return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); + }) + '"' : '"' + string + '"'; + } + function str(key, holder) { + var i, k = null, v, length, mind = gap, partial, value = holder[key]; + if(value && typeof value === 'object' && typeof value.toJSON === 'function') { + value = value.toJSON(key); + } + if(typeof rep === 'function') { + value = rep.call(holder, key, value); + } + switch(typeof value) { + case 'string': + return quote(value); + case 'number': + return isFinite(value) ? String(value) : 'null'; + case 'boolean': + case 'null': + return String(value); + case 'object': + if(!value) { + return 'null'; + } + gap += indent; + partial = []; + if(Object.prototype.toString.apply(value, []) === '[object Array]') { + length = value.length; + for(i = 0; i < length; i += 1) { + partial[i] = str(i, value) || 'null'; + } + v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; + gap = mind; + return v; + } + if(rep && typeof rep === 'object') { + length = rep.length; + for(i = 0; i < length; i += 1) { + if(typeof rep[i] === 'string') { + k = rep[i]; + v = str(k, value); + if(v) { + partial.push(quote(k) + (gap ? ': ' : ':') + v); + } + } + } + } else { + for(k in value) { + if(Object.prototype.hasOwnProperty.call(value, k)) { + v = str(k, value); + if(v) { + partial.push(quote(k) + (gap ? ': ' : ':') + v); + } + } + } + } + v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; + gap = mind; + return v; + } + } + if(typeof JSON2.stringify !== 'function') { + JSON2.stringify = function (value, replacer, space) { + var i; + gap = ''; + indent = ''; + if(typeof space === 'number') { + for(i = 0; i < space; i += 1) { + indent += ' '; + } + } else if(typeof space === 'string') { + indent = space; + } + rep = replacer; + if(replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { + throw new Error('JSON.stringify'); + } + return str('', { + '': value + }); + }; + } +})()); +var TypeScript; +(function (TypeScript) { + var SourceMapPosition = (function () { + function SourceMapPosition() { } + return SourceMapPosition; + })(); + TypeScript.SourceMapPosition = SourceMapPosition; + var SourceMapping = (function () { + function SourceMapping() { + this.start = new SourceMapPosition(); + this.end = new SourceMapPosition(); + this.nameIndex = -1; + this.childMappings = []; + } + return SourceMapping; + })(); + TypeScript.SourceMapping = SourceMapping; + var SourceMapper = (function () { + function SourceMapper(tsFileName, jsFileName, jsFile, sourceMapOut, errorReporter, emitFullPathOfSourceMap) { + this.jsFile = jsFile; + this.sourceMapOut = sourceMapOut; + this.errorReporter = errorReporter; + this.sourceMappings = []; + this.currentMappings = []; + this.names = []; + this.currentNameIndex = []; + this.currentMappings.push(this.sourceMappings); + jsFileName = TypeScript.switchToForwardSlashes(jsFileName); + this.jsFileName = TypeScript.getPrettyName(jsFileName, false, true); + var removalIndex = jsFileName.lastIndexOf(this.jsFileName); + var fixedPath = jsFileName.substring(0, removalIndex); + if(emitFullPathOfSourceMap) { + if(jsFileName.indexOf("://") == -1) { + jsFileName = "file:///" + jsFileName; + } + this.jsFileName = jsFileName; + } + this.tsFileName = TypeScript.getRelativePathToFixedPath(fixedPath, tsFileName); + } + SourceMapper.MapFileExtension = ".map"; + SourceMapper.EmitSourceMapping = function EmitSourceMapping(allSourceMappers) { + var sourceMapper = allSourceMappers[0]; + sourceMapper.jsFile.WriteLine("//@ sourceMappingURL=" + sourceMapper.jsFileName + SourceMapper.MapFileExtension); + var sourceMapOut = sourceMapper.sourceMapOut; + var mappingsString = ""; + var tsFiles = []; + var prevEmittedColumn = 0; + var prevEmittedLine = 0; + var prevSourceColumn = 0; + var prevSourceLine = 0; + var prevSourceIndex = 0; + var prevNameIndex = 0; + var namesList = []; + var namesCount = 0; + var emitComma = false; + var recordedPosition = null; + for(var sourceMapperIndex = 0; sourceMapperIndex < allSourceMappers.length; sourceMapperIndex++) { + sourceMapper = allSourceMappers[sourceMapperIndex]; + var currentSourceIndex = tsFiles.length; + tsFiles.push(sourceMapper.tsFileName); + if(sourceMapper.names.length > 0) { + namesList.push.apply(namesList, sourceMapper.names); + } + var recordSourceMapping = function (mappedPosition, nameIndex) { + if(recordedPosition != null && recordedPosition.emittedColumn == mappedPosition.emittedColumn && recordedPosition.emittedLine == mappedPosition.emittedLine) { + return; + } + if(prevEmittedLine !== mappedPosition.emittedLine) { + while(prevEmittedLine < mappedPosition.emittedLine) { + prevEmittedColumn = 0; + mappingsString = mappingsString + ";"; + prevEmittedLine++; + } + emitComma = false; + } else if(emitComma) { + mappingsString = mappingsString + ","; + } + mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(mappedPosition.emittedColumn - prevEmittedColumn); + prevEmittedColumn = mappedPosition.emittedColumn; + mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(currentSourceIndex - prevSourceIndex); + prevSourceIndex = currentSourceIndex; + mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(mappedPosition.sourceLine - 1 - prevSourceLine); + prevSourceLine = mappedPosition.sourceLine - 1; + mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(mappedPosition.sourceColumn - prevSourceColumn); + prevSourceColumn = mappedPosition.sourceColumn; + if(nameIndex >= 0) { + mappingsString = mappingsString + TypeScript.Base64VLQFormat.encode(namesCount + nameIndex - prevNameIndex); + prevNameIndex = namesCount + nameIndex; + } + emitComma = true; + recordedPosition = mappedPosition; + }; + var recordSourceMappingSiblings = function (sourceMappings) { + for(var i = 0; i < sourceMappings.length; i++) { + var sourceMapping = sourceMappings[i]; + recordSourceMapping(sourceMapping.start, sourceMapping.nameIndex); + recordSourceMappingSiblings(sourceMapping.childMappings); + recordSourceMapping(sourceMapping.end, sourceMapping.nameIndex); + } + }; + recordSourceMappingSiblings(sourceMapper.sourceMappings, -1); + namesCount = namesCount + sourceMapper.names.length; + } + sourceMapOut.Write(JSON2.stringify({ + version: 3, + file: sourceMapper.jsFileName, + sources: tsFiles, + names: namesList, + mappings: mappingsString + })); + try { + sourceMapOut.Close(); + } catch (ex) { + sourceMapper.errorReporter.emitterError(null, ex.message); + } + }; + return SourceMapper; + })(); + TypeScript.SourceMapper = SourceMapper; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (EmitContainer) { + EmitContainer._map = []; + EmitContainer._map[0] = "Prog"; + EmitContainer.Prog = 0; + EmitContainer._map[1] = "Module"; + EmitContainer.Module = 1; + EmitContainer._map[2] = "DynamicModule"; + EmitContainer.DynamicModule = 2; + EmitContainer._map[3] = "Class"; + EmitContainer.Class = 3; + EmitContainer._map[4] = "Constructor"; + EmitContainer.Constructor = 4; + EmitContainer._map[5] = "Function"; + EmitContainer.Function = 5; + EmitContainer._map[6] = "Args"; + EmitContainer.Args = 6; + EmitContainer._map[7] = "Interface"; + EmitContainer.Interface = 7; + })(TypeScript.EmitContainer || (TypeScript.EmitContainer = {})); + var EmitContainer = TypeScript.EmitContainer; + var EmitState = (function () { + function EmitState() { + this.column = 0; + this.line = 0; + this.pretty = false; + this.inObjectLiteral = false; + this.container = EmitContainer.Prog; + } + return EmitState; + })(); + TypeScript.EmitState = EmitState; + var EmitOptions = (function () { + function EmitOptions(settings) { + this.ioHost = null; + this.outputMany = true; + this.commonDirectoryPath = ""; + this.minWhitespace = settings.minWhitespace; + this.propagateConstants = settings.propagateConstants; + this.emitComments = settings.emitComments; + this.outputOption = settings.outputOption; + this.emitFullSourceMapPath = settings.emitFullSourceMapPath; + } + EmitOptions.prototype.mapOutputFileName = function (fileName, extensionChanger) { + if(this.outputMany) { + var updatedFileName = fileName; + if(this.outputOption != "") { + updatedFileName = fileName.replace(this.commonDirectoryPath, ""); + updatedFileName = this.outputOption + updatedFileName; + } + return extensionChanger(updatedFileName, false); + } else { + return extensionChanger(this.outputOption, true); + } + }; + return EmitOptions; + })(); + TypeScript.EmitOptions = EmitOptions; + var Indenter = (function () { + function Indenter() { + this.indentAmt = 0; + } + Indenter.indentStep = 4; + Indenter.indentStepString = " "; + Indenter.indentStrings = []; + Indenter.prototype.increaseIndent = function () { + this.indentAmt += Indenter.indentStep; + }; + Indenter.prototype.decreaseIndent = function () { + this.indentAmt -= Indenter.indentStep; + }; + Indenter.prototype.getIndent = function () { + var indentString = Indenter.indentStrings[this.indentAmt]; + if(indentString === undefined) { + indentString = ""; + for(var i = 0; i < this.indentAmt; i = i + Indenter.indentStep) { + indentString += Indenter.indentStepString; + } + Indenter.indentStrings[this.indentAmt] = indentString; + } + return indentString; + }; + return Indenter; + })(); + TypeScript.Indenter = Indenter; + var Emitter = (function () { + function Emitter(checker, emittingFileName, outfile, emitOptions, errorReporter) { + this.checker = checker; + this.emittingFileName = emittingFileName; + this.outfile = outfile; + this.emitOptions = emitOptions; + this.errorReporter = errorReporter; + this.globalThisCapturePrologueEmitted = false; + this.extendsPrologueEmitted = false; + this.thisClassNode = null; + this.thisFnc = null; + this.moduleDeclList = []; + this.moduleName = ""; + this.emitState = new EmitState(); + this.indenter = new Indenter(); + this.ambientModule = false; + this.modAliasId = null; + this.firstModAlias = null; + this.allSourceMappers = []; + this.sourceMapper = null; + this.captureThisStmtString = "var _this = this;"; + this.varListCountStack = [ + 0 + ]; + } + Emitter.prototype.setSourceMappings = function (mapper) { + this.allSourceMappers.push(mapper); + this.sourceMapper = mapper; + }; + Emitter.prototype.writeToOutput = function (s) { + this.outfile.Write(s); + this.emitState.column += s.length; + }; + Emitter.prototype.writeToOutputTrimmable = function (s) { + if(this.emitOptions.minWhitespace) { + s = s.replace(/[\s]*/g, ''); + } + this.writeToOutput(s); + }; + Emitter.prototype.writeLineToOutput = function (s) { + if(this.emitOptions.minWhitespace) { + this.writeToOutput(s); + var c = s.charCodeAt(s.length - 1); + if(!((c == TypeScript.LexCodeSpace) || (c == TypeScript.LexCodeSMC) || (c == TypeScript.LexCodeLBR))) { + this.writeToOutput(' '); + } + } else { + this.outfile.WriteLine(s); + this.emitState.column = 0; + this.emitState.line++; + } + }; + Emitter.prototype.writeCaptureThisStatement = function (ast) { + this.emitIndent(); + this.recordSourceMappingStart(ast); + this.writeToOutput(this.captureThisStmtString); + this.recordSourceMappingEnd(ast); + this.writeLineToOutput(""); + }; + Emitter.prototype.setInVarBlock = function (count) { + this.varListCountStack[this.varListCountStack.length - 1] = count; + }; + Emitter.prototype.setInObjectLiteral = function (val) { + var temp = this.emitState.inObjectLiteral; + this.emitState.inObjectLiteral = val; + return temp; + }; + Emitter.prototype.setContainer = function (c) { + var temp = this.emitState.container; + this.emitState.container = c; + return temp; + }; + Emitter.prototype.getIndentString = function () { + if(this.emitOptions.minWhitespace) { + return ""; + } else { + return this.indenter.getIndent(); + } + }; + Emitter.prototype.emitIndent = function () { + this.writeToOutput(this.getIndentString()); + }; + Emitter.prototype.emitCommentInPlace = function (comment) { + var text = comment.getText(); + var hadNewLine = false; + if(comment.isBlockComment) { + if(this.emitState.column == 0) { + this.emitIndent(); + } + this.recordSourceMappingStart(comment); + this.writeToOutput(text[0]); + if(text.length > 1 || comment.endsLine) { + for(var i = 1; i < text.length; i++) { + this.writeLineToOutput(""); + this.emitIndent(); + this.writeToOutput(text[i]); + } + this.recordSourceMappingEnd(comment); + this.writeLineToOutput(""); + hadNewLine = true; + } else { + this.recordSourceMappingEnd(comment); + } + } else { + if(this.emitState.column == 0) { + this.emitIndent(); + } + this.recordSourceMappingStart(comment); + this.writeToOutput(text[0]); + this.recordSourceMappingEnd(comment); + this.writeLineToOutput(""); + hadNewLine = true; + } + if(hadNewLine) { + this.emitIndent(); + } else { + this.writeToOutput(" "); + } + }; + Emitter.prototype.emitParensAndCommentsInPlace = function (ast, pre) { + var comments = pre ? ast.preComments : ast.postComments; + if(ast.isParenthesized && !pre) { + this.writeToOutput(")"); + } + if(this.emitOptions.emitComments && comments && comments.length != 0) { + for(var i = 0; i < comments.length; i++) { + this.emitCommentInPlace(comments[i]); + } + } + if(ast.isParenthesized && pre) { + this.writeToOutput("("); + } + }; + Emitter.prototype.emitObjectLiteral = function (content) { + this.writeLineToOutput("{"); + this.indenter.increaseIndent(); + var inObjectLiteral = this.setInObjectLiteral(true); + this.emitJavascriptList(content, ",", TypeScript.TokenID.Comma, true, false, false); + this.setInObjectLiteral(inObjectLiteral); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeToOutput("}"); + }; + Emitter.prototype.emitArrayLiteral = function (content) { + this.writeToOutput("["); + if(content) { + this.writeLineToOutput(""); + this.indenter.increaseIndent(); + this.emitJavascriptList(content, ", ", TypeScript.TokenID.Comma, true, false, false); + this.indenter.decreaseIndent(); + this.emitIndent(); + } + this.writeToOutput("]"); + }; + Emitter.prototype.emitNew = function (target, args) { + this.writeToOutput("new "); + if(target.nodeType == TypeScript.NodeType.TypeRef) { + var typeRef = target; + if(typeRef.arrayCount) { + this.writeToOutput("Array()"); + } else { + this.emitJavascript(typeRef.term, TypeScript.TokenID.Tilde, false); + this.writeToOutput("()"); + } + } else { + this.emitJavascript(target, TypeScript.TokenID.Tilde, false); + this.recordSourceMappingStart(args); + this.writeToOutput("("); + this.emitJavascriptList(args, ", ", TypeScript.TokenID.Comma, false, false, false); + this.writeToOutput(")"); + this.recordSourceMappingEnd(args); + } + }; + Emitter.prototype.getConstantValue = function (init) { + if(init) { + if(init.nodeType === TypeScript.NodeType.NumberLit) { + var numLit = init; + return numLit.value; + } else if(init.nodeType === TypeScript.NodeType.Lsh) { + var binop = init; + if(binop.operand1.nodeType === TypeScript.NodeType.NumberLit && binop.operand2.nodeType === TypeScript.NodeType.NumberLit) { + return (binop.operand1).value << (binop.operand2).value; + } + } else if(init.nodeType === TypeScript.NodeType.Name) { + var ident = init; + if(ident.sym !== null && ident.sym.declAST.nodeType === TypeScript.NodeType.VarDecl) { + var varDecl = ident.sym.declAST; + return this.getConstantValue(varDecl.init); + } + } + } + return null; + }; + Emitter.prototype.tryEmitConstant = function (dotExpr) { + if(!this.emitOptions.propagateConstants) { + return false; + } + var propertyName = dotExpr.operand2; + if(propertyName && propertyName.sym && propertyName.sym.isVariable()) { + if(TypeScript.hasFlag(propertyName.sym.flags, TypeScript.SymbolFlags.Constant)) { + if(propertyName.sym.declAST) { + var boundDecl = propertyName.sym.declAST; + var value = this.getConstantValue(boundDecl.init); + if(value !== null) { + this.writeToOutput(value.toString()); + var comment = " /* "; + comment += propertyName.actualText; + comment += " */ "; + this.writeToOutput(comment); + return true; + } + } + } + } + return false; + }; + Emitter.prototype.emitCall = function (callNode, target, args) { + if(!this.emitSuperCall(callNode)) { + if(!TypeScript.hasFlag(callNode.flags, TypeScript.ASTFlags.ClassBaseConstructorCall)) { + if(target.nodeType == TypeScript.NodeType.FuncDecl && !target.isParenthesized) { + this.writeToOutput("("); + } + if(callNode.target.nodeType == TypeScript.NodeType.Super && this.emitState.container == EmitContainer.Constructor) { + this.writeToOutput("_super.call"); + } else { + this.emitJavascript(target, TypeScript.TokenID.OpenParen, false); + } + if(target.nodeType == TypeScript.NodeType.FuncDecl && !target.isParenthesized) { + this.writeToOutput(")"); + } + this.recordSourceMappingStart(args); + this.writeToOutput("("); + if(callNode.target.nodeType == TypeScript.NodeType.Super && this.emitState.container == EmitContainer.Constructor) { + this.writeToOutput("this"); + if(args && args.members.length) { + this.writeToOutput(", "); + } + } + this.emitJavascriptList(args, ", ", TypeScript.TokenID.Comma, false, false, false); + this.writeToOutput(")"); + this.recordSourceMappingEnd(args); + } else { + this.indenter.decreaseIndent(); + this.indenter.decreaseIndent(); + var constructorCall = new TypeScript.ASTList(); + constructorCall.members[0] = callNode; + this.emitConstructorCalls(constructorCall, this.thisClassNode); + this.indenter.increaseIndent(); + this.indenter.increaseIndent(); + } + } + }; + Emitter.prototype.emitConstructorCalls = function (bases, classDecl) { + if(bases == null) { + return; + } + var basesLen = bases.members.length; + this.recordSourceMappingStart(classDecl); + for(var i = 0; i < basesLen; i++) { + var baseExpr = bases.members[i]; + var baseSymbol = null; + if(baseExpr.nodeType == TypeScript.NodeType.Call) { + baseSymbol = (baseExpr).target.type.symbol; + } else { + baseSymbol = baseExpr.type.symbol; + } + var baseName = baseSymbol.name; + if(baseSymbol.declModule != classDecl.type.symbol.declModule) { + baseName = baseSymbol.fullName(); + } + if(baseExpr.nodeType == TypeScript.NodeType.Call) { + this.emitIndent(); + this.writeToOutput("_super.call(this"); + var args = (baseExpr).arguments; + if(args && (args.members.length > 0)) { + this.writeToOutput(", "); + this.emitJavascriptList(args, ", ", TypeScript.TokenID.Comma, false, false, false); + } + this.writeToOutput(")"); + } else { + if(baseExpr.type && (baseExpr.type.isClassInstance())) { + this.emitIndent(); + this.writeToOutput(classDecl.name.actualText + "._super.constructor"); + this.writeToOutput(".call(this)"); + } + } + } + this.recordSourceMappingEnd(classDecl); + }; + Emitter.prototype.emitInnerFunction = function (funcDecl, printName, isMember, bases, hasSelfRef, classDecl) { + var isClassConstructor = funcDecl.isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod); + var hasNonObjectBaseType = isClassConstructor && TypeScript.hasFlag(this.thisClassNode.type.instanceType.typeFlags, TypeScript.TypeFlags.HasBaseType) && !TypeScript.hasFlag(this.thisClassNode.type.instanceType.typeFlags, TypeScript.TypeFlags.HasBaseTypeOfObject); + var classPropertiesMustComeAfterSuperCall = hasNonObjectBaseType && TypeScript.hasFlag((this.thisClassNode).varFlags, TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor); + var shouldParenthesize = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFunctionExpression) && !funcDecl.isParenthesized && !funcDecl.isAccessor() && (TypeScript.hasFlag(funcDecl.flags, TypeScript.ASTFlags.ExplicitSemicolon) || TypeScript.hasFlag(funcDecl.flags, TypeScript.ASTFlags.AutomaticSemicolon)); + this.emitParensAndCommentsInPlace(funcDecl, true); + if(shouldParenthesize) { + this.writeToOutput("("); + } + this.recordSourceMappingStart(funcDecl); + if(!(funcDecl.isAccessor() && (funcDecl.accessorSymbol).isObjectLitField)) { + this.writeToOutput("function "); + } + if(printName) { + var id = funcDecl.getNameText(); + if(id && !funcDecl.isAccessor()) { + if(funcDecl.name) { + this.recordSourceMappingStart(funcDecl.name); + } + this.writeToOutput(id); + if(funcDecl.name) { + this.recordSourceMappingEnd(funcDecl.name); + } + } + } + this.writeToOutput("("); + var argsLen = 0; + var i = 0; + var arg; + var defaultArgs = []; + if(funcDecl.arguments) { + var tempContainer = this.setContainer(EmitContainer.Args); + argsLen = funcDecl.arguments.members.length; + var printLen = argsLen; + if(funcDecl.variableArgList) { + printLen--; + } + for(i = 0; i < printLen; i++) { + arg = funcDecl.arguments.members[i]; + if(arg.init) { + defaultArgs.push(arg); + } + this.emitJavascript(arg, TypeScript.TokenID.OpenParen, false); + if(i < (printLen - 1)) { + this.writeToOutput(", "); + } + } + this.setContainer(tempContainer); + } + this.writeLineToOutput(") {"); + if(funcDecl.isConstructor) { + this.recordSourceMappingNameStart("constructor"); + } else if(funcDecl.isGetAccessor()) { + this.recordSourceMappingNameStart("get_" + funcDecl.getNameText()); + } else if(funcDecl.isSetAccessor()) { + this.recordSourceMappingNameStart("set_" + funcDecl.getNameText()); + } else { + this.recordSourceMappingNameStart(funcDecl.getNameText()); + } + this.indenter.increaseIndent(); + for(i = 0; i < defaultArgs.length; i++) { + var arg = defaultArgs[i]; + this.emitIndent(); + this.recordSourceMappingStart(arg); + this.writeToOutput("if (typeof " + arg.id.actualText + " === \"undefined\") { "); + this.recordSourceMappingStart(arg.id); + this.writeToOutput(arg.id.actualText); + this.recordSourceMappingEnd(arg.id); + this.writeToOutput(" = "); + this.emitJavascript(arg.init, TypeScript.TokenID.OpenParen, false); + this.writeLineToOutput("; }"); + this.recordSourceMappingEnd(arg); + } + if(funcDecl.isConstructor && ((funcDecl.classDecl).varFlags & TypeScript.VarFlags.MustCaptureThis)) { + this.writeCaptureThisStatement(funcDecl); + } + if(funcDecl.isConstructor && !classPropertiesMustComeAfterSuperCall) { + if(funcDecl.arguments) { + argsLen = funcDecl.arguments.members.length; + for(i = 0; i < argsLen; i++) { + arg = funcDecl.arguments.members[i]; + if((arg.varFlags & TypeScript.VarFlags.Property) != TypeScript.VarFlags.None) { + this.emitIndent(); + this.recordSourceMappingStart(arg); + this.recordSourceMappingStart(arg.id); + this.writeToOutput("this." + arg.id.actualText); + this.recordSourceMappingEnd(arg.id); + this.writeToOutput(" = "); + this.recordSourceMappingStart(arg.id); + this.writeToOutput(arg.id.actualText); + this.recordSourceMappingEnd(arg.id); + this.writeLineToOutput(";"); + this.recordSourceMappingEnd(arg); + } + } + } + if(!TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { + this.emitConstructorCalls(bases, classDecl); + } + } + if(hasSelfRef) { + this.writeCaptureThisStatement(funcDecl); + } + if(funcDecl.variableArgList) { + argsLen = funcDecl.arguments.members.length; + var lastArg = funcDecl.arguments.members[argsLen - 1]; + this.emitIndent(); + this.recordSourceMappingStart(lastArg); + this.writeToOutput("var "); + this.recordSourceMappingStart(lastArg.id); + this.writeToOutput(lastArg.id.actualText); + this.recordSourceMappingEnd(lastArg.id); + this.writeLineToOutput(" = [];"); + this.recordSourceMappingEnd(lastArg); + this.emitIndent(); + this.writeToOutput("for ("); + this.recordSourceMappingStart(lastArg); + this.writeToOutput("var _i = 0;"); + this.recordSourceMappingEnd(lastArg); + this.writeToOutput(" "); + this.recordSourceMappingStart(lastArg); + this.writeToOutput("_i < (arguments.length - " + (argsLen - 1) + ")"); + this.recordSourceMappingEnd(lastArg); + this.writeToOutput("; "); + this.recordSourceMappingStart(lastArg); + this.writeToOutput("_i++"); + this.recordSourceMappingEnd(lastArg); + this.writeLineToOutput(") {"); + this.indenter.increaseIndent(); + this.emitIndent(); + this.recordSourceMappingStart(lastArg); + this.writeToOutput(lastArg.id.actualText + "[_i] = arguments[_i + " + (argsLen - 1) + "];"); + this.recordSourceMappingEnd(lastArg); + this.writeLineToOutput(""); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeLineToOutput("}"); + } + if(funcDecl.isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod) && !classPropertiesMustComeAfterSuperCall) { + var nProps = (this.thisClassNode.members).members.length; + for(var i = 0; i < nProps; i++) { + if((this.thisClassNode.members).members[i].nodeType == TypeScript.NodeType.VarDecl) { + var varDecl = (this.thisClassNode.members).members[i]; + if(!TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static) && varDecl.init) { + this.emitIndent(); + this.emitJavascriptVarDecl(varDecl, TypeScript.TokenID.Tilde); + this.writeLineToOutput(""); + } + } + } + } + this.emitBareJavascriptStatements(funcDecl.bod, classPropertiesMustComeAfterSuperCall); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.recordSourceMappingStart(funcDecl.endingToken); + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(funcDecl.endingToken); + this.recordSourceMappingEnd(funcDecl); + if(shouldParenthesize) { + this.writeToOutput(")"); + } + this.recordSourceMappingEnd(funcDecl); + this.emitParensAndCommentsInPlace(funcDecl, false); + if(!isMember && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFunctionExpression) && (!TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Signature) || funcDecl.isConstructor)) { + this.writeLineToOutput(""); + } else if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFunctionExpression)) { + if(TypeScript.hasFlag(funcDecl.flags, TypeScript.ASTFlags.ExplicitSemicolon) || TypeScript.hasFlag(funcDecl.flags, TypeScript.ASTFlags.AutomaticSemicolon)) { + this.writeLineToOutput(";"); + } + } + }; + Emitter.prototype.emitJavascriptModule = function (moduleDecl) { + var modName = moduleDecl.name.actualText; + if(TypeScript.isTSFile(modName)) { + moduleDecl.name.setText(modName.substring(0, modName.length - 3)); + } else if(TypeScript.isSTRFile(modName)) { + moduleDecl.name.setText(modName.substring(0, modName.length - 4)); + } + if(!TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.Ambient)) { + var isDynamicMod = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsDynamic); + var prevOutFile = this.outfile; + var prevOutFileName = this.emittingFileName; + var prevAllSourceMappers = this.allSourceMappers; + var prevSourceMapper = this.sourceMapper; + var prevColumn = this.emitState.column; + var prevLine = this.emitState.line; + var temp = this.setContainer(EmitContainer.Module); + var svModuleName = this.moduleName; + var isExported = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.Exported); + this.moduleDeclList[this.moduleDeclList.length] = moduleDecl; + var isWholeFile = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsWholeFile); + this.moduleName = moduleDecl.name.actualText; + if(isDynamicMod) { + var tsModFileName = TypeScript.stripQuotes(moduleDecl.name.actualText); + var modFilePath = TypeScript.trimModName(tsModFileName) + ".js"; + modFilePath = this.emitOptions.mapOutputFileName(modFilePath, TypeScript.TypeScriptCompiler.mapToJSFileName); + if(this.emitOptions.ioHost) { + if(TypeScript.switchToForwardSlashes(modFilePath) != TypeScript.switchToForwardSlashes(this.emittingFileName)) { + this.emittingFileName = modFilePath; + var useUTF8InOutputfile = moduleDecl.containsUnicodeChar || (this.emitOptions.emitComments && moduleDecl.containsUnicodeCharInComment); + this.outfile = this.createFile(this.emittingFileName, useUTF8InOutputfile); + if(prevSourceMapper != null) { + this.allSourceMappers = []; + var sourceMappingFile = this.createFile(this.emittingFileName + TypeScript.SourceMapper.MapFileExtension, false); + this.setSourceMappings(new TypeScript.SourceMapper(tsModFileName, this.emittingFileName, this.outfile, sourceMappingFile, this.errorReporter, this.emitOptions.emitFullSourceMapPath)); + this.emitState.column = 0; + this.emitState.line = 0; + } + } else { + TypeScript.CompilerDiagnostics.assert(this.emitOptions.outputMany, "Cannot have dynamic modules compiling into single file"); + } + } + this.setContainer(EmitContainer.DynamicModule); + this.recordSourceMappingStart(moduleDecl); + if(TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { + var dependencyList = "[\"require\", \"exports\""; + var importList = "require, exports"; + var importStatement = null; + for(var i = 0; i < (moduleDecl.mod).importedModules.length; i++) { + importStatement = (moduleDecl.mod).importedModules[i]; + if(importStatement.id.sym && !(importStatement.id.sym).onlyReferencedAsTypeRef) { + if(i <= (moduleDecl.mod).importedModules.length - 1) { + dependencyList += ", "; + importList += ", "; + } + importList += "__" + importStatement.id.actualText + "__"; + dependencyList += importStatement.firstAliasedModToString(); + } + } + for(var i = 0; i < moduleDecl.amdDependencies.length; i++) { + dependencyList += ", \"" + moduleDecl.amdDependencies[i] + "\""; + } + dependencyList += "]"; + this.writeLineToOutput("define(" + dependencyList + "," + " function(" + importList + ") {"); + } else { + } + } else { + if(!isExported) { + this.recordSourceMappingStart(moduleDecl); + this.writeToOutput("var "); + this.recordSourceMappingStart(moduleDecl.name); + this.writeToOutput(this.moduleName); + this.recordSourceMappingEnd(moduleDecl.name); + this.writeLineToOutput(";"); + this.recordSourceMappingEnd(moduleDecl); + this.emitIndent(); + } + this.writeToOutput("("); + this.recordSourceMappingStart(moduleDecl); + this.writeToOutput("function ("); + this.recordSourceMappingStart(moduleDecl.name); + this.writeToOutput(this.moduleName); + this.recordSourceMappingEnd(moduleDecl.name); + this.writeLineToOutput(") {"); + } + if(!isWholeFile) { + this.recordSourceMappingNameStart(this.moduleName); + } + if(!isDynamicMod || TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { + this.indenter.increaseIndent(); + } + if(moduleDecl.modFlags & TypeScript.ModuleFlags.MustCaptureThis) { + this.writeCaptureThisStatement(moduleDecl); + } + this.emitJavascriptList(moduleDecl.members, null, TypeScript.TokenID.Semicolon, true, false, false); + if(!isDynamicMod || TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { + this.indenter.decreaseIndent(); + } + this.emitIndent(); + if(isDynamicMod) { + if(TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { + this.writeLineToOutput("})"); + } else { + } + if(!isWholeFile) { + this.recordSourceMappingNameEnd(); + } + this.recordSourceMappingEnd(moduleDecl); + if(this.outfile != prevOutFile) { + this.Close(); + if(prevSourceMapper != null) { + this.allSourceMappers = prevAllSourceMappers; + this.sourceMapper = prevSourceMapper; + this.emitState.column = prevColumn; + this.emitState.line = prevLine; + } + this.outfile = prevOutFile; + this.emittingFileName = prevOutFileName; + } + } else { + var containingMod = null; + if(moduleDecl.type && moduleDecl.type.symbol.container && moduleDecl.type.symbol.container.declAST) { + containingMod = moduleDecl.type.symbol.container.declAST; + } + var parentIsDynamic = containingMod && TypeScript.hasFlag(containingMod.modFlags, TypeScript.ModuleFlags.IsDynamic); + this.recordSourceMappingStart(moduleDecl.endingToken); + if(temp == EmitContainer.Prog && isExported) { + this.writeToOutput("}"); + if(!isWholeFile) { + this.recordSourceMappingNameEnd(); + } + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeToOutput(")(this." + this.moduleName + " || (this." + this.moduleName + " = {}));"); + } else if(isExported || temp == EmitContainer.Prog) { + var dotMod = svModuleName != "" ? (parentIsDynamic ? "exports" : svModuleName) + "." : svModuleName; + this.writeToOutput("}"); + if(!isWholeFile) { + this.recordSourceMappingNameEnd(); + } + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeToOutput(")(" + dotMod + this.moduleName + " || (" + dotMod + this.moduleName + " = {}));"); + } else if(!isExported && temp != EmitContainer.Prog) { + this.writeToOutput("}"); + if(!isWholeFile) { + this.recordSourceMappingNameEnd(); + } + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeToOutput(")(" + this.moduleName + " || (" + this.moduleName + " = {}));"); + } else { + this.writeToOutput("}"); + if(!isWholeFile) { + this.recordSourceMappingNameEnd(); + } + this.recordSourceMappingEnd(moduleDecl.endingToken); + this.writeToOutput(")();"); + } + this.recordSourceMappingEnd(moduleDecl); + this.writeLineToOutput(""); + if(temp != EmitContainer.Prog && isExported) { + this.emitIndent(); + this.recordSourceMappingStart(moduleDecl); + if(parentIsDynamic) { + this.writeLineToOutput("var " + this.moduleName + " = exports." + this.moduleName + ";"); + } else { + this.writeLineToOutput("var " + this.moduleName + " = " + svModuleName + "." + this.moduleName + ";"); + } + this.recordSourceMappingEnd(moduleDecl); + } + } + this.setContainer(temp); + this.moduleName = svModuleName; + this.moduleDeclList.length--; + } + }; + Emitter.prototype.emitIndex = function (operand1, operand2) { + var temp = this.setInObjectLiteral(false); + this.emitJavascript(operand1, TypeScript.TokenID.Tilde, false); + this.writeToOutput("["); + this.emitJavascriptList(operand2, ", ", TypeScript.TokenID.Comma, false, false, false); + this.writeToOutput("]"); + this.setInObjectLiteral(temp); + }; + Emitter.prototype.emitStringLiteral = function (text) { + this.writeToOutput(text); + }; + Emitter.prototype.emitJavascriptFunction = function (funcDecl) { + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Signature) || funcDecl.isOverload) { + return; + } + var temp; + var tempFnc = this.thisFnc; + this.thisFnc = funcDecl; + if(funcDecl.isConstructor) { + temp = this.setContainer(EmitContainer.Constructor); + } else { + temp = this.setContainer(EmitContainer.Function); + } + var bases = null; + var hasSelfRef = false; + var funcName = funcDecl.getNameText(); + if((this.emitState.inObjectLiteral || !funcDecl.isAccessor()) && ((temp != EmitContainer.Constructor) || ((funcDecl.fncFlags & TypeScript.FncFlags.Method) == TypeScript.FncFlags.None))) { + var tempLit = this.setInObjectLiteral(false); + if(this.thisClassNode) { + bases = this.thisClassNode.extendsList; + } + hasSelfRef = Emitter.shouldCaptureThis(funcDecl); + this.recordSourceMappingStart(funcDecl); + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Exported | TypeScript.FncFlags.ClassPropertyMethodExported) && funcDecl.type.symbol.container == this.checker.gloMod && !funcDecl.isConstructor) { + this.writeToOutput("this." + funcName + " = "); + this.emitInnerFunction(funcDecl, false, false, bases, hasSelfRef, this.thisClassNode); + } else { + this.emitInnerFunction(funcDecl, (funcDecl.name && !funcDecl.name.isMissing()), false, bases, hasSelfRef, this.thisClassNode); + } + this.setInObjectLiteral(tempLit); + } + this.setContainer(temp); + this.thisFnc = tempFnc; + if(!TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Signature)) { + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static)) { + if(this.thisClassNode) { + if(funcDecl.isAccessor()) { + this.emitPropertyAccessor(funcDecl, this.thisClassNode.name.actualText, false); + } else { + this.emitIndent(); + this.recordSourceMappingStart(funcDecl); + this.writeLineToOutput(this.thisClassNode.name.actualText + "." + funcName + " = " + funcName + ";"); + this.recordSourceMappingEnd(funcDecl); + } + } + } else if((this.emitState.container == EmitContainer.Module || this.emitState.container == EmitContainer.DynamicModule) && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Exported | TypeScript.FncFlags.ClassPropertyMethodExported)) { + this.emitIndent(); + var modName = this.emitState.container == EmitContainer.Module ? this.moduleName : "exports"; + this.recordSourceMappingStart(funcDecl); + this.writeLineToOutput(modName + "." + funcName + " = " + funcName + ";"); + this.recordSourceMappingEnd(funcDecl); + } + } + }; + Emitter.prototype.emitAmbientVarDecl = function (varDecl) { + if(varDecl.init) { + this.emitParensAndCommentsInPlace(varDecl, true); + this.recordSourceMappingStart(varDecl); + this.recordSourceMappingStart(varDecl.id); + this.writeToOutput(varDecl.id.actualText); + this.recordSourceMappingEnd(varDecl.id); + this.writeToOutput(" = "); + this.emitJavascript(varDecl.init, TypeScript.TokenID.Comma, false); + this.recordSourceMappingEnd(varDecl); + this.writeToOutput(";"); + this.emitParensAndCommentsInPlace(varDecl, false); + } + }; + Emitter.prototype.varListCount = function () { + return this.varListCountStack[this.varListCountStack.length - 1]; + }; + Emitter.prototype.emitVarDeclVar = function () { + if(this.varListCount() >= 0) { + this.writeToOutput("var "); + this.setInVarBlock(-this.varListCount()); + } + return true; + }; + Emitter.prototype.onEmitVar = function () { + if(this.varListCount() > 0) { + this.setInVarBlock(this.varListCount() - 1); + } else if(this.varListCount() < 0) { + this.setInVarBlock(this.varListCount() + 1); + } + }; + Emitter.prototype.emitJavascriptVarDecl = function (varDecl, tokenId) { + if((varDecl.varFlags & TypeScript.VarFlags.Ambient) == TypeScript.VarFlags.Ambient) { + this.emitAmbientVarDecl(varDecl); + this.onEmitVar(); + } else { + var sym = varDecl.sym; + var hasInitializer = (varDecl.init != null); + this.emitParensAndCommentsInPlace(varDecl, true); + this.recordSourceMappingStart(varDecl); + if(sym && sym.isMember() && sym.container && (sym.container.kind() == TypeScript.SymbolKind.Type)) { + var type = (sym.container).type; + if(type.isClass() && (!TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.ModuleMember))) { + if(this.emitState.container != EmitContainer.Args) { + if(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Static)) { + this.writeToOutput(sym.container.name + "."); + } else { + this.writeToOutput("this."); + } + } + } else if(type.hasImplementation()) { + if(!TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Exported) && (sym.container == this.checker.gloMod || !TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Property))) { + this.emitVarDeclVar(); + } else if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.LocalStatic)) { + this.writeToOutput("."); + } else { + if(this.emitState.container == EmitContainer.DynamicModule) { + this.writeToOutput("exports."); + } else { + this.writeToOutput(this.moduleName + "."); + } + } + } else { + if(tokenId != TypeScript.TokenID.OpenParen) { + if(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Exported) && sym.container == this.checker.gloMod) { + this.writeToOutput("this."); + } else { + this.emitVarDeclVar(); + } + } + } + } else { + if(tokenId != TypeScript.TokenID.OpenParen) { + this.emitVarDeclVar(); + } + } + this.recordSourceMappingStart(varDecl.id); + this.writeToOutput(varDecl.id.actualText); + this.recordSourceMappingEnd(varDecl.id); + if(hasInitializer) { + this.writeToOutputTrimmable(" = "); + this.varListCountStack.push(0); + this.emitJavascript(varDecl.init, TypeScript.TokenID.Comma, false); + this.varListCountStack.pop(); + } + this.onEmitVar(); + if((tokenId != TypeScript.TokenID.OpenParen)) { + if(this.varListCount() < 0) { + this.writeToOutput(", "); + } else if(tokenId != TypeScript.TokenID.For) { + this.writeToOutputTrimmable(";"); + } + } + this.recordSourceMappingEnd(varDecl); + this.emitParensAndCommentsInPlace(varDecl, false); + } + }; + Emitter.prototype.declEnclosed = function (moduleDecl) { + if(moduleDecl == null) { + return true; + } + for(var i = 0, len = this.moduleDeclList.length; i < len; i++) { + if(this.moduleDeclList[i] == moduleDecl) { + return true; + } + } + return false; + }; + Emitter.prototype.emitJavascriptName = function (name, addThis) { + var sym = name.sym; + this.emitParensAndCommentsInPlace(name, true); + this.recordSourceMappingStart(name); + if(!name.isMissing()) { + if(addThis && (this.emitState.container != EmitContainer.Args) && sym) { + if(sym.container && (sym.container.name != TypeScript.globalId)) { + if(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Static) && (TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Property))) { + if(sym.declModule && TypeScript.hasFlag(sym.declModule.modFlags, TypeScript.ModuleFlags.IsDynamic)) { + this.writeToOutput("exports."); + } else { + this.writeToOutput(sym.container.name + "."); + } + } else if(sym.kind() == TypeScript.SymbolKind.Field) { + var fieldSym = sym; + if(TypeScript.hasFlag(fieldSym.flags, TypeScript.SymbolFlags.ModuleMember)) { + if((sym.container != this.checker.gloMod) && ((TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Property)) || TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Exported))) { + if(TypeScript.hasFlag(sym.declModule.modFlags, TypeScript.ModuleFlags.IsDynamic)) { + this.writeToOutput("exports."); + } else { + this.writeToOutput(sym.container.name + "."); + } + } + } else { + if(sym.isInstanceProperty()) { + this.emitThis(); + this.writeToOutput("."); + } + } + } else if(sym.kind() == TypeScript.SymbolKind.Type) { + if(sym.isInstanceProperty()) { + var typeSym = sym; + var type = typeSym.type; + if(type.call && !TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.ModuleMember)) { + this.emitThis(); + this.writeToOutput("."); + } + } else if((sym.unitIndex != this.checker.locationInfo.unitIndex) || (!this.declEnclosed(sym.declModule))) { + this.writeToOutput(sym.container.name + "."); + } + } + } else if(sym.container == this.checker.gloMod && TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Exported) && !TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Ambient) && !((sym.isType() || sym.isMember()) && sym.declModule && TypeScript.hasFlag(sym.declModule.modFlags, TypeScript.ModuleFlags.Ambient)) && this.emitState.container == EmitContainer.Prog && sym.declAST.nodeType != TypeScript.NodeType.FuncDecl) { + this.writeToOutput("this."); + } + } + if(sym && sym.declAST && sym.declAST.nodeType == TypeScript.NodeType.ModuleDeclaration && (TypeScript.hasFlag((sym.declAST).modFlags, TypeScript.ModuleFlags.IsDynamic))) { + var moduleDecl = sym.declAST; + if(TypeScript.moduleGenTarget == TypeScript.ModuleGenTarget.Asynchronous) { + this.writeLineToOutput("__" + this.modAliasId + "__;"); + } else { + var modPath = name.actualText; + var isSingleQuotedMod = TypeScript.isSingleQuoted(modPath); + var isAmbient = moduleDecl.mod.symbol.declAST && TypeScript.hasFlag((moduleDecl.mod.symbol.declAST).modFlags, TypeScript.ModuleFlags.Ambient); + modPath = isAmbient ? modPath : this.firstModAlias ? this.firstModAlias : TypeScript.quoteBaseName(modPath); + modPath = isAmbient ? modPath : (!TypeScript.isRelative(TypeScript.stripQuotes(modPath)) ? TypeScript.quoteStr("./" + TypeScript.stripQuotes(modPath)) : modPath); + if(isSingleQuotedMod) { + modPath = TypeScript.changeToSingleQuote(modPath); + } + this.writeToOutput("require(" + modPath + ")"); + } + } else { + this.writeToOutput(name.actualText); + } + } + this.recordSourceMappingEnd(name); + this.emitParensAndCommentsInPlace(name, false); + }; + Emitter.prototype.emitJavascriptStatements = function (stmts, emitEmptyBod) { + if(stmts) { + if(stmts.nodeType != TypeScript.NodeType.Block) { + var hasContents = (stmts && (stmts.nodeType != TypeScript.NodeType.List || ((stmts).members.length > 0))); + if(emitEmptyBod || hasContents) { + var hasOnlyBlockStatement = ((stmts.nodeType == TypeScript.NodeType.Block) || ((stmts.nodeType == TypeScript.NodeType.List) && ((stmts).members.length == 1) && ((stmts).members[0].nodeType == TypeScript.NodeType.Block))); + this.recordSourceMappingStart(stmts); + if(!hasOnlyBlockStatement) { + this.writeLineToOutput(" {"); + this.indenter.increaseIndent(); + } + this.emitJavascriptList(stmts, null, TypeScript.TokenID.Semicolon, true, false, false); + if(!hasOnlyBlockStatement) { + this.writeLineToOutput(""); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeToOutput("}"); + } + this.recordSourceMappingEnd(stmts); + } + } else { + this.emitJavascript(stmts, TypeScript.TokenID.Semicolon, true); + } + } else if(emitEmptyBod) { + this.writeToOutput("{ }"); + } + }; + Emitter.prototype.emitBareJavascriptStatements = function (stmts, emitClassPropertiesAfterSuperCall) { + if (typeof emitClassPropertiesAfterSuperCall === "undefined") { emitClassPropertiesAfterSuperCall = false; } + if(stmts.nodeType != TypeScript.NodeType.Block) { + if(stmts.nodeType == TypeScript.NodeType.List) { + var stmtList = stmts; + if((stmtList.members.length == 2) && (stmtList.members[0].nodeType == TypeScript.NodeType.Block) && (stmtList.members[1].nodeType == TypeScript.NodeType.EndCode)) { + this.emitJavascript(stmtList.members[0], TypeScript.TokenID.Semicolon, true); + this.writeLineToOutput(""); + } else { + this.emitJavascriptList(stmts, null, TypeScript.TokenID.Semicolon, true, false, emitClassPropertiesAfterSuperCall); + } + } else { + this.emitJavascript(stmts, TypeScript.TokenID.Semicolon, true); + } + } else { + this.emitJavascript(stmts, TypeScript.TokenID.Semicolon, true); + } + }; + Emitter.prototype.recordSourceMappingNameStart = function (name) { + if(this.sourceMapper) { + var finalName = name; + if(!name) { + finalName = ""; + } else if(this.sourceMapper.currentNameIndex.length > 0) { + finalName = this.sourceMapper.names[this.sourceMapper.currentNameIndex[this.sourceMapper.currentNameIndex.length - 1]] + "." + name; + } + this.sourceMapper.names.push(finalName); + this.sourceMapper.currentNameIndex.push(this.sourceMapper.names.length - 1); + } + }; + Emitter.prototype.recordSourceMappingNameEnd = function () { + if(this.sourceMapper) { + this.sourceMapper.currentNameIndex.pop(); + } + }; + Emitter.prototype.recordSourceMappingStart = function (ast) { + if(this.sourceMapper && TypeScript.isValidAstNode(ast)) { + var lineCol = { + line: -1, + col: -1 + }; + var sourceMapping = new TypeScript.SourceMapping(); + sourceMapping.start.emittedColumn = this.emitState.column; + sourceMapping.start.emittedLine = this.emitState.line; + TypeScript.getSourceLineColFromMap(lineCol, ast.minChar, this.checker.locationInfo.lineMap); + sourceMapping.start.sourceColumn = lineCol.col; + sourceMapping.start.sourceLine = lineCol.line; + TypeScript.getSourceLineColFromMap(lineCol, ast.limChar, this.checker.locationInfo.lineMap); + sourceMapping.end.sourceColumn = lineCol.col; + sourceMapping.end.sourceLine = lineCol.line; + if(this.sourceMapper.currentNameIndex.length > 0) { + sourceMapping.nameIndex = this.sourceMapper.currentNameIndex[this.sourceMapper.currentNameIndex.length - 1]; + } + var siblings = this.sourceMapper.currentMappings[this.sourceMapper.currentMappings.length - 1]; + siblings.push(sourceMapping); + this.sourceMapper.currentMappings.push(sourceMapping.childMappings); + } + }; + Emitter.prototype.recordSourceMappingEnd = function (ast) { + if(this.sourceMapper && TypeScript.isValidAstNode(ast)) { + this.sourceMapper.currentMappings.pop(); + var siblings = this.sourceMapper.currentMappings[this.sourceMapper.currentMappings.length - 1]; + var sourceMapping = siblings[siblings.length - 1]; + sourceMapping.end.emittedColumn = this.emitState.column; + sourceMapping.end.emittedLine = this.emitState.line; + } + }; + Emitter.prototype.Close = function () { + if(this.sourceMapper != null) { + TypeScript.SourceMapper.EmitSourceMapping(this.allSourceMappers); + } + try { + this.outfile.Close(); + } catch (ex) { + this.errorReporter.emitterError(null, ex.message); + } + }; + Emitter.prototype.emitJavascriptList = function (ast, delimiter, tokenId, startLine, onlyStatics, emitClassPropertiesAfterSuperCall, emitPrologue, requiresExtendsBlock) { + if (typeof emitClassPropertiesAfterSuperCall === "undefined") { emitClassPropertiesAfterSuperCall = false; } + if (typeof emitPrologue === "undefined") { emitPrologue = false; } + if(ast == null) { + return; + } else if(ast.nodeType != TypeScript.NodeType.List) { + this.emitPrologue(emitPrologue); + this.emitJavascript(ast, tokenId, startLine); + } else { + var list = ast; + this.emitParensAndCommentsInPlace(ast, true); + if(list.members.length == 0) { + this.emitParensAndCommentsInPlace(ast, false); + return; + } + var len = list.members.length; + for(var i = 0; i < len; i++) { + if(emitPrologue) { + if(i == 1 || !TypeScript.hasFlag(list.flags, TypeScript.ASTFlags.StrictMode)) { + this.emitPrologue(requiresExtendsBlock); + emitPrologue = false; + } + } + if(i == 1 && emitClassPropertiesAfterSuperCall) { + var constructorDecl = (this.thisClassNode).constructorDecl; + if(constructorDecl && constructorDecl.arguments) { + var argsLen = constructorDecl.arguments.members.length; + for(var iArg = 0; iArg < argsLen; iArg++) { + var arg = constructorDecl.arguments.members[iArg]; + if((arg.varFlags & TypeScript.VarFlags.Property) != TypeScript.VarFlags.None) { + this.emitIndent(); + this.recordSourceMappingStart(arg); + this.recordSourceMappingStart(arg.id); + this.writeToOutput("this." + arg.id.actualText); + this.recordSourceMappingEnd(arg.id); + this.writeToOutput(" = "); + this.recordSourceMappingStart(arg.id); + this.writeToOutput(arg.id.actualText); + this.recordSourceMappingEnd(arg.id); + this.writeLineToOutput(";"); + this.recordSourceMappingEnd(arg); + } + } + } + var nProps = (this.thisClassNode.members).members.length; + for(var iMember = 0; iMember < nProps; iMember++) { + if((this.thisClassNode.members).members[iMember].nodeType == TypeScript.NodeType.VarDecl) { + var varDecl = (this.thisClassNode.members).members[iMember]; + if(!TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static) && varDecl.init) { + this.emitIndent(); + this.emitJavascriptVarDecl(varDecl, TypeScript.TokenID.Tilde); + this.writeLineToOutput(""); + } + } + } + } + var emitNode = list.members[i]; + var isStaticDecl = (emitNode.nodeType == TypeScript.NodeType.FuncDecl && TypeScript.hasFlag((emitNode).fncFlags, TypeScript.FncFlags.Static)) || (emitNode.nodeType == TypeScript.NodeType.VarDecl && TypeScript.hasFlag((emitNode).varFlags, TypeScript.VarFlags.Static)); + if(onlyStatics ? !isStaticDecl : isStaticDecl) { + continue; + } + this.emitJavascript(emitNode, tokenId, startLine); + if(delimiter && (i < (len - 1))) { + if(startLine) { + this.writeLineToOutput(delimiter); + } else { + this.writeToOutput(delimiter); + } + } else if(startLine && (emitNode.nodeType != TypeScript.NodeType.ModuleDeclaration) && (emitNode.nodeType != TypeScript.NodeType.InterfaceDeclaration) && (!((emitNode.nodeType == TypeScript.NodeType.VarDecl) && ((((emitNode).varFlags) & TypeScript.VarFlags.Ambient) == TypeScript.VarFlags.Ambient) && (((emitNode).init) == null)) && this.varListCount() >= 0) && (emitNode.nodeType != TypeScript.NodeType.Block || (emitNode).isStatementBlock) && (emitNode.nodeType != TypeScript.NodeType.EndCode) && (emitNode.nodeType != TypeScript.NodeType.FuncDecl)) { + this.writeLineToOutput(""); + } + } + this.emitParensAndCommentsInPlace(ast, false); + } + }; + Emitter.prototype.emitJavascript = function (ast, tokenId, startLine) { + if(ast == null) { + return; + } + if(startLine && (this.indenter.indentAmt > 0) && (ast.nodeType != TypeScript.NodeType.List) && (ast.nodeType != TypeScript.NodeType.Block)) { + if((ast.nodeType != TypeScript.NodeType.InterfaceDeclaration) && (!((ast.nodeType == TypeScript.NodeType.VarDecl) && ((((ast).varFlags) & TypeScript.VarFlags.Ambient) == TypeScript.VarFlags.Ambient) && (((ast).init) == null)) && this.varListCount() >= 0) && (ast.nodeType != TypeScript.NodeType.EndCode) && ((ast.nodeType != TypeScript.NodeType.FuncDecl) || (this.emitState.container != EmitContainer.Constructor))) { + this.emitIndent(); + } + } + ast.emit(this, tokenId, startLine); + if((tokenId == TypeScript.TokenID.Semicolon) && (ast.nodeType < TypeScript.NodeType.GeneralNode)) { + this.writeToOutput(";"); + } + }; + Emitter.prototype.emitPropertyAccessor = function (funcDecl, className, isProto) { + if(!(funcDecl.accessorSymbol).hasBeenEmitted) { + var accessorSymbol = funcDecl.accessorSymbol; + this.emitIndent(); + this.recordSourceMappingStart(funcDecl); + this.writeLineToOutput("Object.defineProperty(" + className + (isProto ? ".prototype, \"" : ", \"") + funcDecl.name.actualText + "\"" + ", {"); + this.indenter.increaseIndent(); + if(accessorSymbol.getter) { + var getter = accessorSymbol.getter.declAST; + this.emitIndent(); + this.recordSourceMappingStart(getter); + this.writeToOutput("get: "); + this.emitInnerFunction(getter, false, isProto, null, Emitter.shouldCaptureThis(getter), null); + this.writeLineToOutput(","); + } + if(accessorSymbol.setter) { + var setter = accessorSymbol.setter.declAST; + this.emitIndent(); + this.recordSourceMappingStart(setter); + this.writeToOutput("set: "); + this.emitInnerFunction(setter, false, isProto, null, Emitter.shouldCaptureThis(setter), null); + this.writeLineToOutput(","); + } + this.emitIndent(); + this.writeLineToOutput("enumerable: true,"); + this.emitIndent(); + this.writeLineToOutput("configurable: true"); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeLineToOutput("});"); + this.recordSourceMappingEnd(funcDecl); + accessorSymbol.hasBeenEmitted = true; + } + }; + Emitter.prototype.emitPrototypeMember = function (member, className) { + if(member.nodeType == TypeScript.NodeType.FuncDecl) { + var funcDecl = member; + if(funcDecl.isAccessor()) { + this.emitPropertyAccessor(funcDecl, className, true); + } else { + this.emitIndent(); + this.recordSourceMappingStart(funcDecl); + this.writeToOutput(className + ".prototype." + funcDecl.getNameText() + " = "); + this.emitInnerFunction(funcDecl, false, true, null, Emitter.shouldCaptureThis(funcDecl), null); + this.writeLineToOutput(";"); + } + } else if(member.nodeType == TypeScript.NodeType.VarDecl) { + var varDecl = member; + if(varDecl.init) { + this.emitIndent(); + this.recordSourceMappingStart(varDecl); + this.recordSourceMappingStart(varDecl.id); + this.writeToOutput(className + ".prototype." + varDecl.id.actualText); + this.recordSourceMappingEnd(varDecl.id); + this.writeToOutput(" = "); + this.emitJavascript(varDecl.init, TypeScript.TokenID.Equals, false); + this.recordSourceMappingEnd(varDecl); + this.writeLineToOutput(";"); + } + } + }; + Emitter.prototype.emitAddBaseMethods = function (className, base, classDecl) { + if(base.members) { + var baseSymbol = base.symbol; + var baseName = baseSymbol.name; + if(baseSymbol.declModule != classDecl.type.symbol.declModule) { + baseName = baseSymbol.fullName(); + } + base.members.allMembers.map(function (key, s, c) { + var sym = s; + if((sym.kind() == TypeScript.SymbolKind.Type) && (sym).type.call) { + this.recordSourceMappingStart(sym.declAST); + this.writeLineToOutput(className + ".prototype." + sym.name + " = " + baseName + ".prototype." + sym.name + ";"); + this.recordSourceMappingEnd(sym.declAST); + } + }, null); + } + if(base.extendsList) { + for(var i = 0, len = base.extendsList.length; i < len; i++) { + this.emitAddBaseMethods(className, base.extendsList[i], classDecl); + } + } + }; + Emitter.prototype.emitJavascriptClass = function (classDecl) { + if(!TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Ambient)) { + var svClassNode = this.thisClassNode; + var i = 0; + this.thisClassNode = classDecl; + var className = classDecl.name.actualText; + this.emitParensAndCommentsInPlace(classDecl, true); + var temp = this.setContainer(EmitContainer.Class); + this.recordSourceMappingStart(classDecl); + if(TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Exported) && classDecl.type.symbol.container == this.checker.gloMod) { + this.writeToOutput("this." + className); + } else { + this.writeToOutput("var " + className); + } + var hasBaseClass = classDecl.extendsList && classDecl.extendsList.members.length; + var baseNameDecl = null; + var baseName = null; + if(hasBaseClass) { + this.writeLineToOutput(" = (function (_super) {"); + } else { + this.writeLineToOutput(" = (function () {"); + } + this.recordSourceMappingNameStart(className); + this.indenter.increaseIndent(); + if(hasBaseClass) { + baseNameDecl = classDecl.extendsList.members[0]; + baseName = baseNameDecl.nodeType == TypeScript.NodeType.Call ? (baseNameDecl).target : baseNameDecl; + this.emitIndent(); + this.writeLineToOutput("__extends(" + className + ", _super);"); + } + this.emitIndent(); + var constrDecl = classDecl.constructorDecl; + if(constrDecl) { + this.emitJavascript(classDecl.constructorDecl, TypeScript.TokenID.OpenParen, false); + } else { + var wroteProps = 0; + this.recordSourceMappingStart(classDecl); + this.indenter.increaseIndent(); + this.writeToOutput("function " + classDecl.name.actualText + "() {"); + this.recordSourceMappingNameStart("constructor"); + if(hasBaseClass) { + this.writeLineToOutput(""); + this.emitIndent(); + this.writeLineToOutput("_super.apply(this, arguments);"); + wroteProps++; + } + if(classDecl.varFlags & TypeScript.VarFlags.MustCaptureThis) { + this.writeCaptureThisStatement(classDecl); + } + var members = (this.thisClassNode.members).members; + for(var i = 0; i < members.length; i++) { + if(members[i].nodeType == TypeScript.NodeType.VarDecl) { + var varDecl = members[i]; + if(!TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static) && varDecl.init) { + this.writeLineToOutput(""); + this.emitIndent(); + this.emitJavascriptVarDecl(varDecl, TypeScript.TokenID.Tilde); + wroteProps++; + } + } + } + if(wroteProps) { + this.writeLineToOutput(""); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.writeLineToOutput("}"); + } else { + this.writeLineToOutput(" }"); + this.indenter.decreaseIndent(); + } + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(classDecl); + } + var membersLen = classDecl.members.members.length; + for(var j = 0; j < membersLen; j++) { + var memberDecl = classDecl.members.members[j]; + if(memberDecl.nodeType == TypeScript.NodeType.FuncDecl) { + var fn = memberDecl; + if(TypeScript.hasFlag(fn.fncFlags, TypeScript.FncFlags.Method) && !fn.isSignature()) { + if(!TypeScript.hasFlag(fn.fncFlags, TypeScript.FncFlags.Static)) { + this.emitPrototypeMember(fn, className); + } else { + if(fn.isAccessor()) { + this.emitPropertyAccessor(fn, this.thisClassNode.name.actualText, false); + } else { + this.emitIndent(); + this.recordSourceMappingStart(fn); + this.writeToOutput(classDecl.name.actualText + "." + fn.name.actualText + " = "); + this.emitInnerFunction(fn, (fn.name && !fn.name.isMissing()), true, null, Emitter.shouldCaptureThis(fn), null); + this.writeLineToOutput(";"); + } + } + } + } else if(memberDecl.nodeType == TypeScript.NodeType.VarDecl) { + var varDecl = memberDecl; + if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static)) { + if(varDecl.init) { + this.emitIndent(); + this.recordSourceMappingStart(varDecl); + this.writeToOutput(classDecl.name.actualText + "." + varDecl.id.actualText + " = "); + this.emitJavascript(varDecl.init, TypeScript.TokenID.Equals, false); + this.writeLineToOutput(";"); + this.recordSourceMappingEnd(varDecl); + } + } + } else { + throw Error("We want to catch this"); + } + } + this.emitIndent(); + this.recordSourceMappingStart(classDecl.endingToken); + this.writeLineToOutput("return " + className + ";"); + this.recordSourceMappingEnd(classDecl.endingToken); + this.indenter.decreaseIndent(); + this.emitIndent(); + this.recordSourceMappingStart(classDecl.endingToken); + this.writeToOutput("}"); + this.recordSourceMappingNameEnd(); + this.recordSourceMappingEnd(classDecl.endingToken); + this.recordSourceMappingStart(classDecl); + this.writeToOutput(")("); + if(hasBaseClass) { + this.emitJavascript(baseName, TypeScript.TokenID.Tilde, false); + } + this.writeToOutput(");"); + this.recordSourceMappingEnd(classDecl); + if((temp == EmitContainer.Module || temp == EmitContainer.DynamicModule) && TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Exported)) { + this.writeLineToOutput(""); + this.emitIndent(); + var modName = temp == EmitContainer.Module ? this.moduleName : "exports"; + this.recordSourceMappingStart(classDecl); + this.writeToOutput(modName + "." + className + " = " + className + ";"); + this.recordSourceMappingEnd(classDecl); + } + this.emitIndent(); + this.recordSourceMappingEnd(classDecl); + this.emitParensAndCommentsInPlace(classDecl, false); + this.setContainer(temp); + this.thisClassNode = svClassNode; + } + }; + Emitter.prototype.emitPrologue = function (reqInherits) { + if(!this.extendsPrologueEmitted) { + if(reqInherits) { + this.extendsPrologueEmitted = true; + this.writeLineToOutput("var __extends = this.__extends || function (d, b) {"); + this.writeLineToOutput(" function __() { this.constructor = d; }"); + this.writeLineToOutput(" __.prototype = b.prototype;"); + this.writeLineToOutput(" d.prototype = new __();"); + this.writeLineToOutput("};"); + } + } + if(!this.globalThisCapturePrologueEmitted) { + if(this.checker.mustCaptureGlobalThis) { + this.globalThisCapturePrologueEmitted = true; + this.writeLineToOutput(this.captureThisStmtString); + } + } + }; + Emitter.prototype.emitSuperReference = function () { + this.writeToOutput("_super.prototype"); + }; + Emitter.prototype.emitSuperCall = function (callEx) { + if(callEx.target.nodeType == TypeScript.NodeType.Dot) { + var dotNode = callEx.target; + if(dotNode.operand1.nodeType == TypeScript.NodeType.Super) { + this.emitJavascript(dotNode, TypeScript.TokenID.OpenParen, false); + this.writeToOutput(".call("); + this.emitThis(); + if(callEx.arguments && callEx.arguments.members.length > 0) { + this.writeToOutput(", "); + this.emitJavascriptList(callEx.arguments, ", ", TypeScript.TokenID.Comma, false, false, false); + } + this.writeToOutput(")"); + return true; + } + } + return false; + }; + Emitter.prototype.emitThis = function () { + if(this.thisFnc && !this.thisFnc.isMethod() && (!this.thisFnc.isConstructor)) { + this.writeToOutput("_this"); + } else { + this.writeToOutput("this"); + } + }; + Emitter.shouldCaptureThis = function shouldCaptureThis(func) { + return func.hasSelfReference() || func.hasSuperReferenceInFatArrowFunction(); + }; + Emitter.prototype.createFile = function (fileName, useUTF8) { + try { + return this.emitOptions.ioHost.createFile(fileName, useUTF8); + } catch (ex) { + this.errorReporter.emitterError(null, ex.message); + } + }; + return Emitter; + })(); + TypeScript.Emitter = Emitter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ErrorReporter = (function () { + function ErrorReporter(outfile) { + this.outfile = outfile; + this.parser = null; + this.checker = null; + this.lineCol = { + line: 0, + col: 0 + }; + this.emitAsComments = true; + this.hasErrors = false; + this.pushToErrorSink = false; + this.errorSink = []; + } + ErrorReporter.prototype.getCapturedErrors = function () { + return this.errorSink; + }; + ErrorReporter.prototype.freeCapturedErrors = function () { + this.errorSink = []; + }; + ErrorReporter.prototype.captureError = function (emsg) { + this.errorSink[this.errorSink.length] = emsg; + }; + ErrorReporter.prototype.setErrOut = function (outerr) { + this.outfile = outerr; + this.emitAsComments = false; + }; + ErrorReporter.prototype.emitPrefix = function () { + if(this.emitAsComments) { + this.outfile.Write("// "); + } + this.outfile.Write(this.checker.locationInfo.filename + "(" + this.lineCol.line + "," + this.lineCol.col + "): "); + }; + ErrorReporter.prototype.writePrefix = function (ast) { + if(ast) { + this.setError(ast); + } else { + this.lineCol.line = 0; + this.lineCol.col = 0; + } + this.emitPrefix(); + }; + ErrorReporter.prototype.writePrefixFromSym = function (symbol) { + if(symbol && this.checker.locationInfo.lineMap) { + TypeScript.getSourceLineColFromMap(this.lineCol, symbol.location, this.checker.locationInfo.lineMap); + } else { + this.lineCol.line = -1; + this.lineCol.col = -1; + } + this.emitPrefix(); + }; + ErrorReporter.prototype.setError = function (ast) { + if(ast) { + ast.flags |= TypeScript.ASTFlags.Error; + if(this.checker.locationInfo.lineMap) { + TypeScript.getSourceLineColFromMap(this.lineCol, ast.minChar, this.checker.locationInfo.lineMap); + } + } + }; + ErrorReporter.prototype.reportError = function (ast, message) { + if(this.pushToErrorSink) { + this.captureError(message); + return; + } + this.hasErrors = true; + if(ast && this.parser.errorRecovery && this.parser.errorCallback) { + var len = (ast.limChar - ast.minChar); + this.parser.errorCallback(ast.minChar, len, message, this.checker.locationInfo.unitIndex); + } else { + this.writePrefix(ast); + this.outfile.WriteLine(message); + } + }; + ErrorReporter.prototype.reportErrorFromSym = function (symbol, message) { + if(this.pushToErrorSink) { + this.captureError(message); + return; + } + this.hasErrors = true; + if(this.parser.errorRecovery && this.parser.errorCallback) { + this.parser.errorCallback(symbol.location, symbol.length, message, this.checker.locationInfo.unitIndex); + } else { + this.writePrefixFromSym(symbol); + this.outfile.WriteLine(message); + } + }; + ErrorReporter.prototype.emitterError = function (ast, message) { + this.reportError(ast, message); + throw Error("EmitError"); + }; + ErrorReporter.prototype.duplicateIdentifier = function (ast, name) { + this.reportError(ast, "Duplicate identifier '" + name + "'"); + }; + ErrorReporter.prototype.showRef = function (ast, text, symbol) { + var defLineCol = { + line: -1, + col: -1 + }; + this.parser.getSourceLineCol(defLineCol, symbol.location); + this.reportError(ast, "symbol " + text + " defined at (" + defLineCol.line + "," + defLineCol.col + ")"); + }; + ErrorReporter.prototype.unresolvedSymbol = function (ast, name) { + this.reportError(ast, "The name '" + name + "' does not exist in the current scope"); + }; + ErrorReporter.prototype.symbolDoesNotReferToAValue = function (ast, name) { + this.reportError(ast, "The name '" + name + "' does not refer to a value"); + }; + ErrorReporter.prototype.styleError = function (ast, msg) { + var bkThrow = this.pushToErrorSink; + this.pushToErrorSink = false; + this.reportError(ast, "STYLE: " + msg); + this.pushToErrorSink = bkThrow; + }; + ErrorReporter.prototype.simpleError = function (ast, msg) { + this.reportError(ast, msg); + }; + ErrorReporter.prototype.simpleErrorFromSym = function (sym, msg) { + this.reportErrorFromSym(sym, msg); + }; + ErrorReporter.prototype.invalidSuperReference = function (ast) { + this.simpleError(ast, "Keyword 'super' can only be used inside a class instance method"); + }; + ErrorReporter.prototype.valueCannotBeModified = function (ast) { + this.simpleError(ast, "The left-hand side of an assignment expression must be a variable, property or indexer"); + }; + ErrorReporter.prototype.invalidCall = function (ast, nodeType, scope) { + var targetType = ast.target.type; + var typeName = targetType.getScopedTypeName(scope); + if(targetType.construct && (nodeType == TypeScript.NodeType.Call)) { + this.reportError(ast, "Value of type '" + typeName + "' is not callable. Did you mean to include 'new'?"); + } else { + var catString = (nodeType == TypeScript.NodeType.Call) ? "callable" : "newable"; + this.reportError(ast, "Value of type '" + typeName + "' is not " + catString); + } + }; + ErrorReporter.prototype.indexLHS = function (ast, scope) { + var targetType = ast.operand1.type.getScopedTypeName(scope); + var indexType = ast.operand2.type.getScopedTypeName(scope); + this.simpleError(ast, "Value of type '" + targetType + "' is not indexable by type '" + indexType + "'"); + }; + ErrorReporter.prototype.incompatibleTypes = function (ast, t1, t2, op, scope, comparisonInfo) { + if(!t1) { + t1 = this.checker.anyType; + } + if(!t2) { + t2 = this.checker.anyType; + } + var reason = comparisonInfo ? comparisonInfo.message : ""; + if(op) { + this.reportError(ast, "Operator '" + op + "' cannot be applied to types '" + t1.getScopedTypeName(scope) + "' and '" + t2.getScopedTypeName(scope) + "'" + (reason ? ": " + reason : "")); + } else { + this.reportError(ast, "Cannot convert '" + t1.getScopedTypeName(scope) + "' to '" + t2.getScopedTypeName(scope) + "'" + (reason ? ": " + reason : "")); + } + }; + ErrorReporter.prototype.expectedClassOrInterface = function (ast) { + this.simpleError(ast, "Expected var, class, interface, or module"); + }; + ErrorReporter.prototype.unaryOperatorTypeError = function (ast, op, type) { + this.reportError(ast, "Operator '" + op + "' cannot be applied to type '" + type.getTypeName() + "'"); + }; + return ErrorReporter; + })(); + TypeScript.ErrorReporter = ErrorReporter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (TypeContext) { + TypeContext._map = []; + TypeContext.NoTypes = 0; + TypeContext.ArraySuffix = 1; + TypeContext.Primitive = 2; + TypeContext.Named = 4; + TypeContext.AllSimpleTypes = TypeContext.Primitive | TypeContext.Named; + TypeContext.AllTypes = TypeContext.Primitive | TypeContext.Named | TypeContext.ArraySuffix; + })(TypeScript.TypeContext || (TypeScript.TypeContext = {})); + var TypeContext = TypeScript.TypeContext; + var QuickParseResult = (function () { + function QuickParseResult(Script, endLexState) { + this.Script = Script; + this.endLexState = endLexState; + } + return QuickParseResult; + })(); + TypeScript.QuickParseResult = QuickParseResult; + var Parser = (function () { + function Parser() { + this.varLists = []; + this.scopeLists = []; + this.staticsLists = []; + this.scanner = new TypeScript.Scanner(); + this.currentToken = null; + this.needTerminator = false; + this.inFunction = false; + this.inInterfaceDecl = false; + this.currentClassDecl = null; + this.inFncDecl = false; + this.anonId = new TypeScript.Identifier("_anonymous"); + this.style_requireSemi = false; + this.style_funcInLoop = true; + this.incremental = false; + this.errorRecovery = false; + this.outfile = undefined; + this.errorCallback = null; + this.ambientModule = false; + this.ambientClass = false; + this.topLevel = true; + this.allowImportDeclaration = true; + this.currentUnitIndex = (-1); + this.prevIDTok = null; + this.statementInfoStack = new Array(); + this.hasTopLevelImportOrExport = false; + this.strictMode = false; + this.nestingLevel = 0; + this.prevExpr = null; + this.currentClassDefinition = null; + this.parsingClassConstructorDefinition = false; + this.parsingDeclareFile = false; + this.amdDependencies = []; + this.inferPropertiesFromThisAssignment = false; + this.requiresExtendsBlock = false; + this.fname = ""; + } + Parser.prototype.resetStmtStack = function () { + this.statementInfoStack = new Array(); + }; + Parser.prototype.inLoop = function () { + for(var j = this.statementInfoStack.length - 1; j >= 0; j--) { + if(this.statementInfoStack[j].stmt.isLoop()) { + return true; + } + } + return false; + }; + Parser.prototype.pushStmt = function (stmt, labels) { + var info = { + stmt: stmt, + labels: labels + }; + this.statementInfoStack.push(info); + }; + Parser.prototype.popStmt = function () { + return this.statementInfoStack.pop(); + }; + Parser.prototype.resolveJumpTarget = function (jump) { + var resolvedTarget = TypeScript.AST.getResolvedIdentifierName(jump.target); + var len = this.statementInfoStack.length; + for(var i = len - 1; i >= 0; i--) { + var info = this.statementInfoStack[i]; + if(jump.target) { + if(info.labels && (info.labels.members.length > 0)) { + for(var j = 0, labLen = info.labels.members.length; j < labLen; j++) { + var label = info.labels.members[j]; + if(label.id.text == resolvedTarget) { + jump.setResolvedTarget(this, info.stmt); + return; + } + } + } + } else { + if(info.stmt.isLoop()) { + jump.setResolvedTarget(this, info.stmt); + return; + } else if((info.stmt.nodeType == TypeScript.NodeType.Switch) && (jump.nodeType == TypeScript.NodeType.Break)) { + jump.setResolvedTarget(this, info.stmt); + return; + } + } + } + if(jump.target) { + this.reportParseError("could not find enclosing statement with label " + jump.target); + } else { + if(jump.nodeType == TypeScript.NodeType.Break) { + this.reportParseError("break statement requires enclosing loop or switch"); + } else { + this.reportParseError("continue statement requires enclosing loop"); + } + } + }; + Parser.prototype.setErrorRecovery = function (outfile) { + this.outfile = outfile; + this.errorRecovery = true; + }; + Parser.prototype.getSourceLineCol = function (lineCol, minChar) { + TypeScript.getSourceLineColFromMap(lineCol, minChar, this.scanner.lineMap); + }; + Parser.prototype.createRef = function (text, hasEscapeSequence, minChar) { + var id = new TypeScript.Identifier(text, hasEscapeSequence); + id.minChar = minChar; + return id; + }; + Parser.prototype.reportParseStyleError = function (message) { + this.reportParseError("STYLE: " + message); + }; + Parser.prototype.reportParseError = function (message, startPos, pos) { + if (typeof startPos === "undefined") { startPos = this.scanner.startPos; } + if (typeof pos === "undefined") { pos = this.scanner.pos; } + var len = Math.max(1, pos - startPos); + if(this.errorCallback) { + this.errorCallback(startPos, len, message, this.currentUnitIndex); + } else if(this.errorRecovery) { + var lineCol = { + line: -1, + col: -1 + }; + this.getSourceLineCol(lineCol, startPos); + if(this.outfile) { + this.outfile.WriteLine("// " + this.fname + " (" + lineCol.line + "," + lineCol.col + "): " + message); + } + } else { + throw new SyntaxError(this.fname + " (" + this.scanner.line + "," + this.scanner.col + "): " + message); + } + }; + Parser.prototype.checkNextToken = function (tokenId, errorRecoverySet, errorText) { + if (typeof errorText === "undefined") { errorText = null; } + this.currentToken = this.scanner.scan(); + this.checkCurrentToken(tokenId, errorRecoverySet, errorText); + }; + Parser.prototype.skip = function (errorRecoverySet) { + errorRecoverySet |= TypeScript.ErrorRecoverySet.EOF; + var ersTok = TypeScript.ErrorRecoverySet.None; + var tokenInfo = TypeScript.lookupToken(this.currentToken.tokenId); + if(tokenInfo != undefined) { + ersTok = tokenInfo.ers; + } + var pendingRightCurlies = 0; + while(((ersTok & errorRecoverySet) == TypeScript.ErrorRecoverySet.None) || (this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) && (pendingRightCurlies > 0)) { + if(this.currentToken.tokenId == TypeScript.TokenID.OpenBrace) { + pendingRightCurlies++; + } else if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { + pendingRightCurlies--; + } + this.currentToken = this.scanner.scan(); + ersTok = TypeScript.ErrorRecoverySet.None; + tokenInfo = TypeScript.lookupToken(this.currentToken.tokenId); + if(tokenInfo != undefined) { + ersTok = tokenInfo.ers; + } + } + }; + Parser.prototype.checkCurrentToken = function (tokenId, errorRecoverySet, errorText) { + if (typeof errorText === "undefined") { errorText = null; } + if(this.currentToken.tokenId != tokenId) { + errorText = errorText == null ? ("Expected '" + TypeScript.tokenTable[tokenId].text + "'") : errorText; + this.reportParseError(errorText); + if(this.errorRecovery) { + this.skip(errorRecoverySet); + } + } else { + this.currentToken = this.scanner.scan(); + } + }; + Parser.prototype.pushDeclLists = function () { + this.staticsLists.push(new TypeScript.ASTList()); + this.varLists.push(new TypeScript.ASTList()); + this.scopeLists.push(new TypeScript.ASTList()); + }; + Parser.prototype.popDeclLists = function () { + this.staticsLists.pop(); + this.varLists.pop(); + this.scopeLists.pop(); + }; + Parser.prototype.topVarList = function () { + return this.varLists[this.varLists.length - 1]; + }; + Parser.prototype.topScopeList = function () { + return this.scopeLists[this.scopeLists.length - 1]; + }; + Parser.prototype.topStaticsList = function () { + return this.staticsLists[this.staticsLists.length - 1]; + }; + Parser.prototype.parseComment = function (comment) { + if(comment) { + var c = new TypeScript.Comment(comment.value, comment.isBlock, comment.endsLine); + c.minChar = comment.startPos; + c.limChar = comment.startPos + comment.value.length; + var lineCol = { + line: -1, + col: -1 + }; + this.getSourceLineCol(lineCol, c.minChar); + c.minLine = lineCol.line; + this.getSourceLineCol(lineCol, c.limChar); + c.limLine = lineCol.line; + if(!comment.isBlock && comment.value.length > 3 && comment.value.substring(0, 3) == "///") { + var dependencyPath = TypeScript.getAdditionalDependencyPath(comment.value); + if(dependencyPath) { + this.amdDependencies.push(dependencyPath); + } + if(TypeScript.getImplicitImport(comment.value)) { + this.hasTopLevelImportOrExport = true; + } + } + return c; + } else { + return null; + } + }; + Parser.prototype.parseCommentsInner = function (comments) { + if(comments) { + var commentASTs = new Array(); + for(var i = 0; i < comments.length; i++) { + commentASTs.push(this.parseComment(comments[i])); + } + return commentASTs; + } else { + return null; + } + }; + Parser.prototype.parseComments = function () { + var comments = this.scanner.getComments(); + return this.parseCommentsInner(comments); + }; + Parser.prototype.parseCommentsForLine = function (line) { + var comments = this.scanner.getCommentsForLine(line); + return this.parseCommentsInner(comments); + }; + Parser.prototype.combineComments = function (comment1, comment2) { + if(comment1 == null) { + return comment2; + } else if(comment2 == null) { + return comment1; + } else { + return comment1.concat(comment2); + } + }; + Parser.prototype.parseEnumDecl = function (errorRecoverySet, modifiers) { + var leftCurlyCount = this.scanner.leftCurlyCount; + var rightCurlyCount = this.scanner.rightCurlyCount; + var name = null; + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + name = TypeScript.Identifier.fromToken(this.currentToken); + name.minChar = this.scanner.startPos; + name.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + } else { + this.reportParseError("Enum declaration requires identifier"); + if(this.errorRecovery) { + name = new TypeScript.MissingIdentifier(); + name.minChar = this.scanner.startPos; + name.limChar = this.scanner.startPos; + name.flags |= TypeScript.ASTFlags.Error; + } + } + var membersMinChar = this.scanner.startPos; + this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.ID); + this.pushDeclLists(); + var members = new TypeScript.ASTList(); + members.minChar = membersMinChar; + var mapDecl = new TypeScript.VarDecl(new TypeScript.Identifier("_map"), 0); + mapDecl.varFlags |= TypeScript.VarFlags.Exported; + mapDecl.varFlags |= TypeScript.VarFlags.Private; + mapDecl.varFlags |= (TypeScript.VarFlags.Property | TypeScript.VarFlags.Public); + mapDecl.init = new TypeScript.UnaryExpression(TypeScript.NodeType.ArrayLit, null); + members.append(mapDecl); + var lastValue = null; + var memberNames = []; + for(; ; ) { + var minChar = this.scanner.startPos; + var limChar; + var memberName = null; + var memberValue = null; + var preComments = null; + var postComments = null; + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToIDName(this.currentToken)) { + memberName = TypeScript.Identifier.fromToken(this.currentToken); + memberName.minChar = this.scanner.startPos; + memberName.limChar = this.scanner.pos; + memberNames.push(memberName); + } else if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { + break; + } else { + this.reportParseError("Expected identifer of enum member"); + if(this.errorRecovery) { + memberName = new TypeScript.MissingIdentifier(); + memberName.minChar = this.scanner.startPos; + memberName.limChar = this.scanner.startPos; + memberName.flags |= TypeScript.ASTFlags.Error; + } + } + limChar = this.scanner.pos; + preComments = this.parseComments(); + this.currentToken = this.scanner.scan(); + postComments = this.parseComments(); + if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { + this.currentToken = this.scanner.scan(); + memberValue = this.parseExpr(errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); + lastValue = memberValue; + limChar = memberValue.limChar; + } else { + if(lastValue == null) { + memberValue = new TypeScript.NumberLiteral(0, "0"); + lastValue = memberValue; + } else { + var nextValue = lastValue.value + 1; + memberValue = new TypeScript.NumberLiteral(nextValue, nextValue.toString()); + lastValue = memberValue; + } + var map = new TypeScript.BinaryExpression(TypeScript.NodeType.Asg, new TypeScript.BinaryExpression(TypeScript.NodeType.Index, new TypeScript.Identifier("_map"), memberValue), new TypeScript.StringLiteral('"' + memberName.actualText + '"')); + members.append(map); + } + var member = new TypeScript.VarDecl(memberName, this.nestingLevel); + member.minChar = minChar; + member.limChar = limChar; + member.init = memberValue; + member.typeExpr = new TypeScript.TypeReference(this.createRef(name.actualText, name.hasEscapeSequence, -1), 0); + member.varFlags |= (TypeScript.VarFlags.Readonly | TypeScript.VarFlags.Property); + if(memberValue.nodeType == TypeScript.NodeType.NumberLit) { + member.varFlags |= TypeScript.VarFlags.Constant; + } else if(memberValue.nodeType === TypeScript.NodeType.Lsh) { + var binop = memberValue; + if(binop.operand1.nodeType === TypeScript.NodeType.NumberLit && binop.operand2.nodeType === TypeScript.NodeType.NumberLit) { + member.varFlags |= TypeScript.VarFlags.Constant; + } + } else if(memberValue.nodeType === TypeScript.NodeType.Name) { + var nameNode = memberValue; + for(var i = 0; i < memberNames.length; i++) { + var memberName = memberNames[i]; + if(memberName.text === nameNode.text) { + member.varFlags |= TypeScript.VarFlags.Constant; + break; + } + } + } + member.preComments = preComments; + members.append(member); + member.postComments = postComments; + member.varFlags |= TypeScript.VarFlags.Exported; + if(this.currentToken.tokenId == TypeScript.TokenID.Comma) { + this.currentToken = this.scanner.scan(); + member.postComments = this.combineComments(member.postComments, this.parseCommentsForLine(this.scanner.prevLine)); + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || (TypeScript.convertTokToIDName(this.currentToken))) { + continue; + } + } + break; + } + var endingToken = new TypeScript.ASTSpan(); + endingToken.minChar = this.scanner.startPos; + endingToken.limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); + members.limChar = this.scanner.lastTokenLimChar(); + var modDecl = new TypeScript.ModuleDeclaration(name, members, this.topVarList(), endingToken); + modDecl.modFlags |= TypeScript.ModuleFlags.IsEnum; + this.popDeclLists(); + modDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; + modDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; + return modDecl; + }; + Parser.prototype.parseDottedName = function (enclosedList) { + this.currentToken = this.scanner.scan(); + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + var id = TypeScript.Identifier.fromToken(this.currentToken); + id.preComments = this.parseComments(); + enclosedList[enclosedList.length] = id; + id.minChar = this.scanner.startPos; + id.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.Dot) { + this.parseDottedName(enclosedList); + } + } else { + this.reportParseError("need identifier after '.'"); + } + }; + Parser.prototype.isValidImportPath = function (importPath) { + importPath = TypeScript.stripQuotes(importPath); + if(!importPath || importPath.indexOf(':') != -1 || importPath.indexOf('\\') != -1 || importPath.charAt(0) == '/') { + return false; + } + return true; + }; + Parser.prototype.parseImportDeclaration = function (errorRecoverySet, modifiers) { + var name = null; + var alias = null; + var importDecl = null; + var minChar = this.scanner.startPos; + var isDynamicImport = false; + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + name = TypeScript.Identifier.fromToken(this.currentToken); + } else { + this.reportParseError("Expected identifer after 'import'"); + name = new TypeScript.MissingIdentifier(); + } + name.minChar = this.scanner.startPos; + name.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + this.checkCurrentToken(TypeScript.TokenID.Equals, errorRecoverySet | TypeScript.ErrorRecoverySet.ID); + var aliasPreComments = this.parseComments(); + var limChar; + if(this.currentToken.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + if(this.currentToken.tokenId == TypeScript.TokenID.Module) { + limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.StringLiteral || this.currentToken.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + if(this.currentToken.tokenId == TypeScript.TokenID.StringLiteral) { + if(this.topLevel) { + this.hasTopLevelImportOrExport = true; + } else if(!this.allowImportDeclaration) { + this.reportParseError("Import declaration of external module is permitted only in global or top level dynamic modules"); + } + var aliasText = this.currentToken.getText(); + alias = TypeScript.Identifier.fromToken(this.currentToken); + alias.minChar = this.scanner.startPos; + alias.limChar = this.scanner.pos; + if(!this.isValidImportPath((alias).text)) { + this.reportParseError("Invalid import path"); + } + isDynamicImport = true; + this.currentToken = this.scanner.scan(); + alias.preComments = aliasPreComments; + } else { + alias = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.Assignment, true, TypeContext.NoTypes); + alias.preComments = aliasPreComments; + } + } + limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ID); + if(alias) { + alias.postComments = this.parseComments(); + } + } + } else { + alias = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.Assignment, true, TypeContext.NoTypes); + limChar = this.scanner.pos; + } + } else { + this.reportParseError("Expected module name"); + alias = new TypeScript.MissingIdentifier(); + alias.minChar = this.scanner.startPos; + if(this.currentToken.tokenId == TypeScript.TokenID.Semicolon) { + alias.limChar = this.scanner.startPos; + } else { + alias.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + } + alias.flags |= TypeScript.ASTFlags.Error; + limChar = alias.limChar; + } + importDecl = new TypeScript.ImportDeclaration(name, alias); + importDecl.isDynamicImport = isDynamicImport; + importDecl.minChar = minChar; + importDecl.limChar = limChar; + return importDecl; + }; + Parser.prototype.parseModuleDecl = function (errorRecoverySet, modifiers, preComments) { + var leftCurlyCount = this.scanner.leftCurlyCount; + var rightCurlyCount = this.scanner.rightCurlyCount; + var svAmbient = this.ambientModule; + var svTopLevel = this.topLevel; + this.topLevel = false; + if(this.parsingDeclareFile || svAmbient || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + this.ambientModule = true; + } + this.currentToken = this.scanner.scan(); + var name = null; + var enclosedList = null; + this.pushDeclLists(); + var minChar = this.scanner.startPos; + var isDynamicMod = false; + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || (this.currentToken.tokenId == TypeScript.TokenID.StringLiteral) || (!TypeScript.isPrimitiveTypeToken(this.currentToken) && TypeScript.convertTokToID(this.currentToken, this.strictMode))) { + var nameText = this.currentToken.getText(); + if(this.currentToken.tokenId == TypeScript.TokenID.StringLiteral) { + isDynamicMod = true; + if(!this.ambientModule) { + this.reportParseError("Only ambient dynamic modules may have string literal names"); + } + if(!svTopLevel) { + this.reportParseError("Dynamic modules may not be nested within other modules"); + } + } + name = TypeScript.Identifier.fromToken(this.currentToken); + name.minChar = this.scanner.startPos; + name.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + } else if(this.currentToken.tokenId == TypeScript.TokenID.OpenBrace) { + this.reportParseError("Module name missing"); + name = new TypeScript.Identifier(""); + name.minChar = minChar; + name.limChar = minChar; + } + if(this.currentToken.tokenId == TypeScript.TokenID.Dot) { + enclosedList = new Array(); + this.parseDottedName(enclosedList); + } + if(name == null) { + name = new TypeScript.MissingIdentifier(); + } + var moduleBody = new TypeScript.ASTList(); + var bodyMinChar = this.scanner.startPos; + this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.ID); + if(svTopLevel && isDynamicMod) { + this.allowImportDeclaration = true; + } else { + this.allowImportDeclaration = false; + } + this.parseStatementList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, moduleBody, true, true, TypeScript.AllowedElements.Global, modifiers); + moduleBody.minChar = bodyMinChar; + moduleBody.limChar = this.scanner.pos; + var endingToken = new TypeScript.ASTSpan(); + endingToken.minChar = this.scanner.startPos; + endingToken.limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); + var limChar = this.scanner.lastTokenLimChar(); + var moduleDecl; + this.allowImportDeclaration = svTopLevel; + if(enclosedList && (enclosedList.length > 0)) { + var len = enclosedList.length; + var innerName = enclosedList[len - 1]; + var innerDecl = new TypeScript.ModuleDeclaration(innerName, moduleBody, this.topVarList(), endingToken); + innerDecl.preComments = preComments; + if(this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + innerDecl.modFlags |= TypeScript.ModuleFlags.Ambient; + } + innerDecl.modFlags |= TypeScript.ModuleFlags.Exported; + innerDecl.minChar = minChar; + innerDecl.limChar = limChar; + this.popDeclLists(); + var outerModBod; + for(var i = len - 2; i >= 0; i--) { + outerModBod = new TypeScript.ASTList(); + outerModBod.append(innerDecl); + innerName = enclosedList[i]; + innerDecl = new TypeScript.ModuleDeclaration(innerName, outerModBod, new TypeScript.ASTList(), endingToken); + outerModBod.minChar = innerDecl.minChar = minChar; + outerModBod.limChar = innerDecl.limChar = limChar; + if(this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + innerDecl.modFlags |= TypeScript.ModuleFlags.Ambient; + } + innerDecl.modFlags |= TypeScript.ModuleFlags.Exported; + } + outerModBod = new TypeScript.ASTList(); + outerModBod.append(innerDecl); + outerModBod.minChar = minChar; + outerModBod.limChar = limChar; + moduleDecl = new TypeScript.ModuleDeclaration(name, outerModBod, new TypeScript.ASTList(), endingToken); + } else { + moduleDecl = new TypeScript.ModuleDeclaration(name, moduleBody, this.topVarList(), endingToken); + moduleDecl.preComments = preComments; + this.popDeclLists(); + } + if(this.parsingDeclareFile || svAmbient || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + moduleDecl.modFlags |= TypeScript.ModuleFlags.Ambient; + } + if(svAmbient || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { + moduleDecl.modFlags |= TypeScript.ModuleFlags.Exported; + } + if(isDynamicMod) { + moduleDecl.modFlags |= TypeScript.ModuleFlags.IsDynamic; + } + this.ambientModule = svAmbient; + this.topLevel = svTopLevel; + moduleDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; + moduleDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; + moduleDecl.limChar = moduleBody.limChar; + return moduleDecl; + }; + Parser.prototype.parseTypeReferenceTail = function (errorRecoverySet, minChar, term) { + var result = new TypeScript.TypeReference(term, 0); + result.minChar = minChar; + while(this.currentToken.tokenId == TypeScript.TokenID.OpenBracket) { + this.currentToken = this.scanner.scan(); + result.arrayCount++; + this.checkCurrentToken(TypeScript.TokenID.CloseBracket, errorRecoverySet | TypeScript.ErrorRecoverySet.LBrack); + } + result.limChar = this.scanner.lastTokenLimChar(); + return result; + }; + Parser.prototype.parseNamedType = function (errorRecoverySet, minChar, term, tail) { + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.Dot) { + var curpos = this.scanner.pos; + this.currentToken = this.scanner.scan(); + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || ((!this.errorRecovery || !this.scanner.lastTokenHadNewline()) && TypeScript.convertTokToID(this.currentToken, this.strictMode))) { + var op2 = TypeScript.Identifier.fromToken(this.currentToken); + op2.minChar = this.scanner.startPos; + op2.limChar = this.scanner.pos; + var dotNode = new TypeScript.BinaryExpression(TypeScript.NodeType.Dot, term, op2); + dotNode.minChar = term.minChar; + dotNode.limChar = op2.limChar; + return this.parseNamedType(errorRecoverySet, minChar, dotNode, tail); + } else { + this.reportParseError("need identifier after '.'"); + if(this.errorRecovery) { + term.flags |= TypeScript.ASTFlags.DotLHS; + term.limChar = this.scanner.lastTokenLimChar(); + return term; + } else { + var eop2 = new TypeScript.MissingIdentifier(); + eop2.minChar = this.scanner.pos; + eop2.limChar = this.scanner.pos; + var edotNode = new TypeScript.BinaryExpression(TypeScript.NodeType.Dot, term, eop2); + edotNode.flags |= TypeScript.ASTFlags.Error; + edotNode.minChar = term.minChar; + edotNode.limChar = eop2.limChar; + return this.parseNamedType(errorRecoverySet, minChar, edotNode, tail); + } + } + } else { + if(tail) { + return this.parseTypeReferenceTail(errorRecoverySet, minChar, term); + } else { + return term; + } + } + }; + Parser.prototype.parseTypeReference = function (errorRecoverySet, allowVoid) { + var minChar = this.scanner.startPos; + var isConstructorMember = false; + switch(this.currentToken.tokenId) { + case TypeScript.TokenID.Void: + if(!allowVoid) { + this.reportParseError("void not a valid type in this context"); + } + case TypeScript.TokenID.Any: + case TypeScript.TokenID.Number: + case TypeScript.TokenID.Bool: + case TypeScript.TokenID.String: { + var text = TypeScript.tokenTable[this.currentToken.tokenId].text; + var predefinedIdentifier = new TypeScript.Identifier(text); + predefinedIdentifier.minChar = minChar; + predefinedIdentifier.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + return this.parseTypeReferenceTail(errorRecoverySet, minChar, predefinedIdentifier); + } + case TypeScript.TokenID.Identifier: + var ident = this.createRef(this.currentToken.getText(), (this.currentToken).hasEscapeSequence, minChar); + ident.limChar = this.scanner.pos; + return this.parseNamedType(errorRecoverySet, minChar, ident, true); + case TypeScript.TokenID.OpenBrace: + return this.parseObjectType(minChar, errorRecoverySet); + case TypeScript.TokenID.New: + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId != TypeScript.TokenID.OpenParen) { + this.reportParseError("Expected '('"); + } else { + isConstructorMember = true; + } + case TypeScript.TokenID.OpenParen: { + var formals = new TypeScript.ASTList(); + var variableArgList = this.parseFormalParameterList(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, formals, false, true, false, false, false, false, null, true); + this.checkCurrentToken(TypeScript.TokenID.EqualsGreaterThan, errorRecoverySet); + var returnType = this.parseTypeReference(errorRecoverySet, true); + var funcDecl = new TypeScript.FuncDecl(null, null, false, formals, null, null, null, TypeScript.NodeType.FuncDecl); + funcDecl.returnTypeAnnotation = returnType; + funcDecl.variableArgList = variableArgList; + funcDecl.fncFlags |= TypeScript.FncFlags.Signature; + if(isConstructorMember) { + funcDecl.fncFlags |= TypeScript.FncFlags.ConstructMember; + funcDecl.hint = "_construct"; + funcDecl.classDecl = null; + } + funcDecl.minChar = minChar; + return this.parseTypeReferenceTail(errorRecoverySet, minChar, funcDecl); + } + default: + this.reportParseError("Expected type name"); + var etr = new TypeScript.TypeReference(null, 0); + etr.flags |= TypeScript.ASTFlags.Error; + etr.minChar = this.scanner.pos; + etr.limChar = this.scanner.pos; + return etr; + } + }; + Parser.prototype.parseObjectType = function (minChar, errorRecoverySet) { + this.currentToken = this.scanner.scan(); + var members = new TypeScript.ASTList(); + members.minChar = minChar; + var prevInInterfaceDecl = this.inInterfaceDecl; + this.inInterfaceDecl = true; + this.parseTypeMemberList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, members); + this.inInterfaceDecl = prevInInterfaceDecl; + this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); + var interfaceDecl = new TypeScript.InterfaceDeclaration(this.anonId, members, null, null); + interfaceDecl.minChar = minChar; + interfaceDecl.limChar = members.limChar; + return this.parseTypeReferenceTail(errorRecoverySet, minChar, interfaceDecl); + }; + Parser.prototype.parseFunctionBlock = function (errorRecoverySet, allowedElements, parentModifiers, bod, bodMinChar) { + this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); + var savedInFunction = this.inFunction; + this.inFunction = true; + this.parseStatementList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly | TypeScript.ErrorRecoverySet.StmtStart, bod, true, false, allowedElements, parentModifiers); + bod.minChar = bodMinChar; + bod.limChar = this.scanner.pos; + this.inFunction = savedInFunction; + if(bod.limChar > bod.minChar) { + var ec = new TypeScript.EndCode(); + ec.minChar = bod.limChar; + ec.limChar = ec.minChar; + bod.append(ec); + } + }; + Parser.prototype.parseFunctionStatements = function (errorRecoverySet, name, isConstructor, isMethod, args, allowedElements, minChar, requiresSignature, parentModifiers) { + this.pushDeclLists(); + var svStmtStack = this.statementInfoStack; + this.resetStmtStack(); + var bod = null; + var wasShorthand = false; + var isAnonLambda = false; + var limChar; + if(requiresSignature) { + limChar = this.scanner.pos; + if(this.currentToken.tokenId === TypeScript.TokenID.OpenBrace) { + this.reportParseError("Function declarations are not permitted within interfaces, ambient modules or classes"); + bod = new TypeScript.ASTList(); + var bodMinChar = this.scanner.startPos; + this.parseFunctionBlock(errorRecoverySet, allowedElements, parentModifiers, bod, bodMinChar); + this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); + if(this.currentToken.tokenId === TypeScript.TokenID.Semicolon) { + this.currentToken = this.scanner.scan(); + } + } else { + this.checkCurrentToken(TypeScript.TokenID.Semicolon, errorRecoverySet, "Expected ';'"); + } + } else { + bod = new TypeScript.ASTList(); + var bodMinChar = this.scanner.startPos; + if(this.currentToken.tokenId == TypeScript.TokenID.EqualsGreaterThan) { + if(isMethod) { + this.reportParseError("'=>' may not be used for class methods"); + } + wasShorthand = true; + this.currentToken = this.scanner.scan(); + } + if(wasShorthand && this.currentToken.tokenId != TypeScript.TokenID.OpenBrace) { + var retExpr = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.Assignment, true, TypeContext.NoTypes); + var retStmt = new TypeScript.ReturnStatement(); + retStmt.returnExpression = retExpr; + retStmt.minChar = retExpr.minChar; + retStmt.limChar = retExpr.limChar; + bod.minChar = bodMinChar; + bod.limChar = retExpr.limChar; + bod.append(retStmt); + } else if(this.currentToken.tokenId != TypeScript.TokenID.EndOfFile) { + isAnonLambda = wasShorthand; + this.parseFunctionBlock(errorRecoverySet, allowedElements, parentModifiers, bod, bodMinChar); + } + limChar = this.scanner.pos; + } + var funcDecl = new TypeScript.FuncDecl(name, bod, isConstructor, args, this.topVarList(), this.topScopeList(), this.topStaticsList(), TypeScript.NodeType.FuncDecl); + this.popDeclLists(); + var scopeList = this.topScopeList(); + scopeList.append(funcDecl); + var staticFuncDecl = false; + if(!requiresSignature) { + if(!wasShorthand || isAnonLambda) { + funcDecl.endingToken = new TypeScript.ASTSpan(); + funcDecl.endingToken.minChar = this.scanner.startPos; + funcDecl.endingToken.limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); + if(isAnonLambda) { + funcDecl.fncFlags |= TypeScript.FncFlags.IsFatArrowFunction; + } + } else { + funcDecl.fncFlags |= TypeScript.FncFlags.IsFatArrowFunction; + funcDecl.endingToken = new TypeScript.ASTSpan(); + funcDecl.endingToken.minChar = bod.members[0].minChar; + funcDecl.endingToken.limChar = bod.members[0].limChar; + } + } + funcDecl.minChar = minChar; + funcDecl.limChar = limChar; + if(requiresSignature) { + funcDecl.fncFlags |= TypeScript.FncFlags.Signature; + } + this.statementInfoStack = svStmtStack; + return funcDecl; + }; + Parser.prototype.transformAnonymousArgsIntoFormals = function (formals, argList) { + var _this = this; + var translateBinExOperand = function (operand) { + if(operand.nodeType == TypeScript.NodeType.Comma) { + return _this.transformAnonymousArgsIntoFormals(formals, operand); + } else if(operand.nodeType == TypeScript.NodeType.Name || operand.nodeType == TypeScript.NodeType.Asg) { + var opArg = operand.nodeType == TypeScript.NodeType.Asg ? (operand).operand1 : operand; + opArg.isParenthesized = false; + var arg = new TypeScript.ArgDecl(opArg); + arg.preComments = opArg.preComments; + arg.postComments = opArg.postComments; + arg.minChar = operand.minChar; + arg.limChar = operand.limChar; + if(TypeScript.hasFlag(opArg.flags, TypeScript.ASTFlags.PossibleOptionalParameter)) { + arg.isOptional = true; + } + if(operand.nodeType == TypeScript.NodeType.Asg) { + arg.init = (operand).operand2; + } + formals.append(arg); + return arg.isOptional || arg.init; + } else { + _this.reportParseError("Invalid lambda argument"); + } + return false; + }; + if(argList) { + if(argList.nodeType == TypeScript.NodeType.Comma) { + var commaList = argList; + if(commaList.operand1.isParenthesized) { + this.reportParseError("Invalid lambda argument", commaList.operand1.minChar, commaList.operand1.limChar); + } + if(commaList.operand2.isParenthesized) { + this.reportParseError("Invalid lambda argument", commaList.operand2.minChar, commaList.operand2.limChar); + } + var isOptional = translateBinExOperand(commaList.operand1); + isOptional = translateBinExOperand(commaList.operand2) || isOptional; + return isOptional; + } else { + return translateBinExOperand(argList); + } + } + }; + Parser.prototype.parseFormalParameterList = function (errorRecoverySet, formals, isClassConstr, isSig, isIndexer, isGetter, isSetter, isLambda, preProcessedLambdaArgs, expectClosingRParen) { + formals.minChar = this.scanner.startPos; + if(isIndexer) { + this.currentToken = this.scanner.scan(); + } else if(!isLambda) { + this.checkCurrentToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.RParen); + } + var sawEllipsis = false; + var firstArg = true; + var hasOptional = false; + var haveFirstArgID = false; + if(isLambda && preProcessedLambdaArgs && preProcessedLambdaArgs.nodeType != TypeScript.NodeType.EmptyExpr) { + hasOptional = this.transformAnonymousArgsIntoFormals(formals, preProcessedLambdaArgs); + formals.minChar = preProcessedLambdaArgs.minChar; + haveFirstArgID = true; + } + while(true) { + var munchedArg = false; + var argFlags = TypeScript.VarFlags.None; + var argMinChar = this.scanner.startPos; + if(this.inferPropertiesFromThisAssignment && this.currentToken.tokenId == TypeScript.TokenID.This) { + if(!isClassConstr) { + this.reportParseError("Instance property declarations using 'this' may only be used in class constructors"); + } + this.currentToken = this.scanner.scan(); + argFlags |= (TypeScript.VarFlags.Public | TypeScript.VarFlags.Property); + if(this.currentClassDefinition) { + this.currentClassDefinition.varFlags |= TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor; + } + } + if(this.currentToken.tokenId == TypeScript.TokenID.Public) { + argFlags |= (TypeScript.VarFlags.Public | TypeScript.VarFlags.Property); + if(this.currentClassDefinition) { + this.currentClassDefinition.varFlags |= TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor; + } + } else if(this.currentToken.tokenId == TypeScript.TokenID.Private) { + argFlags |= (TypeScript.VarFlags.Private | TypeScript.VarFlags.Property); + if(this.currentClassDefinition) { + this.currentClassDefinition.varFlags |= TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor; + } + } else if(this.currentToken.tokenId == TypeScript.TokenID.Static && isClassConstr) { + this.reportParseError("Static properties can not be declared as parameter properties"); + this.currentToken = this.scanner.scan(); + } + if(argFlags != TypeScript.VarFlags.None) { + if(!isClassConstr) { + this.reportParseError("only constructor parameters can be properties"); + } + this.currentToken = this.scanner.scan(); + if(TypeScript.isModifier(this.currentToken)) { + this.reportParseError("Multiple modifiers may not be applied to parameters"); + this.currentToken = this.scanner.scan(); + } + if(this.inferPropertiesFromThisAssignment && this.currentToken.tokenId == TypeScript.TokenID.This) { + if(!isClassConstr) { + this.reportParseError("Instance property declarations using 'this' may only be used in class constructors"); + } + this.currentToken = this.scanner.scan(); + this.currentToken = this.scanner.scan(); + } + } else if(this.currentToken.tokenId == TypeScript.TokenID.DotDotDot) { + sawEllipsis = true; + this.currentToken = this.scanner.scan(); + if(!(this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + this.reportParseError("'...' parameters require both a parameter name and an array type annotation to be specified"); + sawEllipsis = false; + } + } + var argId = null; + if(!haveFirstArgID && (this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + argId = TypeScript.Identifier.fromToken(this.currentToken); + argId.minChar = this.scanner.startPos; + argId.limChar = this.scanner.pos; + } + if(haveFirstArgID || argId) { + munchedArg = true; + var type = null; + var arg = null; + if(haveFirstArgID && formals.members.length) { + arg = formals.members[formals.members.length - 1]; + if(arg.isOptional) { + hasOptional = true; + } + } else { + arg = new TypeScript.ArgDecl(argId); + if(isGetter) { + this.reportParseError("Property getters may not take any arguments"); + } + if(isSetter && !firstArg) { + this.reportParseError("Property setters may only take one argument"); + } + arg.minChar = argMinChar; + arg.preComments = this.parseComments(); + this.currentToken = this.scanner.scan(); + } + if(this.currentToken.tokenId == TypeScript.TokenID.Question) { + arg.isOptional = true; + hasOptional = true; + this.currentToken = this.scanner.scan(); + } + if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { + this.currentToken = this.scanner.scan(); + type = this.parseTypeReference(errorRecoverySet, false); + } + if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { + if(isSig) { + this.reportParseError("Arguments in signatures may not have default values"); + } + hasOptional = true; + this.currentToken = this.scanner.scan(); + arg.init = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, false, TypeContext.NoTypes); + } + if(hasOptional && !arg.isOptionalArg() && !sawEllipsis) { + this.reportParseError("Optional parameters may only be followed by other optional parameters"); + } + if(sawEllipsis && arg.isOptionalArg()) { + this.reportParseError("Varargs may not be optional or have default parameters"); + } + if(sawEllipsis && !type) { + this.reportParseError("'...' parameters require both a parameter name and an array type annotation to be specified"); + } + arg.postComments = this.parseComments(); + arg.typeExpr = type; + arg.limChar = this.scanner.lastTokenLimChar(); + arg.varFlags |= argFlags; + if(!haveFirstArgID) { + formals.append(arg); + } else { + haveFirstArgID = false; + } + } + firstArg = false; + if(this.currentToken.tokenId == TypeScript.TokenID.Comma) { + if((munchedArg) && (!sawEllipsis)) { + this.currentToken = this.scanner.scan(); + continue; + } else { + this.reportParseError("Unexpected ',' in argument list"); + if(this.errorRecovery) { + this.currentToken = this.scanner.scan(); + continue; + } + } + } else { + break; + } + } + if(isIndexer) { + this.checkCurrentToken(TypeScript.TokenID.CloseBracket, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly | TypeScript.ErrorRecoverySet.SColon); + } else if(expectClosingRParen) { + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly | TypeScript.ErrorRecoverySet.SColon); + } + formals.limChar = this.currentToken.tokenId == TypeScript.TokenID.EndOfFile ? this.scanner.pos : this.scanner.lastTokenLimChar(); + return sawEllipsis; + }; + Parser.prototype.parseFncDecl = function (errorRecoverySet, isDecl, requiresSignature, isMethod, methodName, indexer, isStatic, markedAsAmbient, modifiers, lambdaArgContext, expectClosingRParen) { + var leftCurlyCount = this.scanner.leftCurlyCount; + var rightCurlyCount = this.scanner.rightCurlyCount; + var prevInConstr = this.parsingClassConstructorDefinition; + this.parsingClassConstructorDefinition = false; + var name = null; + var fnMin = this.scanner.startPos; + var minChar = this.scanner.pos; + var prevNestingLevel = this.nestingLevel; + var preComments = this.parseComments(); + var isLambda = !!lambdaArgContext; + this.nestingLevel = 0; + if((!this.style_funcInLoop) && this.inLoop()) { + this.reportParseStyleError("function declaration in loop"); + } + if(!isMethod && !isStatic && !indexer && !lambdaArgContext && !methodName) { + this.currentToken = this.scanner.scan(); + if((this.currentToken.tokenId != TypeScript.TokenID.Identifier) && (!TypeScript.convertTokToID(this.currentToken, this.strictMode))) { + if(isDecl) { + this.reportParseError("Function declaration must include identifier"); + this.nestingLevel = prevNestingLevel; + return new TypeScript.IncompleteAST(fnMin, this.scanner.pos); + } + } else { + name = TypeScript.Identifier.fromToken(this.currentToken); + name.minChar = this.scanner.startPos; + name.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + } + } else { + if(methodName) { + name = methodName; + } + } + var args = new TypeScript.ASTList(); + var variableArgList = false; + var isOverload = false; + var isGetter = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter); + var isSetter = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Setter); + if((this.currentToken.tokenId == TypeScript.TokenID.OpenParen) || (indexer && (this.currentToken.tokenId == TypeScript.TokenID.OpenBracket)) || (lambdaArgContext && (lambdaArgContext.preProcessedLambdaArgs || this.currentToken.tokenId == TypeScript.TokenID.DotDotDot))) { + variableArgList = this.parseFormalParameterList(errorRecoverySet, args, false, requiresSignature, indexer, isGetter, isSetter, isLambda, lambdaArgContext ? lambdaArgContext.preProcessedLambdaArgs : null, expectClosingRParen); + } + var returnType = null; + if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { + this.currentToken = this.scanner.scan(); + if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Setter)) { + this.reportParseError("Property setters may not declare a return type"); + } + returnType = this.parseTypeReference(errorRecoverySet, true); + } + if(indexer && args.members.length == 0) { + this.reportParseError("Index signatures require a parameter type to be specified"); + } + if(isLambda && this.currentToken.tokenId != TypeScript.TokenID.EqualsGreaterThan) { + this.reportParseError("Expected '=>'"); + } + if(isDecl && !(this.parsingDeclareFile || markedAsAmbient) && !this.ambientModule && !this.ambientClass && !this.inInterfaceDecl && this.currentToken.tokenId == TypeScript.TokenID.Semicolon) { + isOverload = true; + isDecl = false; + requiresSignature = true; + } + var svInFncDecl = this.inFncDecl; + this.inFncDecl = true; + var funcDecl = this.parseFunctionStatements(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, name, false, isMethod, args, TypeScript.AllowedElements.None, minChar, requiresSignature, TypeScript.Modifiers.None); + this.inFncDecl = svInFncDecl; + funcDecl.variableArgList = variableArgList; + funcDecl.isOverload = isOverload; + if(isStatic) { + funcDecl.fncFlags |= TypeScript.FncFlags.Static; + } + if(requiresSignature) { + funcDecl.fncFlags |= TypeScript.FncFlags.Signature; + } + if(indexer) { + funcDecl.fncFlags |= TypeScript.FncFlags.IndexerMember; + } + funcDecl.returnTypeAnnotation = returnType; + if(isMethod) { + funcDecl.fncFlags |= TypeScript.FncFlags.Method; + funcDecl.fncFlags |= TypeScript.FncFlags.ClassPropertyMethodExported; + } + funcDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; + funcDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; + this.nestingLevel = prevNestingLevel; + this.parsingClassConstructorDefinition = prevInConstr; + funcDecl.preComments = preComments; + return funcDecl; + }; + Parser.prototype.convertToTypeReference = function (ast) { + var result; + switch(ast.nodeType) { + case TypeScript.NodeType.TypeRef: + return ast; + case TypeScript.NodeType.Name: + result = new TypeScript.TypeReference(ast, 0); + result.minChar = ast.minChar; + result.limChar = ast.limChar; + return result; + case TypeScript.NodeType.Index: { + var expr = ast; + result = this.convertToTypeReference(expr.operand1); + if(result) { + result.arrayCount++; + result.minChar = expr.minChar; + result.limChar = expr.limChar; + return result; + } else { + var etr = new TypeScript.AST(TypeScript.NodeType.Error); + return etr; + } + } + } + return null; + }; + Parser.prototype.parseArgList = function (errorRecoverySet) { + var args = new TypeScript.ASTList(); + args.minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId !== TypeScript.TokenID.CloseParen) { + while(true) { + if(args.members.length > 0xffff) { + this.reportParseError("max number of args exceeded"); + break; + } + var arg = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); + args.append(arg); + if(this.currentToken.tokenId != TypeScript.TokenID.Comma) { + break; + } + this.currentToken = this.scanner.scan(); + } + } + args.limChar = this.scanner.pos; + return args; + }; + Parser.prototype.parseBaseList = function (extendsList, implementsList, errorRecoverySet, isClass) { + var keyword = true; + var currentList = extendsList; + for(; ; ) { + if(keyword) { + if(this.currentToken.tokenId === TypeScript.TokenID.Implements) { + currentList = implementsList; + } else if(this.currentToken.tokenId == TypeScript.TokenID.Extends && !this.requiresExtendsBlock) { + this.requiresExtendsBlock = isClass; + } + this.currentToken = this.scanner.scan(); + keyword = false; + } + var baseName = null; + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + var minChar = this.scanner.startPos; + baseName = TypeScript.Identifier.fromToken(this.currentToken); + baseName.minChar = minChar; + baseName.limChar = this.scanner.pos; + baseName = this.parseNamedType(errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly, minChar, baseName, false); + } else { + this.reportParseError("Expected base name"); + if(this.errorRecovery) { + baseName = new TypeScript.MissingIdentifier(); + baseName.minChar = this.scanner.pos; + baseName.limChar = this.scanner.pos; + baseName.flags |= TypeScript.ASTFlags.Error; + } + } + if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { + if(isClass) { + this.reportParseError("Base classes may only be initialized via a 'super' call within the constructor body"); + } else { + this.reportParseError("Interfaces may not be extended with a call expression"); + } + } else { + currentList.append(baseName); + } + if(isClass && currentList == extendsList && extendsList.members.length > 1) { + this.reportParseError("A class may only extend one other class"); + } + if(this.currentToken.tokenId == TypeScript.TokenID.Comma) { + this.currentToken = this.scanner.scan(); + continue; + } else if((this.currentToken.tokenId == TypeScript.TokenID.Extends) || (this.currentToken.tokenId == TypeScript.TokenID.Implements)) { + if(this.currentToken.tokenId == TypeScript.TokenID.Extends && !this.requiresExtendsBlock) { + this.requiresExtendsBlock = isClass; + } + currentList = extendsList; + keyword = true; + continue; + } + break; + } + }; + Parser.prototype.parseClassDecl = function (errorRecoverySet, minChar, modifiers) { + var leftCurlyCount = this.scanner.leftCurlyCount; + var rightCurlyCount = this.scanner.rightCurlyCount; + if((modifiers & TypeScript.Modifiers.Readonly) != TypeScript.Modifiers.None) { + this.reportParseError("const modifier is implicit for class"); + } + if(this.parsingDeclareFile || this.ambientModule) { + modifiers |= TypeScript.Modifiers.Ambient; + modifiers |= TypeScript.Modifiers.Exported; + } + var classIsMarkedAsAmbient = this.parsingDeclareFile || (modifiers & TypeScript.Modifiers.Ambient) != TypeScript.Modifiers.None; + var svAmbientClass = this.ambientClass; + this.ambientClass = classIsMarkedAsAmbient; + this.currentToken = this.scanner.scan(); + var name = null; + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || (!TypeScript.isPrimitiveTypeToken(this.currentToken) && TypeScript.convertTokToID(this.currentToken, this.strictMode))) { + name = TypeScript.Identifier.fromToken(this.currentToken); + name.minChar = this.scanner.startPos; + name.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + } else { + this.reportParseError("class missing name"); + if(this.errorRecovery) { + name = new TypeScript.MissingIdentifier(); + name.minChar = this.scanner.pos; + name.limChar = this.scanner.pos; + name.flags |= TypeScript.ASTFlags.Error; + } + } + var extendsList = null; + var implementsList = null; + var requiresSignature = false; + if((this.currentToken.tokenId == TypeScript.TokenID.Extends) || (this.currentToken.tokenId == TypeScript.TokenID.Implements)) { + extendsList = new TypeScript.ASTList(); + implementsList = new TypeScript.ASTList(); + this.parseBaseList(extendsList, implementsList, errorRecoverySet, true); + } + var classDecl = new TypeScript.ClassDeclaration(name, new TypeScript.ASTList(), extendsList, implementsList); + this.currentClassDefinition = classDecl; + this.parseClassElements(classDecl, errorRecoverySet, modifiers); + if(this.ambientModule || this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { + classDecl.varFlags |= TypeScript.VarFlags.Exported; + } + if(this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + classDecl.varFlags |= TypeScript.VarFlags.Ambient; + } + classDecl.varFlags |= TypeScript.VarFlags.Class; + this.ambientClass = svAmbientClass; + classDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; + classDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; + return classDecl; + }; + Parser.prototype.parseClassElements = function (classDecl, errorRecoverySet, parentModifiers) { + var modifiers = parentModifiers; + var resetModifiers = false; + var membersMinChar = this.scanner.startPos; + this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet); + this.nestingLevel++; + var currentMemberMinChar = this.scanner.startPos; + var wasGetOrSetId = false; + while(!(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace || this.currentToken.tokenId == TypeScript.TokenID.EndOfFile)) { + var scanNext = true; + var publicOrPrivateFlags = TypeScript.Modifiers.Public | TypeScript.Modifiers.Private; + if(this.currentToken.tokenId == TypeScript.TokenID.Get) { + if(modifiers & TypeScript.Modifiers.Getter) { + this.reportParseError("Duplicate 'get' declaration in class body"); + } + if(modifiers & TypeScript.Modifiers.Setter) { + this.reportParseError("Getter already marked as a setter"); + } + modifiers |= TypeScript.Modifiers.Getter; + } else if(this.currentToken.tokenId == TypeScript.TokenID.Set) { + if(modifiers & TypeScript.Modifiers.Setter) { + this.reportParseError("Duplicate 'set' declaration in class body"); + } + if(modifiers & TypeScript.Modifiers.Getter) { + this.reportParseError("Setter already marked as a getter"); + } + modifiers |= TypeScript.Modifiers.Setter; + } else if(this.currentToken.tokenId == TypeScript.TokenID.Private) { + if(modifiers & publicOrPrivateFlags) { + this.reportParseError("Multiple modifiers may not be applied to class members"); + } + modifiers |= TypeScript.Modifiers.Private; + } else if(this.currentToken.tokenId == TypeScript.TokenID.Public) { + if(modifiers & publicOrPrivateFlags) { + this.reportParseError("Multiple modifiers may not be applied to class members"); + } + modifiers |= TypeScript.Modifiers.Public; + } else if(this.currentToken.tokenId == TypeScript.TokenID.Static) { + if(modifiers & TypeScript.Modifiers.Static) { + this.reportParseError("Multiple modifiers may not be applied to class members"); + } + modifiers |= TypeScript.Modifiers.Static; + } else if(this.currentToken.tokenId == TypeScript.TokenID.Constructor) { + if(modifiers != parentModifiers) { + this.reportParseError("Constructors may not have modifiers"); + } + this.parseClassConstructorDeclaration(currentMemberMinChar, errorRecoverySet, modifiers); + scanNext = false; + resetModifiers = true; + } else if(wasGetOrSetId || this.currentToken.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToIDName(this.currentToken)) { + var idText = wasGetOrSetId ? ((modifiers & TypeScript.Modifiers.Getter) ? "get" : "set") : this.currentToken.getText(); + var id = wasGetOrSetId ? new TypeScript.Identifier(idText) : TypeScript.Identifier.fromToken(this.currentToken); + id.minChar = this.scanner.startPos; + id.limChar = this.scanner.pos; + if(wasGetOrSetId) { + modifiers = modifiers ^ ((modifiers & TypeScript.Modifiers.Getter) ? TypeScript.Modifiers.Getter : TypeScript.Modifiers.Setter); + wasGetOrSetId = false; + } else { + this.currentToken = this.scanner.scan(); + } + if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { + this.parseClassMemberFunctionDeclaration(id, currentMemberMinChar, errorRecoverySet, modifiers); + scanNext = false; + } else { + if(modifiers & TypeScript.Modifiers.Getter || modifiers & TypeScript.Modifiers.Setter) { + this.reportParseError("Property accessors must be functions"); + } + var varDecl = this.parseClassMemberVariableDeclaration(id, currentMemberMinChar, false, errorRecoverySet, modifiers); + if(varDecl.init && varDecl.init.nodeType == TypeScript.NodeType.FuncDecl) { + if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { + scanNext = false; + } + } else if(varDecl.init && varDecl.init.nodeType == TypeScript.NodeType.ObjectLit && this.currentToken.tokenId != TypeScript.TokenID.Semicolon) { + scanNext = false; + varDecl.init.flags |= TypeScript.ASTFlags.AutomaticSemicolon; + } else if(this.currentToken.tokenId != TypeScript.TokenID.Semicolon) { + this.reportParseError("Expected ';'"); + scanNext = false; + } + } + resetModifiers = true; + } else if(this.currentToken.tokenId == TypeScript.TokenID.Super) { + this.reportParseError("Base class initializers must be the first statement in a class definition"); + } else if(!wasGetOrSetId && ((modifiers & TypeScript.Modifiers.Getter) || (modifiers & TypeScript.Modifiers.Setter)) && ((this.currentToken.tokenId == TypeScript.TokenID.OpenParen) || (this.currentToken.tokenId == TypeScript.TokenID.Equals) || (this.currentToken.tokenId == TypeScript.TokenID.Colon) || (this.currentToken.tokenId == TypeScript.TokenID.Semicolon))) { + wasGetOrSetId = true; + scanNext = false; + } else if(this.currentToken.tokenId != TypeScript.TokenID.Semicolon) { + this.reportParseError("Unexpected '" + this.currentToken.getText() + "' in class definition"); + resetModifiers = true; + } + if(scanNext) { + this.currentToken = this.scanner.scan(); + } + if(resetModifiers) { + modifiers = parentModifiers; + currentMemberMinChar = this.scanner.startPos; + resetModifiers = false; + } + } + var membersLimChar = this.scanner.pos; + if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { + classDecl.endingToken = new TypeScript.ASTSpan(); + classDecl.endingToken.minChar = this.scanner.startPos; + classDecl.endingToken.limChar = this.scanner.pos; + if(!this.currentClassDefinition.members.members.length) { + this.currentClassDefinition.preComments = this.parseComments(); + } + this.currentToken = this.scanner.scan(); + } + this.nestingLevel--; + this.currentClassDefinition.members.minChar = membersMinChar; + this.currentClassDefinition.members.limChar = membersLimChar; + this.currentClassDefinition.limChar = membersLimChar; + this.currentClassDefinition = null; + }; + Parser.prototype.parseClassConstructorDeclaration = function (minChar, errorRecoverySet, modifiers) { + this.parsingClassConstructorDefinition = true; + var isAmbient = this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient); + var args = new TypeScript.ASTList(); + var variableArgList = false; + var preComments = this.parseComments(); + var constructorSpan = new TypeScript.ASTSpan(); + constructorSpan.minChar = this.scanner.startPos; + constructorSpan.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { + variableArgList = this.parseFormalParameterList(errorRecoverySet, args, true, isAmbient, false, false, false, false, null, true); + if(args.members.length > 0) { + var lastArg = args.members[args.members.length - 1]; + } + } + var requiresSignature = isAmbient || this.currentToken.tokenId == TypeScript.TokenID.Semicolon; + if(requiresSignature) { + for(var i = 0; i < args.members.length; i++) { + var arg = args.members[i]; + if(TypeScript.hasFlag(arg.varFlags, TypeScript.VarFlags.Property)) { + this.reportParseError("Overload or ambient signatures may not specify parameter properties", arg.minChar, arg.limChar); + } + } + } + if(!requiresSignature) { + this.currentClassDefinition.constructorNestingLevel = this.nestingLevel + 1; + } + var constructorFuncDecl = this.parseFunctionStatements(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, this.currentClassDefinition.name, true, false, args, TypeScript.AllowedElements.Properties, minChar, requiresSignature, modifiers); + constructorFuncDecl.constructorSpan = constructorSpan; + constructorFuncDecl.preComments = preComments; + if(requiresSignature && !isAmbient) { + constructorFuncDecl.isOverload = true; + } + constructorFuncDecl.variableArgList = variableArgList; + this.currentClassDecl = null; + constructorFuncDecl.returnTypeAnnotation = this.convertToTypeReference(this.currentClassDefinition.name); + constructorFuncDecl.classDecl = this.currentClassDefinition; + if(isAmbient) { + constructorFuncDecl.fncFlags |= TypeScript.FncFlags.Ambient; + } + if(requiresSignature) { + constructorFuncDecl.fncFlags |= TypeScript.FncFlags.Signature; + } + if(this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { + constructorFuncDecl.fncFlags |= TypeScript.FncFlags.Exported; + } + if(this.currentClassDefinition.constructorDecl) { + if(!isAmbient && !this.currentClassDefinition.constructorDecl.isSignature() && !constructorFuncDecl.isSignature()) { + this.reportParseError("Duplicate constructor definition"); + } + } + if(isAmbient || !constructorFuncDecl.isSignature()) { + this.currentClassDefinition.constructorDecl = constructorFuncDecl; + } + constructorFuncDecl.fncFlags |= TypeScript.FncFlags.ClassMethod; + this.currentClassDefinition.members.members[this.currentClassDefinition.members.members.length] = constructorFuncDecl; + this.parsingClassConstructorDefinition = false; + return constructorFuncDecl; + }; + Parser.prototype.parseClassMemberVariableDeclaration = function (text, minChar, isDeclaredInConstructor, errorRecoverySet, modifiers) { + var varDecl = new TypeScript.VarDecl(text, this.nestingLevel); + varDecl.minChar = minChar; + var isStatic = false; + varDecl.preComments = this.parseComments(); + if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { + this.currentToken = this.scanner.scan(); + varDecl.typeExpr = this.parseTypeReference(errorRecoverySet | TypeScript.ErrorRecoverySet.Asg | TypeScript.ErrorRecoverySet.Comma, false); + if(varDecl.typeExpr && varDecl.typeExpr.nodeType == TypeScript.NodeType.TypeRef) { + var typeExpr = (varDecl.typeExpr); + if(typeExpr.term && typeExpr.term.nodeType == TypeScript.NodeType.FuncDecl) { + typeExpr.term.preComments = varDecl.preComments; + } + } + } + if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { + if(this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + this.reportParseError("context does not permit variable initializer"); + if(this.errorRecovery) { + this.skip(errorRecoverySet); + varDecl.flags |= TypeScript.ASTFlags.Error; + varDecl.limChar = this.scanner.lastTokenLimChar(); + return varDecl; + } + } + this.currentToken = this.scanner.scan(); + varDecl.init = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); + varDecl.limChar = varDecl.init.limChar; + if(!(modifiers & TypeScript.Modifiers.Static)) { + this.currentClassDefinition.varFlags |= TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor; + } + } else { + varDecl.limChar = this.scanner.pos; + } + if(modifiers & TypeScript.Modifiers.Static) { + varDecl.varFlags |= TypeScript.VarFlags.Static; + isStatic = true; + } + if((modifiers & TypeScript.Modifiers.Private) != TypeScript.Modifiers.None) { + varDecl.varFlags |= TypeScript.VarFlags.Private; + } else { + varDecl.varFlags |= TypeScript.VarFlags.Public; + } + varDecl.varFlags |= TypeScript.VarFlags.Property; + if(isDeclaredInConstructor) { + varDecl.varFlags |= TypeScript.VarFlags.ClassConstructorProperty; + } + if(!isDeclaredInConstructor && !isStatic) { + varDecl.varFlags |= TypeScript.VarFlags.ClassBodyProperty; + } + this.currentClassDefinition.knownMemberNames[text.actualText] = true; + if(!isDeclaredInConstructor) { + this.currentClassDefinition.members.members[this.currentClassDefinition.members.members.length] = varDecl; + } + varDecl.postComments = this.parseComments(); + return varDecl; + }; + Parser.prototype.parseClassMemberFunctionDeclaration = function (methodName, minChar, errorRecoverySet, modifiers) { + var wasAccessorID = this.prevIDTok != null; + var isAccessor = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter) || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Setter); + var isStatic = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Static); + var isAmbient = this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient); + errorRecoverySet |= TypeScript.ErrorRecoverySet.RParen; + if(isAccessor && (modifiers & TypeScript.Modifiers.Ambient)) { + this.reportParseError("Property accessors may not be declared in ambient classes"); + } + var ast = this.parseFncDecl(errorRecoverySet, true, isAmbient, true, methodName, false, isStatic, isAmbient, modifiers, null, true); + if(ast.nodeType == TypeScript.NodeType.Error) { + return ast; + } + var funcDecl = ast; + funcDecl.minChar = minChar; + if(funcDecl.bod !== null) { + funcDecl.limChar = funcDecl.bod.limChar; + } + if(modifiers & TypeScript.Modifiers.Private) { + funcDecl.fncFlags |= TypeScript.FncFlags.Private; + } else { + funcDecl.fncFlags |= TypeScript.FncFlags.Public; + } + if(isStatic) { + funcDecl.fncFlags |= TypeScript.FncFlags.Static; + } + if(isAccessor) { + if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter)) { + funcDecl.fncFlags |= TypeScript.FncFlags.GetAccessor; + funcDecl.hint = "get" + funcDecl.name.actualText; + } else { + funcDecl.fncFlags |= TypeScript.FncFlags.SetAccessor; + funcDecl.hint = "set" + funcDecl.name.actualText; + } + funcDecl.fncFlags |= TypeScript.FncFlags.IsFunctionExpression; + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("Property accessors are only available when targeting ES5 or greater", funcDecl.minChar, funcDecl.limChar); + } + } + funcDecl.fncFlags |= TypeScript.FncFlags.ClassMethod; + this.currentClassDefinition.knownMemberNames[methodName.actualText] = true; + this.currentClassDefinition.members.members[this.currentClassDefinition.members.members.length] = funcDecl; + return funcDecl; + }; + Parser.prototype.parseTypeMember = function (errorRecoverySet) { + var minChar = this.scanner.startPos; + var propertyDecl = this.parsePropertyDeclaration(errorRecoverySet, TypeScript.Modifiers.Public, true, false); + if(propertyDecl) { + propertyDecl.minChar = minChar; + if(propertyDecl.nodeType == TypeScript.NodeType.VarDecl) { + this.checkCurrentToken(TypeScript.TokenID.Semicolon, errorRecoverySet); + } + } + return propertyDecl; + }; + Parser.prototype.parseTypeMemberList = function (errorRecoverySet, members) { + errorRecoverySet |= TypeScript.ErrorRecoverySet.TypeScriptS; + while(true) { + switch(this.currentToken.tokenId) { + case TypeScript.TokenID.CloseBrace: + case TypeScript.TokenID.EndOfFile: + members.limChar = this.scanner.pos; + return; + } + var element = this.parseTypeMember(errorRecoverySet); + if(element) { + members.append(element); + } + } + }; + Parser.prototype.parseInterfaceDecl = function (errorRecoverySet, modifiers) { + var leftCurlyCount = this.scanner.leftCurlyCount; + var rightCurlyCount = this.scanner.rightCurlyCount; + this.currentToken = this.scanner.scan(); + var minChar = this.scanner.pos; + var name = null; + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || (!TypeScript.isPrimitiveTypeToken(this.currentToken) && TypeScript.convertTokToID(this.currentToken, this.strictMode))) { + name = TypeScript.Identifier.fromToken(this.currentToken); + name.minChar = this.scanner.startPos; + name.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + } else { + this.reportParseError("interface missing name"); + if(this.errorRecovery) { + name = new TypeScript.MissingIdentifier(); + name.minChar = this.scanner.pos; + name.limChar = this.scanner.pos; + name.flags |= TypeScript.ASTFlags.Error; + } + } + var extendsList = null; + var implementsList = null; + if(this.currentToken.tokenId === TypeScript.TokenID.Extends || this.currentToken.tokenId === TypeScript.TokenID.Implements) { + if(this.currentToken.tokenId === TypeScript.TokenID.Implements) { + this.reportParseError("Expected 'extends'"); + } + extendsList = new TypeScript.ASTList(); + implementsList = new TypeScript.ASTList(); + extendsList.minChar = this.scanner.startPos; + this.parseBaseList(extendsList, implementsList, errorRecoverySet, false); + } + var membersMinChar = this.scanner.startPos; + this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.TypeScriptS); + var members = new TypeScript.ASTList(); + members.minChar = membersMinChar; + var prevInInterfaceDecl = this.inInterfaceDecl; + this.inInterfaceDecl = true; + this.parseTypeMemberList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, members); + this.inInterfaceDecl = prevInInterfaceDecl; + this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); + var interfaceDecl = new TypeScript.InterfaceDeclaration(name, members, extendsList, null); + if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Private)) { + interfaceDecl.varFlags |= TypeScript.VarFlags.Private; + } + if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Public)) { + interfaceDecl.varFlags |= TypeScript.VarFlags.Public; + } + if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { + interfaceDecl.varFlags |= TypeScript.VarFlags.Exported; + } + interfaceDecl.limChar = members.limChar; + interfaceDecl.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; + interfaceDecl.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; + return interfaceDecl; + }; + Parser.prototype.makeVarDecl = function (id, nest) { + var varDecl = new TypeScript.VarDecl(id, nest); + var currentVarList = this.topVarList(); + if(currentVarList) { + currentVarList.append(varDecl); + } + return varDecl; + }; + Parser.prototype.parsePropertyDeclaration = function (errorRecoverySet, modifiers, requireSignature, isStatic, unnamedAmbientFunctionOk) { + var text = null; + var minChar = this.scanner.startPos; + var nameLimChar = minChar; + var isNew = false; + var isIndexer = false; + var wasAccessorID = this.prevIDTok != null; + var isAccessor = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter) || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Setter); + if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + requireSignature = true; + } + if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen && !wasAccessorID) { + if(!requireSignature && !isStatic) { + this.reportParseError("Expected identifier in property declaration"); + if(this.errorRecovery) { + this.skip(errorRecoverySet); + text = new TypeScript.MissingIdentifier(); + } + } + } else if(this.currentToken.tokenId == TypeScript.TokenID.New) { + if(requireSignature) { + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.OpenParen) { + isNew = true; + } + } + if(!isNew) { + if(!requireSignature) { + this.currentToken = this.scanner.scan(); + } + text = new TypeScript.Identifier("new"); + text.minChar = this.scanner.pos - 3; + text.limChar = this.scanner.pos; + nameLimChar = this.scanner.pos; + } + } else if((this.currentToken.tokenId == TypeScript.TokenID.OpenBracket) && requireSignature) { + isIndexer = true; + text = new TypeScript.Identifier("__item"); + } else if((this.currentToken.tokenId != TypeScript.TokenID.Identifier) && (!TypeScript.convertTokToIDName(this.currentToken)) && !wasAccessorID) { + this.reportParseError("Expected identifier in property declaration"); + if(this.errorRecovery) { + var eminChar = this.scanner.startPos; + var curpos = this.scanner.pos; + this.skip(errorRecoverySet & (~TypeScript.ErrorRecoverySet.Comma)); + if(this.scanner.pos == curpos) { + this.currentToken = this.scanner.scan(); + } + var epd = new TypeScript.VarDecl(new TypeScript.MissingIdentifier(), this.nestingLevel); + epd.flags |= TypeScript.ASTFlags.Error; + epd.minChar = eminChar; + epd.limChar = this.scanner.lastTokenLimChar(); + return epd; + } + } else { + if(wasAccessorID) { + text = TypeScript.Identifier.fromToken(this.prevIDTok); + text.minChar = this.scanner.lastTokenLimChar() - 3; + text.limChar = this.scanner.lastTokenLimChar(); + nameLimChar = text.limChar; + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("Property accessors are only available when targeting ES5 or greater"); + } + if(this.currentToken.getText() == text.actualText && this.currentToken != this.prevIDTok) { + this.currentToken = this.scanner.scan(); + } + this.prevIDTok = null; + } else { + text = TypeScript.Identifier.fromToken(this.currentToken); + text.minChar = this.scanner.startPos; + text.limChar = this.scanner.pos; + nameLimChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + } + } + if(this.currentToken.tokenId == TypeScript.TokenID.Question) { + if(this.inInterfaceDecl && text) { + text.flags |= TypeScript.ASTFlags.OptionalName; + } else { + this.reportParseError("Optional properties may only be declared on interface or object types"); + } + this.currentToken = this.scanner.scan(); + } + if((this.currentToken.tokenId == TypeScript.TokenID.OpenParen) || (isIndexer && (this.currentToken.tokenId == TypeScript.TokenID.OpenBracket))) { + var ers = errorRecoverySet | TypeScript.ErrorRecoverySet.RParen; + if(isIndexer) { + ers = errorRecoverySet | TypeScript.ErrorRecoverySet.RBrack; + } + if(!text && unnamedAmbientFunctionOk && !isIndexer) { + text = new TypeScript.MissingIdentifier(); + } + var ast = this.parseFncDecl(ers, true, requireSignature, this.currentClassDefinition || this.inInterfaceDecl, text, isIndexer, isStatic, (this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)), modifiers, null, true); + var funcDecl; + if(ast.nodeType == TypeScript.NodeType.Error) { + return ast; + } else { + funcDecl = ast; + } + if(funcDecl.name) { + funcDecl.name.minChar = minChar; + funcDecl.name.limChar = nameLimChar; + } + if((modifiers & TypeScript.Modifiers.Public) != TypeScript.Modifiers.None) { + funcDecl.fncFlags |= TypeScript.FncFlags.Public; + } + if((modifiers & TypeScript.Modifiers.Private) != TypeScript.Modifiers.None) { + funcDecl.fncFlags |= TypeScript.FncFlags.Private; + } + if(isStatic) { + funcDecl.fncFlags |= TypeScript.FncFlags.Static; + } + if(this.parsingDeclareFile || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + funcDecl.fncFlags |= TypeScript.FncFlags.Ambient; + } + if(isAccessor) { + if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Getter)) { + funcDecl.fncFlags |= TypeScript.FncFlags.GetAccessor; + funcDecl.hint = "get" + funcDecl.name.actualText; + } else { + funcDecl.fncFlags |= TypeScript.FncFlags.SetAccessor; + funcDecl.hint = "set" + funcDecl.name.actualText; + } + funcDecl.fncFlags |= TypeScript.FncFlags.IsFunctionExpression; + if(modifiers & TypeScript.Modifiers.Ambient) { + this.reportParseError("Property accessors may not be declared in ambient types"); + } + } + if(text == null || (text.isMissing() && unnamedAmbientFunctionOk && !isIndexer)) { + if(isNew) { + funcDecl.fncFlags |= TypeScript.FncFlags.ConstructMember; + funcDecl.hint = "_construct"; + funcDecl.classDecl = this.currentClassDecl; + } else { + funcDecl.hint = "_call"; + funcDecl.fncFlags |= TypeScript.FncFlags.CallMember; + } + } + return funcDecl; + } else { + var varDecl = new TypeScript.VarDecl(text, this.nestingLevel); + varDecl.preComments = this.parseComments(); + varDecl.minChar = minChar; + if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { + this.currentToken = this.scanner.scan(); + varDecl.typeExpr = this.parseTypeReference(errorRecoverySet | TypeScript.ErrorRecoverySet.Asg | TypeScript.ErrorRecoverySet.Comma, false); + if(varDecl.typeExpr && varDecl.typeExpr.nodeType == TypeScript.NodeType.TypeRef) { + var typeExpr = (varDecl.typeExpr); + if(typeExpr.term && typeExpr.term.nodeType == TypeScript.NodeType.FuncDecl) { + typeExpr.term.preComments = varDecl.preComments; + } + } + } + if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { + if(requireSignature) { + this.reportParseError("context does not permit variable initializer"); + if(this.errorRecovery) { + this.skip(errorRecoverySet); + varDecl.flags |= TypeScript.ASTFlags.Error; + varDecl.limChar = this.scanner.lastTokenLimChar(); + return varDecl; + } + } + this.currentToken = this.scanner.scan(); + varDecl.init = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); + varDecl.limChar = varDecl.init.limChar; + if(varDecl.init.nodeType == TypeScript.NodeType.FuncDecl) { + var funcDecl = varDecl.init; + funcDecl.hint = varDecl.id.text; + funcDecl.boundToProperty = varDecl; + } else if(isAccessor) { + this.reportParseError("Accessors may only be functions"); + } + } else { + varDecl.limChar = this.scanner.pos; + } + if((modifiers & TypeScript.Modifiers.Readonly) != TypeScript.Modifiers.None) { + varDecl.varFlags |= TypeScript.VarFlags.Readonly; + } + if(isStatic) { + varDecl.varFlags |= TypeScript.VarFlags.Static; + } + if((modifiers & TypeScript.Modifiers.Public) != TypeScript.Modifiers.None) { + varDecl.varFlags |= TypeScript.VarFlags.Public; + } + if((modifiers & TypeScript.Modifiers.Private) != TypeScript.Modifiers.None) { + varDecl.varFlags |= TypeScript.VarFlags.Private; + } + varDecl.varFlags |= TypeScript.VarFlags.Property; + return varDecl; + } + }; + Parser.prototype.parseVariableDeclaration = function (errorRecoverySet, modifiers, allowIn, isStatic) { + var isConst = TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Readonly); + var minChar = this.scanner.startPos; + var varDecl = null; + var declList = null; + var multivar = false; + this.currentToken = this.scanner.scan(); + var varDeclPreComments = this.parseComments(); + while(true) { + if((this.currentToken.tokenId != TypeScript.TokenID.Identifier) && (!TypeScript.convertTokToID(this.currentToken, this.strictMode))) { + this.reportParseError("Expected identifier in variable declaration"); + if(this.errorRecovery) { + varDecl = new TypeScript.VarDecl(new TypeScript.MissingIdentifier(), this.nestingLevel); + varDecl.minChar = minChar; + this.skip(errorRecoverySet); + varDecl.flags |= TypeScript.ASTFlags.Error; + varDecl.limChar = this.scanner.lastTokenLimChar(); + return varDecl; + } + } + var varDeclName = TypeScript.Identifier.fromToken(this.currentToken); + if(this.strictMode && (varDeclName.text == "eval")) { + this.reportParseError("'eval' may not name a variable in strict mode"); + } + varDecl = this.makeVarDecl(varDeclName, this.nestingLevel); + varDecl.id.minChar = this.scanner.startPos; + varDecl.id.limChar = this.scanner.pos; + varDecl.preComments = varDeclPreComments; + if(isStatic) { + varDecl.varFlags |= TypeScript.VarFlags.Static; + } + if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Readonly)) { + varDecl.varFlags |= TypeScript.VarFlags.Readonly; + } + if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + varDecl.varFlags |= TypeScript.VarFlags.Ambient; + } + if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { + varDecl.varFlags |= TypeScript.VarFlags.Exported; + } + varDecl.minChar = minChar; + if(declList) { + declList.append(varDecl); + } + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { + this.currentToken = this.scanner.scan(); + var prevInFncDecl = this.inFncDecl; + this.inFncDecl = false; + varDecl.typeExpr = this.parseTypeReference(errorRecoverySet | TypeScript.ErrorRecoverySet.Asg | TypeScript.ErrorRecoverySet.Comma, false); + this.inFncDecl = prevInFncDecl; + } + if(this.currentToken.tokenId == TypeScript.TokenID.Equals) { + if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Ambient)) { + this.reportParseError("Ambient variable can not have an initializer"); + } + this.currentToken = this.scanner.scan(); + varDecl.init = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, allowIn, TypeContext.NoTypes); + varDecl.limChar = varDecl.init.limChar; + if(varDecl.init.nodeType == TypeScript.NodeType.FuncDecl) { + var funcDecl = varDecl.init; + funcDecl.hint = varDecl.id.actualText; + } + } else { + if(isConst) { + this.reportParseError("const declaration requires initializer"); + } + varDecl.limChar = this.scanner.pos; + } + varDecl.postComments = this.parseCommentsForLine(this.scanner.line); + if(this.currentToken.tokenId != TypeScript.TokenID.Comma) { + if(declList) { + declList.limChar = varDecl.limChar; + return declList; + } else { + return varDecl; + } + } + if(!multivar) { + declList = new TypeScript.ASTList(); + declList.minChar = varDecl.minChar; + declList.append(varDecl); + multivar = true; + } + this.currentToken = this.scanner.scan(); + minChar = this.scanner.startPos; + } + }; + Parser.prototype.parseMemberList = function (errorRecoverySet) { + var elements = new TypeScript.ASTList(); + if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { + return elements; + } + var idHint = null; + var memberName = null; + var memberExpr = null; + var member = null; + var minChar = this.scanner.startPos; + var isSet = false; + var skippedTokenForGetSetId = false; + var getSetTok = null; + var getSetStartPos = 0; + var getSetPos = 0; + for(; ; ) { + var accessorPattern = false; + if(this.currentToken.tokenId == TypeScript.TokenID.Get || this.currentToken.tokenId == TypeScript.TokenID.Set) { + isSet = this.currentToken.tokenId == TypeScript.TokenID.Set; + getSetTok = this.currentToken; + getSetStartPos = this.scanner.startPos; + getSetPos = this.scanner.pos; + this.currentToken = this.scanner.scan(); + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToIDName(this.currentToken)) { + idHint = isSet ? "set" : "get"; + idHint = idHint + this.currentToken.getText(); + memberName = TypeScript.Identifier.fromToken(this.currentToken); + memberName.minChar = this.scanner.startPos; + accessorPattern = true; + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("Property accessors are only available when targeting ES5 or greater"); + } + } else if(this.currentToken.tokenId != TypeScript.TokenID.Colon) { + this.reportParseError("Expected identifier, string or number as accessor name"); + } else { + skippedTokenForGetSetId = true; + memberName = TypeScript.Identifier.fromToken(getSetTok); + memberName.minChar = getSetStartPos; + memberName.limChar = getSetPos; + } + } else if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToIDName(this.currentToken)) { + idHint = this.currentToken.getText(); + memberName = TypeScript.Identifier.fromToken(this.currentToken); + memberName.minChar = this.scanner.startPos; + memberName.limChar = this.scanner.pos; + } else if(this.currentToken.tokenId == TypeScript.TokenID.StringLiteral) { + idHint = this.currentToken.getText(); + memberName = new TypeScript.StringLiteral(idHint); + memberName.minChar = this.scanner.startPos; + memberName.limChar = this.scanner.pos; + } else if(this.currentToken.tokenId == TypeScript.TokenID.NumberLiteral) { + var ntok = this.currentToken; + idHint = ntok.value.toString(); + memberName = new TypeScript.StringLiteral(idHint); + memberName.minChar = this.scanner.startPos; + memberName.limChar = this.scanner.pos; + } else { + this.reportParseError("Expected identifier, string or number as member name"); + if(this.errorRecovery) { + memberName = new TypeScript.MissingIdentifier(); + memberName.minChar = this.scanner.startPos; + memberName.flags |= TypeScript.ASTFlags.Error; + this.skip(errorRecoverySet | TypeScript.ErrorRecoverySet.Comma); + memberName.limChar = this.scanner.lastTokenLimChar(); + } + } + if(!skippedTokenForGetSetId) { + this.currentToken = this.scanner.scan(); + } else { + skippedTokenForGetSetId = false; + } + if(this.currentToken.tokenId == TypeScript.TokenID.Question) { + memberName.flags |= TypeScript.ASTFlags.OptionalName; + this.currentToken = this.scanner.scan(); + } + if(accessorPattern) { + var args = new TypeScript.ASTList(); + this.parseFormalParameterList(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, args, false, true, false, !isSet, isSet, false, null, true); + var funcDecl = this.parseFunctionStatements(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, memberName, false, true, args, TypeScript.AllowedElements.None, this.scanner.startPos, false, TypeScript.Modifiers.None); + if(isSet && funcDecl.returnTypeAnnotation) { + this.reportParseError("Property setters may not declare a return type"); + } + funcDecl.fncFlags |= isSet ? TypeScript.FncFlags.SetAccessor : TypeScript.FncFlags.GetAccessor; + funcDecl.fncFlags |= TypeScript.FncFlags.IsFunctionExpression; + funcDecl.hint = idHint; + memberExpr = funcDecl; + member = new TypeScript.BinaryExpression(TypeScript.NodeType.Member, memberName, memberExpr); + member.minChar = memberName.minChar; + if(memberExpr.nodeType == TypeScript.NodeType.FuncDecl) { + var funcDecl = memberExpr; + funcDecl.hint = idHint; + } + } else if(this.currentToken.tokenId == TypeScript.TokenID.Colon) { + this.currentToken = this.scanner.scan(); + memberExpr = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); + if(memberExpr.nodeType == TypeScript.NodeType.TypeRef) { + this.reportParseError("Expected 'new' on array declaration in member definition"); + } + member = new TypeScript.BinaryExpression(TypeScript.NodeType.Member, memberName, memberExpr); + member.minChar = memberName.minChar; + if(memberExpr.nodeType == TypeScript.NodeType.FuncDecl) { + var funcDecl = memberExpr; + funcDecl.hint = idHint; + } + } else { + this.reportParseError("Expected ':' in member definition"); + if(this.errorRecovery) { + this.skip(errorRecoverySet); + elements.flags |= TypeScript.ASTFlags.Error; + elements.minChar = minChar; + elements.limChar = this.scanner.lastTokenLimChar(); + return elements; + } + } + idHint = null; + elements.append(member); + member.limChar = this.scanner.lastTokenLimChar(); + if(this.currentToken.tokenId != TypeScript.TokenID.Comma) { + break; + } else { + this.currentToken = this.scanner.scan(); + } + if(this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) { + break; + } + } + if(member) { + elements.limChar = member.limChar; + } + elements.minChar = minChar; + return elements; + }; + Parser.prototype.parseArrayList = function (errorRecoverySet) { + var elements = null; + if(this.currentToken.tokenId == TypeScript.TokenID.CloseBracket) { + return elements; + } else { + elements = new TypeScript.ASTList(); + elements.minChar = this.scanner.startPos; + } + var arg; + for(; ; ) { + if((this.currentToken.tokenId == TypeScript.TokenID.Comma) || (this.currentToken.tokenId == TypeScript.TokenID.CloseBracket)) { + arg = new TypeScript.AST(TypeScript.NodeType.EmptyExpr); + } else { + arg = this.parseExpr(TypeScript.ErrorRecoverySet.Comma | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, true, TypeContext.NoTypes); + } + elements.append(arg); + if(this.currentToken.tokenId != TypeScript.TokenID.Comma) { + break; + } + this.currentToken = this.scanner.scan(); + } + elements.limChar = this.scanner.lastTokenLimChar(); + return elements; + }; + Parser.prototype.parseArrayLiteral = function (errorRecoverySet) { + var arrayLiteral = null; + arrayLiteral = new TypeScript.UnaryExpression(TypeScript.NodeType.ArrayLit, this.parseArrayList(errorRecoverySet)); + return arrayLiteral; + }; + Parser.prototype.parseTerm = function (errorRecoverySet, allowCall, typeContext, inCast) { + var ast = null; + var sawId = false; + var inNew = false; + var minChar = this.scanner.startPos; + var limChar = this.scanner.pos; + var parseAsLambda = false; + var expectlambdaRParen = false; + switch(this.currentToken.tokenId) { + case TypeScript.TokenID.Number: + case TypeScript.TokenID.Bool: + case TypeScript.TokenID.Any: + case TypeScript.TokenID.String: + var tid = new TypeScript.Identifier(TypeScript.tokenTable[this.currentToken.tokenId].text); + if(TypeScript.hasFlag(typeContext, TypeContext.Primitive)) { + ast = new TypeScript.TypeReference(tid, 0); + sawId = true; + } else { + ast = tid; + sawId = true; + } + ast.minChar = minChar; + this.currentToken = this.scanner.scan(); + limChar = this.scanner.lastTokenLimChar(); + break; + case TypeScript.TokenID.This: + ast = new TypeScript.AST(TypeScript.NodeType.This); + ast.minChar = minChar; + this.currentToken = this.scanner.scan(); + limChar = this.scanner.lastTokenLimChar(); + break; + case TypeScript.TokenID.Super: + ast = new TypeScript.AST(TypeScript.NodeType.Super); + ast.minChar = minChar; + this.currentToken = this.scanner.scan(); + limChar = this.scanner.lastTokenLimChar(); + break; + case TypeScript.TokenID.True: + ast = new TypeScript.AST(TypeScript.NodeType.True); + this.currentToken = this.scanner.scan(); + ast.minChar = minChar; + break; + case TypeScript.TokenID.False: + ast = new TypeScript.AST(TypeScript.NodeType.False); + this.currentToken = this.scanner.scan(); + ast.minChar = minChar; + break; + case TypeScript.TokenID.Null: + ast = new TypeScript.AST(TypeScript.NodeType.Null); + this.currentToken = this.scanner.scan(); + ast.minChar = minChar; + break; + case TypeScript.TokenID.New: + this.currentToken = this.scanner.scan(); + var target = this.parseTerm(errorRecoverySet, false, TypeContext.AllSimpleTypes, inCast); + if(target.nodeType == TypeScript.NodeType.Error || (target.nodeType == TypeScript.NodeType.Index && (target).operand1.nodeType == TypeScript.NodeType.TypeRef)) { + this.reportParseError("Cannot invoke 'new' on this expression"); + } else { + ast = new TypeScript.CallExpression(TypeScript.NodeType.New, target, null); + ast.minChar = minChar; + limChar = this.currentToken.tokenId == TypeScript.TokenID.EndOfFile ? this.scanner.pos : this.scanner.lastTokenLimChar(); + inNew = true; + } + break; + case TypeScript.TokenID.Function: + minChar = this.scanner.pos; + ast = this.parseFncDecl(errorRecoverySet, false, false, false, null, false, false, false, TypeScript.Modifiers.None, null, true); + (ast).fncFlags |= TypeScript.FncFlags.IsFunctionExpression; + ast.minChar = minChar; + limChar = this.currentToken.tokenId == TypeScript.TokenID.EndOfFile ? this.scanner.pos : this.scanner.lastTokenLimChar(); + ast.limChar = limChar; + break; + } + if(ast == null) { + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + var idText = this.currentToken.getText(); + ast = this.createRef(idText, (this.currentToken).hasEscapeSequence, minChar); + sawId = true; + ast.minChar = minChar; + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.Question) { + ast.flags |= TypeScript.ASTFlags.PossibleOptionalParameter; + } + limChar = this.scanner.lastTokenLimChar(); + } + } + if(inCast) { + this.checkCurrentToken(TypeScript.TokenID.GreaterThan, errorRecoverySet); + } + if(ast == null) { + switch(this.currentToken.tokenId) { + case TypeScript.TokenID.OpenParen: + minChar = this.scanner.pos; + var prevTokId = this.scanner.previousToken().tokenId; + this.currentToken = this.scanner.scan(); + var couldBeLambda = prevTokId == TypeScript.TokenID.OpenParen || prevTokId == TypeScript.TokenID.Comma || prevTokId == TypeScript.TokenID.EqualsEquals || prevTokId == TypeScript.TokenID.Colon; + if(couldBeLambda && this.currentToken.tokenId == TypeScript.TokenID.CloseParen) { + parseAsLambda = true; + expectlambdaRParen = false; + this.currentToken = this.scanner.scan(); + } else if(couldBeLambda && this.currentToken.tokenId == TypeScript.TokenID.DotDotDot) { + parseAsLambda = true; + expectlambdaRParen = true; + } else { + ast = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes, couldBeLambda); + limChar = this.scanner.lastTokenLimChar(); + parseAsLambda = couldBeLambda && (ast.nodeType == TypeScript.NodeType.Name || ast.nodeType == TypeScript.NodeType.Comma) && (this.currentToken.tokenId == TypeScript.TokenID.Colon || this.currentToken.tokenId == TypeScript.TokenID.Question); + expectlambdaRParen = true; + } + if((ast && !parseAsLambda)) { + if(TypeScript.hasFlag(ast.flags, TypeScript.ASTFlags.SkipNextRParen)) { + ast.flags = ast.flags & (~(TypeScript.ASTFlags.SkipNextRParen)); + break; + } + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet); + ast.isParenthesized = true; + } + break; + case TypeScript.TokenID.NumberLiteral: { + var numTok = this.currentToken; + this.currentToken = this.scanner.scan(); + ast = new TypeScript.NumberLiteral(numTok.value, numTok.text); + ast.minChar = minChar; + limChar = this.scanner.lastTokenLimChar(); + break; + } + case TypeScript.TokenID.StringLiteral: + ast = new TypeScript.StringLiteral(this.currentToken.getText()); + this.currentToken = this.scanner.scan(); + ast.minChar = minChar; + limChar = this.scanner.lastTokenLimChar(); + break; + case TypeScript.TokenID.RegularExpressionLiteral: { + var rtok = this.currentToken; + ast = new TypeScript.RegexLiteral(rtok.text); + this.currentToken = this.scanner.scan(); + ast.minChar = minChar; + limChar = this.scanner.lastTokenLimChar(); + break; + } + case TypeScript.TokenID.OpenBracket: + minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + ast = this.parseArrayLiteral(TypeScript.ErrorRecoverySet.RBrack | errorRecoverySet); + ast.minChar = minChar; + limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseBracket, errorRecoverySet); + break; + case TypeScript.TokenID.OpenBrace: + minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + var members = this.parseMemberList(TypeScript.ErrorRecoverySet.RCurly | errorRecoverySet); + this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); + ast = new TypeScript.UnaryExpression(TypeScript.NodeType.ObjectLit, members); + ast.minChar = minChar; + limChar = this.scanner.lastTokenLimChar(); + members.minChar = minChar; + members.limChar = limChar; + break; + case TypeScript.TokenID.LessThan: + minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + var term = this.parseTypeReference(TypeScript.ErrorRecoverySet.BinOp, false); + this.checkCurrentToken(TypeScript.TokenID.GreaterThan, errorRecoverySet); + ast = new TypeScript.UnaryExpression(TypeScript.NodeType.TypeAssertion, this.parseExpr(errorRecoverySet, TypeScript.OperatorPrecedence.Unary, false, TypeContext.NoTypes)); + (ast).castTerm = term; + break; + default: + if(this.prevExpr && TypeScript.hasFlag(this.prevExpr.flags, TypeScript.ASTFlags.PossibleOptionalParameter)) { + parseAsLambda = true; + ast = this.prevExpr; + } else { + this.reportParseError("Check format of expression term"); + if(this.errorRecovery) { + var ident = new TypeScript.MissingIdentifier(); + ident.minChar = minChar; + ident.flags |= TypeScript.ASTFlags.Error; + this.skip(errorRecoverySet | TypeScript.ErrorRecoverySet.Postfix); + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + ident.setText(this.currentToken.getText(), (this.currentToken).hasEscapeSequence); + this.currentToken = this.scanner.scan(); + limChar = this.scanner.lastTokenLimChar(); + } else { + limChar = this.scanner.lastTokenLimChar(); + } + ast = ident; + } + } + } + } + if(parseAsLambda) { + if(this.currentToken.tokenId == TypeScript.TokenID.Colon || this.currentToken.tokenId == TypeScript.TokenID.Comma || this.currentToken.tokenId == TypeScript.TokenID.CloseParen || this.currentToken.tokenId == TypeScript.TokenID.DotDotDot) { + ast = this.parseLambdaExpr(errorRecoverySet, ast, true, expectlambdaRParen); + ast.minChar = minChar; + limChar = this.scanner.lastTokenLimChar(); + ast.limChar = limChar; + } else if(ast) { + ast.isParenthesized = true; + } + } + if(sawId && (typeContext != TypeContext.NoTypes)) { + typeContext |= TypeContext.ArraySuffix; + } + var postFix = this.parsePostfixOperators(errorRecoverySet, ast, allowCall, inNew, typeContext, minChar, limChar); + if(postFix) { + if(sawId && (postFix.nodeType == TypeScript.NodeType.Index)) { + var binExpr = postFix; + if(binExpr.operand2 == null) { + postFix = this.convertToTypeReference(postFix); + } + } + postFix.minChar = minChar; + postFix.limChar = TypeScript.max(postFix.limChar, this.scanner.lastTokenLimChar()); + return postFix; + } else { + return new TypeScript.AST(TypeScript.NodeType.Error); + } + }; + Parser.prototype.parseLambdaExpr = function (errorRecoverySet, lambdaArgs, skipNextRParen, expectClosingRParen) { + var ast = this.parseFncDecl(errorRecoverySet, false, false, false, null, false, false, false, TypeScript.Modifiers.None, { + preProcessedLambdaArgs: lambdaArgs + }, expectClosingRParen); + (ast).fncFlags |= TypeScript.FncFlags.IsFunctionExpression; + (ast).fncFlags |= TypeScript.FncFlags.IsFatArrowFunction; + if(!skipNextRParen) { + ast.flags |= TypeScript.ASTFlags.SkipNextRParen; + } + ast.limChar = this.scanner.lastTokenLimChar(); + ; + return ast; + }; + Parser.prototype.parseExpr = function (errorRecoverySet, minPrecedence, allowIn, typeContext, possiblyInLambda) { + if (typeof possiblyInLambda === "undefined") { possiblyInLambda = false; } + var ast = null; + var tokenInfo = TypeScript.lookupToken(this.currentToken.tokenId); + var canAssign = true; + var idHint = null; + var minChar = this.scanner.startPos; + var preComments = this.parseComments(); + var exprIsAnonLambda = false; + if((tokenInfo != undefined) && (tokenInfo.unopNodeType != TypeScript.NodeType.None)) { + canAssign = false; + this.currentToken = this.scanner.scan(); + var tempExpr = this.parseExpr(TypeScript.ErrorRecoverySet.BinOp | errorRecoverySet, tokenInfo.unopPrecedence, allowIn, TypeContext.NoTypes); + ast = new TypeScript.UnaryExpression(tokenInfo.unopNodeType, tempExpr); + ast.limChar = tempExpr.limChar; + ast.minChar = minChar; + } else { + ast = this.parseTerm(TypeScript.ErrorRecoverySet.BinOp | TypeScript.ErrorRecoverySet.AddOp | errorRecoverySet, true, typeContext, false); + var id; + var temp; + if(ast.nodeType == TypeScript.NodeType.Name) { + id = ast; + idHint = id.actualText; + } else if(ast.nodeType == TypeScript.NodeType.Dot) { + var subsumedExpr = false; + if(this.inferPropertiesFromThisAssignment && (this.currentToken.tokenId == TypeScript.TokenID.Colon || this.currentToken.tokenId == TypeScript.TokenID.Equals) && this.parsingClassConstructorDefinition && this.nestingLevel == this.currentClassDefinition.constructorNestingLevel && (ast).operand1.nodeType == TypeScript.NodeType.This) { + if((ast).operand2.nodeType == TypeScript.NodeType.Name) { + var op2ID = ((ast).operand2); + if(!this.currentClassDefinition.knownMemberNames[op2ID.actualText]) { + ast = this.parseClassMemberVariableDeclaration(op2ID, ast.minChar, true, errorRecoverySet, TypeScript.Modifiers.Public); + subsumedExpr = true; + } + } + } + if(!subsumedExpr) { + temp = ast; + while(temp.nodeType == TypeScript.NodeType.Dot) { + var binExpr = temp; + temp = binExpr.operand2; + } + if(temp.nodeType == TypeScript.NodeType.Name) { + id = temp; + idHint = id.actualText; + } + } + } + if((!this.scanner.lastTokenHadNewline()) && ((this.currentToken.tokenId == TypeScript.TokenID.PlusPlus) || (this.currentToken.tokenId == TypeScript.TokenID.MinusMinus))) { + canAssign = false; + var operand = ast; + ast = new TypeScript.UnaryExpression((this.currentToken.tokenId == TypeScript.TokenID.PlusPlus) ? TypeScript.NodeType.IncPost : TypeScript.NodeType.DecPost, operand); + ast.limChar = this.scanner.pos; + ast.minChar = operand.minChar; + this.currentToken = this.scanner.scan(); + } + } + for(; ; ) { + tokenInfo = TypeScript.lookupToken(this.currentToken.tokenId); + if((tokenInfo == undefined) || (tokenInfo.binopNodeType == TypeScript.NodeType.None)) { + break; + } + if((!allowIn) && (tokenInfo.binopNodeType == TypeScript.NodeType.In)) { + break; + } + if(tokenInfo.binopPrecedence == TypeScript.OperatorPrecedence.Assignment) { + if(tokenInfo.binopPrecedence < minPrecedence) { + break; + } + if(!canAssign) { + this.reportParseError("illegal assignment"); + } + } else if(tokenInfo.binopPrecedence <= minPrecedence) { + break; + } + if(possiblyInLambda && this.currentToken.tokenId == TypeScript.TokenID.Comma && this.scanner.getLookAheadToken().tokenId == TypeScript.TokenID.DotDotDot) { + exprIsAnonLambda = true; + canAssign = false; + ast = this.parseLambdaExpr(errorRecoverySet, ast, false, true); + break; + } + this.currentToken = this.scanner.scan(); + canAssign = false; + if(tokenInfo.binopNodeType == TypeScript.NodeType.ConditionalExpression) { + if(possiblyInLambda && (this.currentToken.tokenId == TypeScript.TokenID.Equals || this.currentToken.tokenId == TypeScript.TokenID.Colon || this.currentToken.tokenId == TypeScript.TokenID.CloseParen || this.currentToken.tokenId == TypeScript.TokenID.Comma)) { + exprIsAnonLambda = true; + canAssign = true; + } else { + this.prevExpr = ast; + var whenTrue = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.Colon, TypeScript.OperatorPrecedence.Assignment, allowIn, TypeContext.NoTypes); + this.prevExpr = null; + this.checkCurrentToken(TypeScript.TokenID.Colon, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); + var whenFalse = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.BinOp, TypeScript.OperatorPrecedence.Assignment, allowIn, TypeContext.NoTypes); + ast = new TypeScript.ConditionalExpression(ast, whenTrue, whenFalse); + } + } else { + var tc = TypeContext.NoTypes; + var binExpr2; + binExpr2 = new TypeScript.BinaryExpression(tokenInfo.binopNodeType, ast, this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.BinOp, tokenInfo.binopPrecedence, allowIn, TypeContext.NoTypes, possiblyInLambda)); + if(binExpr2.operand2.nodeType == TypeScript.NodeType.FuncDecl) { + var funcDecl = binExpr2.operand2; + funcDecl.hint = idHint; + } + binExpr2.minChar = ast.minChar; + binExpr2.limChar = this.scanner.lastTokenLimChar(); + idHint = null; + ast = binExpr2; + } + } + if(canAssign) { + ast.flags |= TypeScript.ASTFlags.Writeable; + } + if(!exprIsAnonLambda) { + ast.minChar = minChar; + ast.limChar = TypeScript.max(ast.limChar, this.scanner.lastTokenLimChar()); + if(preComments) { + ast.preComments = ast.preComments ? preComments.concat(ast.preComments) : preComments; + } + ast.postComments = this.parseCommentsForLine(this.scanner.line); + } + return ast; + }; + Parser.prototype.parsePostfixOperators = function (errorRecoverySet, ast, allowCall, inNew, typeContext, lhsMinChar, lhsLimChar) { + var count = 0; + if(!ast) { + ast = new TypeScript.AST(TypeScript.NodeType.EmptyExpr); + ast.isParenthesized = true; + } + ast.minChar = lhsMinChar; + ast.limChar = lhsLimChar; + for(; ; ) { + switch(this.currentToken.tokenId) { + case TypeScript.TokenID.OpenParen: + if(inNew) { + var callExpr = ast; + callExpr.arguments = this.parseArgList(errorRecoverySet); + inNew = false; + } else { + if(!allowCall) { + return ast; + } + ast = new TypeScript.CallExpression(TypeScript.NodeType.Call, ast, this.parseArgList(errorRecoverySet)); + ast.minChar = lhsMinChar; + } + ast.limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet); + break; + case TypeScript.TokenID.OpenBracket: + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.CloseBracket) { + if(TypeScript.hasFlag(typeContext, TypeContext.ArraySuffix)) { + this.currentToken = this.scanner.scan(); + if(ast.nodeType == TypeScript.NodeType.TypeRef) { + var typeRef = ast; + typeRef.arrayCount++; + } else { + ast = new TypeScript.BinaryExpression(TypeScript.NodeType.Index, ast, null); + } + ast.limChar = this.scanner.pos; + break; + } + } + ast = new TypeScript.BinaryExpression(TypeScript.NodeType.Index, ast, this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RBrack, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes)); + ast.minChar = lhsMinChar; + ast.limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseBracket, errorRecoverySet); + break; + case TypeScript.TokenID.Dot: { + var name = null; + var curpos = this.scanner.pos; + this.currentToken = this.scanner.scan(); + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || ((!this.errorRecovery || !this.scanner.lastTokenHadNewline()) && TypeScript.convertTokToIDName(this.currentToken))) { + ast.flags |= TypeScript.ASTFlags.DotLHS; + name = this.createRef(this.currentToken.getText(), (this.currentToken).hasEscapeSequence, this.scanner.startPos); + name.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + } else { + this.reportParseError("Expected identifier following dot"); + if(this.errorRecovery) { + this.skip(errorRecoverySet); + ast.flags |= (TypeScript.ASTFlags.Error | TypeScript.ASTFlags.DotLHS); + return ast; + } else { + name = new TypeScript.MissingIdentifier(); + } + } + ast = new TypeScript.BinaryExpression(TypeScript.NodeType.Dot, ast, name); + ast.minChar = lhsMinChar; + ast.limChar = this.scanner.lastTokenLimChar(); + break; + } + case TypeScript.TokenID.EqualsGreaterThan: + ast = this.parseFncDecl(errorRecoverySet, false, false, false, null, false, false, false, TypeScript.Modifiers.None, { + preProcessedLambdaArgs: ast + }, false); + (ast).fncFlags |= TypeScript.FncFlags.IsFunctionExpression; + ast.minChar = lhsMinChar; + ast.limChar = this.scanner.lastTokenLimChar(); + break; + default: + return ast; + } + } + }; + Parser.prototype.parseTry = function (tryNode, errorRecoverySet, parentModifiers) { + var minChar = this.scanner.startPos; + var preComments = this.parseComments(); + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId != TypeScript.TokenID.OpenBrace) { + this.reportParseError("Expected '{'"); + if(this.errorRecovery) { + var etryNode = tryNode; + etryNode.minChar = minChar; + etryNode.limChar = this.scanner.lastTokenLimChar(); + etryNode.flags |= TypeScript.ASTFlags.Error; + return etryNode; + } + } + tryNode.body = this.parseStatement(errorRecoverySet, TypeScript.AllowedElements.None, parentModifiers); + tryNode.minChar = minChar; + tryNode.limChar = tryNode.body.limChar; + tryNode.preComments = preComments; + tryNode.postComments = this.parseComments(); + return tryNode; + }; + Parser.prototype.parseCatch = function (errorRecoverySet, parentModifiers) { + var catchMinChar = this.scanner.startPos; + var preComments = this.parseComments(); + this.currentToken = this.scanner.scan(); + this.checkCurrentToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); + if((this.currentToken.tokenId != TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + this.reportParseError("Expected identifier in catch header"); + if(this.errorRecovery) { + this.skip(errorRecoverySet); + var ecatch = new TypeScript.Catch(new TypeScript.VarDecl(new TypeScript.MissingIdentifier(), this.nestingLevel), new TypeScript.Statement(TypeScript.NodeType.Empty)); + ecatch.statement.minChar = catchMinChar; + ecatch.statement.limChar = this.scanner.pos; + ecatch.minChar = this.scanner.startPos; + ecatch.limChar = this.scanner.pos; + ecatch.flags |= TypeScript.ASTFlags.Error; + return ecatch; + } + } + var param = new TypeScript.VarDecl(TypeScript.Identifier.fromToken(this.currentToken), this.nestingLevel); + param.id.minChar = this.scanner.startPos; + param.id.limChar = this.scanner.pos; + param.minChar = param.id.minChar; + param.limChar = param.id.limChar; + this.currentToken = this.scanner.scan(); + var statementPos = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); + if(this.currentToken.tokenId != TypeScript.TokenID.OpenBrace) { + this.reportParseError("Expected '{' to start catch body"); + if(this.errorRecovery) { + this.skip(errorRecoverySet); + var ecatch = new TypeScript.Catch(new TypeScript.VarDecl(new TypeScript.MissingIdentifier(), this.nestingLevel), new TypeScript.Statement(TypeScript.NodeType.Empty)); + ecatch.statement.minChar = catchMinChar; + ecatch.statement.limChar = statementPos; + ecatch.minChar = this.scanner.startPos; + ecatch.limChar = this.scanner.pos; + ecatch.flags |= TypeScript.ASTFlags.Error; + return ecatch; + } + } + var catchStmt = this.parseStatement(errorRecoverySet, TypeScript.AllowedElements.None, parentModifiers); + var catchNode = new TypeScript.Catch(param, catchStmt); + catchNode.statement.minChar = catchMinChar; + catchNode.statement.limChar = statementPos; + catchNode.minChar = catchMinChar; + catchNode.limChar = catchStmt.limChar; + catchNode.preComments = preComments; + catchNode.postComments = this.parseComments(); + return catchNode; + }; + Parser.prototype.parseFinally = function (errorRecoverySet, parentModifiers) { + var finMinChar = this.scanner.startPos; + var preComments = this.parseComments(); + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId != TypeScript.TokenID.OpenBrace) { + this.reportParseError("Expected '{' to start body of finally statement"); + if(this.errorRecovery) { + this.skip(errorRecoverySet); + var efin = new TypeScript.Finally(new TypeScript.Statement(TypeScript.NodeType.Empty)); + efin.flags |= TypeScript.ASTFlags.Error; + efin.minChar = this.scanner.startPos; + efin.limChar = this.scanner.pos; + return efin; + } + } + var finBody = this.parseStatement(errorRecoverySet, TypeScript.AllowedElements.None, parentModifiers); + var fin = new TypeScript.Finally(finBody); + fin.minChar = finMinChar; + fin.limChar = fin.body.limChar; + fin.preComments = preComments; + fin.postComments = this.parseComments(); + return fin; + }; + Parser.prototype.parseTryCatchFinally = function (errorRecoverySet, parentModifiers, labelList) { + var tryPart = new TypeScript.Try(null); + var tryMinChar = this.scanner.startPos; + this.pushStmt(tryPart, labelList); + this.parseTry(tryPart, errorRecoverySet | TypeScript.ErrorRecoverySet.Catch, parentModifiers); + this.popStmt(); + var tc = null; + var tf = null; + if(this.currentToken.tokenId == TypeScript.TokenID.Catch) { + var catchPart = this.parseCatch(errorRecoverySet | TypeScript.ErrorRecoverySet.Catch, parentModifiers); + tc = new TypeScript.TryCatch(tryPart, catchPart); + tc.minChar = tryPart.minChar; + tc.limChar = catchPart.limChar; + } + if(this.currentToken.tokenId != TypeScript.TokenID.Finally) { + if(tc == null) { + this.reportParseError("try with neither catch nor finally"); + if(this.errorRecovery) { + var etf = new TypeScript.TryFinally(tryPart, new TypeScript.Finally(new TypeScript.AST(TypeScript.NodeType.Empty))); + etf.flags |= TypeScript.ASTFlags.Error; + etf.minChar = this.scanner.startPos; + etf.limChar = this.scanner.pos; + return etf; + } + return new TypeScript.TryFinally(tryPart, new TypeScript.Finally(new TypeScript.AST(TypeScript.NodeType.Empty))); + } else { + return tc; + } + } else { + if(tc) { + tryPart = tc; + } + var finallyPart = this.parseFinally(errorRecoverySet, parentModifiers); + tf = new TypeScript.TryFinally(tryPart, finallyPart); + tf.minChar = tryMinChar; + tf.limChar = finallyPart.limChar; + return tf; + } + }; + Parser.prototype.parseStatement = function (errorRecoverySet, allowedElements, parentModifiers) { + var ast = null; + var labelList = null; + var astList = null; + var temp; + var modifiers = TypeScript.Modifiers.None; + var minChar = this.scanner.startPos; + var forInOk = false; + var needTerminator = false; + var fnOrVar = null; + var preComments = this.parseComments(); + function isAmbient() { + return TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient) || TypeScript.hasFlag(parentModifiers, TypeScript.Modifiers.Ambient); + } + function mayNotBeExported() { + if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { + this.reportError("Statement may not be exported"); + } + } + for(; ; ) { + switch(this.currentToken.tokenId) { + case TypeScript.TokenID.EndOfFile: + ast = new TypeScript.AST(TypeScript.NodeType.Error); + ast.minChar = minChar; + ast.limChar = this.scanner.pos; + break; + case TypeScript.TokenID.Function: + if(this.parsingDeclareFile || isAmbient() || this.ambientModule) { + this.currentToken = this.scanner.scan(); + fnOrVar = this.parsePropertyDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, modifiers, true, false, true); + if(fnOrVar.nodeType == TypeScript.NodeType.VarDecl) { + this.reportParseError("function keyword can only introduce function declaration"); + } else if((fnOrVar.nodeType == TypeScript.NodeType.FuncDecl) && ((fnOrVar).fncFlags , TypeScript.FncFlags.IsFatArrowFunction)) { + needTerminator = true; + } + ast = fnOrVar; + if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported) || this.parsingDeclareFile || this.ambientModule && ast.nodeType == TypeScript.NodeType.FuncDecl) { + (ast).fncFlags |= TypeScript.FncFlags.Exported; + } + } else { + ast = this.parseFncDecl(errorRecoverySet, true, false, false, null, false, false, false, modifiers, null, true); + if(TypeScript.hasFlag((ast).fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { + needTerminator = true; + } + if(this.ambientModule) { + this.reportParseError("function declaration not permitted within ambient module"); + } + if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { + (ast).fncFlags |= TypeScript.FncFlags.Exported; + } + } + break; + case TypeScript.TokenID.Module: + if((allowedElements & TypeScript.AllowedElements.ModuleDeclarations) == TypeScript.AllowedElements.None) { + this.reportParseError("module not allowed in this context"); + this.currentToken = this.scanner.scan(); + ast = new TypeScript.AST(TypeScript.NodeType.Error); + ast.minChar = minChar; + ast.limChar = this.scanner.lastTokenLimChar(); + } else { + ast = this.parseModuleDecl(errorRecoverySet, modifiers, preComments); + preComments = null; + } + break; + case TypeScript.TokenID.Import: + if((allowedElements & TypeScript.AllowedElements.ModuleDeclarations) == TypeScript.AllowedElements.None) { + this.reportParseError("module not allowed in this context"); + this.currentToken = this.scanner.scan(); + ast = new TypeScript.AST(TypeScript.NodeType.Error); + ast.minChar = minChar; + ast.limChar = this.scanner.lastTokenLimChar(); + } else { + if(TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { + this.reportParseError("export keyword not permitted on import declaration"); + } + ast = this.parseImportDeclaration(errorRecoverySet, modifiers); + needTerminator = true; + } + break; + case TypeScript.TokenID.Export: + if((allowedElements & TypeScript.AllowedElements.ModuleDeclarations) == TypeScript.AllowedElements.None) { + this.reportParseError("'export' statements are only allowed at the global and module levels"); + this.currentToken = this.scanner.scan(); + ast = new TypeScript.AST(TypeScript.NodeType.Error); + ast.minChar = minChar; + ast.limChar = this.scanner.lastTokenLimChar(); + } + if(this.topLevel) { + this.hasTopLevelImportOrExport = true; + } + modifiers |= TypeScript.Modifiers.Exported; + this.currentToken = this.scanner.scan(); + break; + case TypeScript.TokenID.Private: + modifiers |= TypeScript.Modifiers.Private; + this.currentToken = this.scanner.scan(); + if(this.parsingClassConstructorDefinition) { + if(!this.inferPropertiesFromThisAssignment) { + this.reportParseError("Property declarations are not permitted within constructor bodies"); + } + minChar = this.scanner.pos; + if(this.inferPropertiesFromThisAssignment && (this.currentToken.tokenId != TypeScript.TokenID.This || (this.currentToken = this.scanner.scan()).tokenId != TypeScript.TokenID.Dot)) { + this.reportParseError("Expected 'this.' for property declaration"); + this.currentToken = this.scanner.scan(); + ast = new TypeScript.AST(TypeScript.NodeType.Error); + ast.minChar = minChar; + ast.limChar = this.scanner.lastTokenLimChar(); + } else { + this.currentToken = this.scanner.scan(); + var id = TypeScript.Identifier.fromToken(this.currentToken); + id.minChar = this.scanner.startPos; + id.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + ast = this.parseClassMemberVariableDeclaration(id, minChar, this.parsingClassConstructorDefinition, errorRecoverySet, modifiers); + } + } else { + if(this.currentToken.tokenId != TypeScript.TokenID.Interface) { + if(this.currentToken.tokenId == TypeScript.TokenID.Get) { + this.prevIDTok = this.currentToken; + this.currentToken = this.scanner.scan(); + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("Property accessors are only available when targeting ES5 or greater"); + } + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + modifiers |= TypeScript.Modifiers.Getter; + this.prevIDTok = null; + } + } else if(this.currentToken.tokenId == TypeScript.TokenID.Set) { + this.prevIDTok = this.currentToken; + this.currentToken = this.scanner.scan(); + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("Property accessors are only available when targeting ES5 or greater"); + } + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + modifiers |= TypeScript.Modifiers.Setter; + this.prevIDTok = null; + } + } + fnOrVar = this.parsePropertyDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, modifiers, isAmbient(), false); + if((fnOrVar.nodeType == TypeScript.NodeType.VarDecl) || ((fnOrVar.nodeType == TypeScript.NodeType.FuncDecl) && (TypeScript.hasFlag((fnOrVar).fncFlags, TypeScript.FncFlags.IsFatArrowFunction)))) { + needTerminator = true; + } + ast = fnOrVar; + } + } + break; + case TypeScript.TokenID.Public: + if(this.parsingClassConstructorDefinition) { + if(!this.inferPropertiesFromThisAssignment) { + this.reportParseError("Property declarations are not permitted within constructor bodies"); + } + this.currentToken = this.scanner.scan(); + minChar = this.scanner.pos; + modifiers |= TypeScript.Modifiers.Public; + if(this.inferPropertiesFromThisAssignment && (this.currentToken.tokenId != TypeScript.TokenID.This || (this.currentToken = this.scanner.scan()).tokenId != TypeScript.TokenID.Dot)) { + this.reportParseError("Expected 'this.' for property declaration"); + this.currentToken = this.scanner.scan(); + ast = new TypeScript.AST(TypeScript.NodeType.Error); + ast.minChar = minChar; + ast.limChar = this.scanner.lastTokenLimChar(); + } else { + this.currentToken = this.scanner.scan(); + var id = TypeScript.Identifier.fromToken(this.currentToken); + id.minChar = this.scanner.startPos; + id.limChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + ast = this.parseClassMemberVariableDeclaration(id, minChar, this.parsingClassConstructorDefinition, errorRecoverySet, modifiers); + } + } else { + if((allowedElements & TypeScript.AllowedElements.Properties) == TypeScript.AllowedElements.None) { + this.reportParseError("'property' statements are only allowed within classes"); + this.currentToken = this.scanner.scan(); + ast = new TypeScript.AST(TypeScript.NodeType.Error); + ast.minChar = minChar; + ast.limChar = this.scanner.lastTokenLimChar(); + } else { + modifiers |= TypeScript.Modifiers.Public; + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.Get) { + this.prevIDTok = this.currentToken; + this.currentToken = this.scanner.scan(); + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("Property accessors are only available when targeting ES5 or greater"); + } + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + modifiers |= TypeScript.Modifiers.Getter; + this.prevIDTok = null; + } + } else if(this.currentToken.tokenId == TypeScript.TokenID.Set) { + this.prevIDTok = this.currentToken; + this.currentToken = this.scanner.scan(); + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("Property accessors are only available when targeting ES5 or greater"); + } + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + modifiers |= TypeScript.Modifiers.Setter; + this.prevIDTok = null; + } + } + fnOrVar = this.parsePropertyDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, modifiers, isAmbient(), false); + if((fnOrVar.nodeType == TypeScript.NodeType.VarDecl) || ((fnOrVar.nodeType == TypeScript.NodeType.FuncDecl) && TypeScript.hasFlag((fnOrVar).fncFlags, TypeScript.FncFlags.IsFatArrowFunction))) { + needTerminator = true; + } + ast = fnOrVar; + } + } + break; + case TypeScript.TokenID.Declare: + if(!(allowedElements & TypeScript.AllowedElements.AmbientDeclarations)) { + this.reportParseError("Ambient declarations are only allowed at the top-level or module scopes"); + } + if(!this.parsingDeclareFile && TypeScript.hasFlag(parentModifiers, TypeScript.Modifiers.Ambient)) { + this.reportParseError("Duplicate ambient declaration in this context. (Is the enclosing module or class already ambient?)"); + } + modifiers |= TypeScript.Modifiers.Ambient; + this.currentToken = this.scanner.scan(); + break; + case TypeScript.TokenID.Class: + if((allowedElements & TypeScript.AllowedElements.ClassDeclarations) == TypeScript.AllowedElements.None) { + this.reportParseError("class not allowed in this context"); + this.currentToken = this.scanner.scan(); + ast = new TypeScript.AST(TypeScript.NodeType.Error); + ast.minChar = minChar; + ast.limChar = this.scanner.lastTokenLimChar(); + } else { + ast = this.parseClassDecl(errorRecoverySet, minChar, modifiers); + } + break; + case TypeScript.TokenID.Interface: + if((allowedElements & TypeScript.AllowedElements.InterfaceDeclarations) == TypeScript.AllowedElements.None) { + this.reportParseError("interface not allowed in this context"); + this.currentToken = this.scanner.scan(); + ast = new TypeScript.AST(TypeScript.NodeType.Error); + ast.minChar = minChar; + ast.limChar = this.scanner.lastTokenLimChar(); + } else { + ast = this.parseInterfaceDecl(errorRecoverySet, modifiers); + } + break; + case TypeScript.TokenID.Var: + var declAst = this.parseVariableDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart, modifiers, true, false); + if(declAst.nodeType == TypeScript.NodeType.VarDecl) { + ast = declAst; + } else { + ast = new TypeScript.Block(declAst, false); + } + needTerminator = true; + break; + case TypeScript.TokenID.Static: + if(this.currentClassDecl == null) { + this.reportParseError("Statics may only be class members"); + } + mayNotBeExported(); + modifiers |= TypeScript.Modifiers.Public; + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.Get) { + this.prevIDTok = this.currentToken; + this.currentToken = this.scanner.scan(); + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("Property accessors are only available when targeting ES5 or greater"); + } + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + modifiers |= TypeScript.Modifiers.Getter; + this.prevIDTok = null; + } + } else if(this.currentToken.tokenId == TypeScript.TokenID.Set) { + this.currentToken = this.scanner.scan(); + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("Property accessors are only available when targeting ES5 or greater"); + } + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) || TypeScript.convertTokToID(this.currentToken, this.strictMode)) { + modifiers |= TypeScript.Modifiers.Setter; + } + } + if(isAmbient()) { + modifiers |= TypeScript.Modifiers.Ambient; + } + fnOrVar = this.parsePropertyDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, modifiers, this.parsingDeclareFile || (modifiers & TypeScript.Modifiers.Ambient) != TypeScript.Modifiers.None, true); + var staticsList = this.topStaticsList(); + if(staticsList && fnOrVar.nodeType == TypeScript.NodeType.VarDecl) { + staticsList.append(fnOrVar); + } + if(fnOrVar.nodeType == TypeScript.NodeType.VarDecl || ((fnOrVar.nodeType == TypeScript.NodeType.FuncDecl) && TypeScript.hasFlag((fnOrVar).fncFlags, TypeScript.FncFlags.IsFatArrowFunction))) { + needTerminator = true; + } + ast = fnOrVar; + break; + case TypeScript.TokenID.For: + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("syntax error: for statement does not take modifiers"); + } + minChar = this.scanner.startPos; + this.checkNextToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart | TypeScript.ErrorRecoverySet.Var); + forInOk = true; + switch(this.currentToken.tokenId) { + case TypeScript.TokenID.Var: + temp = this.parseVariableDeclaration(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon | TypeScript.ErrorRecoverySet.In, TypeScript.Modifiers.None, false, false); + break; + case TypeScript.TokenID.Semicolon: + temp = null; + break; + default: + temp = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon | TypeScript.ErrorRecoverySet.In, TypeScript.OperatorPrecedence.None, false, TypeContext.NoTypes); + break; + } + if(this.currentToken.tokenId == TypeScript.TokenID.In) { + if((temp == null) || (!forInOk)) { + this.reportParseError("malformed for statement"); + if(this.errorRecovery) { + this.skip(errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); + ast = new TypeScript.AST(TypeScript.NodeType.Empty); + ast.flags |= TypeScript.ASTFlags.Error; + } + } else { + this.currentToken = this.scanner.scan(); + var forInStmt = new TypeScript.ForInStatement(temp, this.parseExpr(TypeScript.ErrorRecoverySet.RParen | errorRecoverySet, TypeScript.OperatorPrecedence.Comma, false, TypeContext.NoTypes)); + forInStmt.limChar = this.scanner.pos; + forInStmt.statement.minChar = minChar; + forInStmt.statement.limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseParen, TypeScript.ErrorRecoverySet.StmtStart | errorRecoverySet); + this.pushStmt(forInStmt, labelList); + forInStmt.body = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); + this.popStmt(); + forInStmt.minChar = minChar; + ast = forInStmt; + } + } else { + var forStmt = new TypeScript.ForStatement(temp); + forStmt.minChar = minChar; + this.checkCurrentToken(TypeScript.TokenID.Semicolon, errorRecoverySet); + if(this.currentToken.tokenId == TypeScript.TokenID.Semicolon) { + forStmt.cond = null; + } else { + forStmt.cond = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); + if(this.currentToken.tokenId != TypeScript.TokenID.Semicolon) { + this.skip(errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); + ast = forStmt; + ast.flags |= TypeScript.ASTFlags.Error; + } + } + this.currentToken = this.scanner.scan(); + if(this.currentToken.tokenId == TypeScript.TokenID.CloseParen) { + forStmt.incr = null; + } else { + forStmt.incr = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); + } + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly); + this.pushStmt(forStmt, labelList); + forStmt.body = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); + this.popStmt(); + forStmt.limChar = forStmt.body.limChar; + ast = forStmt; + } + break; + case TypeScript.TokenID.With: + { + if(TypeScript.codeGenTarget < TypeScript.CodeGenTarget.ES5) { + this.reportParseError("'with' statements are only available in ES5 codegen mode or better"); + } + if(this.strictMode) { + this.reportParseError("'with' statements are not available in strict mode"); + } + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("'with' statement does not take modifiers"); + } + minChar = this.scanner.startPos; + this.checkNextToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart | TypeScript.ErrorRecoverySet.Var); + var expr = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.Colon, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly); + var withStmt = new TypeScript.WithStatement(expr); + withStmt.body = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); + withStmt.minChar = minChar; + withStmt.limChar = withStmt.body.limChar; + ast = withStmt; + } + break; + case TypeScript.TokenID.Switch: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("'switch' statement does not take modifiers"); + } + this.checkNextToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); + var switchStmt = new TypeScript.SwitchStatement(this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes)); + switchStmt.statement.minChar = minChar; + switchStmt.statement.limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.LCurly); + var caseListMinChar = this.scanner.startPos; + this.checkCurrentToken(TypeScript.TokenID.OpenBrace, errorRecoverySet | TypeScript.ErrorRecoverySet.SCase); + switchStmt.defaultCase = null; + switchStmt.caseList = new TypeScript.ASTList(); + var caseStmt = null; + this.pushStmt(switchStmt, labelList); + for(; ; ) { + if((this.currentToken.tokenId == TypeScript.TokenID.Case) || (this.currentToken.tokenId == TypeScript.TokenID.Default)) { + var isDefault = (this.currentToken.tokenId == TypeScript.TokenID.Default); + caseStmt = new TypeScript.CaseStatement(); + caseStmt.minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + if(isDefault) { + switchStmt.defaultCase = caseStmt; + } else { + caseStmt.expr = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.Colon, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); + } + caseStmt.colonSpan.minChar = this.scanner.startPos; + caseStmt.colonSpan.limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.Colon, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); + caseStmt.body = new TypeScript.ASTList(); + this.parseStatementList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, caseStmt.body, false, true, allowedElements, modifiers); + caseStmt.limChar = caseStmt.body.limChar; + switchStmt.caseList.append(caseStmt); + } else { + break; + } + } + switchStmt.caseList.minChar = caseListMinChar; + switchStmt.caseList.limChar = this.scanner.pos; + switchStmt.limChar = switchStmt.caseList.limChar; + this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); + this.popStmt(); + ast = switchStmt; + break; + } + case TypeScript.TokenID.While: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("'while' statement does not take modifiers"); + } + minChar = this.scanner.startPos; + this.checkNextToken(TypeScript.TokenID.OpenParen, TypeScript.ErrorRecoverySet.ExprStart | errorRecoverySet); + var whileStmt = new TypeScript.WhileStatement(this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes)); + whileStmt.minChar = minChar; + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); + this.pushStmt(whileStmt, labelList); + whileStmt.body = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); + whileStmt.limChar = whileStmt.body.limChar; + this.popStmt(); + ast = whileStmt; + break; + } + case TypeScript.TokenID.Do: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("'do' statement does not take modifiers"); + } + minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + var doStmt = new TypeScript.DoWhileStatement(); + doStmt.minChar = minChar; + this.pushStmt(doStmt, labelList); + doStmt.body = this.parseStatement(errorRecoverySet | TypeScript.ErrorRecoverySet.While, allowedElements, parentModifiers); + this.popStmt(); + doStmt.whileAST = new TypeScript.Identifier("while"); + doStmt.whileAST.minChar = this.scanner.startPos; + this.checkCurrentToken(TypeScript.TokenID.While, errorRecoverySet | TypeScript.ErrorRecoverySet.LParen); + doStmt.whileAST.limChar = doStmt.whileAST.minChar + 5; + this.checkCurrentToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); + doStmt.cond = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.RParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); + doStmt.limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet); + ast = doStmt; + if(this.currentToken.tokenId == TypeScript.TokenID.Semicolon) { + this.currentToken = this.scanner.scan(); + } + break; + } + case TypeScript.TokenID.If: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("if statement does not take modifiers"); + } + minChar = this.scanner.startPos; + this.checkNextToken(TypeScript.TokenID.OpenParen, errorRecoverySet | TypeScript.ErrorRecoverySet.ExprStart); + var ifStmt = new TypeScript.IfStatement(this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.LParen, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes)); + ifStmt.minChar = minChar; + ifStmt.statement.minChar = minChar; + ifStmt.statement.limChar = this.scanner.pos; + this.checkCurrentToken(TypeScript.TokenID.CloseParen, errorRecoverySet | TypeScript.ErrorRecoverySet.StmtStart); + this.pushStmt(ifStmt, labelList); + ifStmt.thenBod = this.parseStatement(TypeScript.ErrorRecoverySet.Else | errorRecoverySet, allowedElements, parentModifiers); + ifStmt.limChar = ifStmt.thenBod.limChar; + if(this.currentToken.tokenId == TypeScript.TokenID.Else) { + this.currentToken = this.scanner.scan(); + ifStmt.elseBod = this.parseStatement(errorRecoverySet, allowedElements, parentModifiers); + ifStmt.limChar = ifStmt.elseBod.limChar; + } + this.popStmt(); + ast = ifStmt; + break; + } + case TypeScript.TokenID.Try: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("try statement does not take modifiers"); + } + minChar = this.scanner.startPos; + ast = this.parseTryCatchFinally(errorRecoverySet, parentModifiers, labelList); + break; + } + case TypeScript.TokenID.OpenBrace: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("block does not take modifiers"); + } + minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + var block = new TypeScript.Block(new TypeScript.ASTList(), true); + this.pushStmt(block, labelList); + this.parseStatementList(errorRecoverySet | TypeScript.ErrorRecoverySet.RCurly, block.statements, false, false, TypeScript.AllowedElements.None, modifiers); + this.popStmt(); + block.statements.minChar = minChar; + block.statements.limChar = this.scanner.pos; + block.minChar = block.statements.minChar; + block.limChar = block.statements.limChar; + this.checkCurrentToken(TypeScript.TokenID.CloseBrace, errorRecoverySet); + ast = block; + break; + } + case TypeScript.TokenID.Semicolon: + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("modifier can not appear here"); + } + ast = new TypeScript.AST(TypeScript.NodeType.Empty); + this.currentToken = this.scanner.scan(); + break; + case TypeScript.TokenID.Break: + case TypeScript.TokenID.Continue: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("modifiers can not appear before jump statement"); + } + var jump = new TypeScript.Jump((this.currentToken.tokenId == TypeScript.TokenID.Break) ? TypeScript.NodeType.Break : TypeScript.NodeType.Continue); + this.currentToken = this.scanner.scan(); + if((this.currentToken.tokenId == TypeScript.TokenID.Identifier) && (!this.scanner.lastTokenHadNewline())) { + jump.target = this.currentToken.getText(); + this.currentToken = this.scanner.scan(); + } + this.resolveJumpTarget(jump); + ast = jump; + needTerminator = true; + break; + } + case TypeScript.TokenID.Return: { + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("modifiers can not appear before return statement"); + } + if(!this.inFunction) { + this.reportParseError("return statement outside of function body"); + } + minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + var retStmt = new TypeScript.ReturnStatement(); + retStmt.minChar = minChar; + if((this.currentToken.tokenId != TypeScript.TokenID.Semicolon) && (this.currentToken.tokenId != TypeScript.TokenID.CloseBrace) && (!(this.scanner.lastTokenHadNewline()))) { + retStmt.returnExpression = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); + } + needTerminator = true; + retStmt.limChar = this.scanner.lastTokenLimChar(); + ast = retStmt; + break; + } + case TypeScript.TokenID.Throw: + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("modifiers can not appear before a throw statement"); + } + minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + if((this.currentToken.tokenId != TypeScript.TokenID.Semicolon) && (this.currentToken.tokenId != TypeScript.TokenID.CloseBrace) && (!(this.scanner.lastTokenHadNewline()))) { + temp = this.parseExpr(errorRecoverySet | TypeScript.ErrorRecoverySet.SColon, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); + } else { + this.reportParseError("throw with no target"); + temp = null; + } + ast = new TypeScript.UnaryExpression(TypeScript.NodeType.Throw, temp); + ast.limChar = this.scanner.lastTokenLimChar(); + needTerminator = true; + break; + case TypeScript.TokenID.Enum: + this.currentToken = this.scanner.scan(); + ast = this.parseEnumDecl(errorRecoverySet, modifiers); + ast.minChar = minChar; + ast.limChar = this.scanner.lastTokenLimChar(); + if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Ambient)) { + (ast).modFlags |= TypeScript.ModuleFlags.Ambient; + } + if(this.parsingDeclareFile || this.ambientModule || TypeScript.hasFlag(modifiers, TypeScript.Modifiers.Exported)) { + (ast).modFlags |= TypeScript.ModuleFlags.Exported; + } + break; + case TypeScript.TokenID.Debugger: + mayNotBeExported(); + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("modifiers can not appear before debugger statement"); + } + minChar = this.scanner.startPos; + this.currentToken = this.scanner.scan(); + var debuggerStmt = new TypeScript.DebuggerStatement(); + debuggerStmt.minChar = minChar; + needTerminator = true; + debuggerStmt.limChar = this.scanner.lastTokenLimChar(); + ast = debuggerStmt; + break; + default: + if(modifiers != TypeScript.Modifiers.None) { + this.reportParseError("modifiers can not appear before an expression statement or label"); + } + minChar = this.scanner.startPos; + var svPos = this.scanner.pos; + temp = this.parseExpr(TypeScript.ErrorRecoverySet.Colon | TypeScript.ErrorRecoverySet.StmtStart | errorRecoverySet, TypeScript.OperatorPrecedence.None, true, TypeContext.NoTypes); + if(this.scanner.pos == svPos) { + this.currentToken = this.scanner.scan(); + ast = temp; + } else if((this.currentToken.tokenId == TypeScript.TokenID.Colon) && (!this.scanner.lastTokenHadNewline()) && temp && (temp.nodeType == TypeScript.NodeType.Name)) { + if(labelList == null) { + labelList = new TypeScript.ASTList(); + } + labelList.append(new TypeScript.Label(temp)); + this.currentToken = this.scanner.scan(); + } else { + ast = temp; + needTerminator = true; + } + } + if(ast) { + break; + } + } + if(needTerminator) { + switch(this.currentToken.tokenId) { + case TypeScript.TokenID.Semicolon: + this.currentToken = this.scanner.scan(); + ast.flags |= TypeScript.ASTFlags.ExplicitSemicolon; + break; + case TypeScript.TokenID.EndOfFile: + ast.limChar = this.scanner.pos; + case TypeScript.TokenID.CloseBrace: + ast.flags |= TypeScript.ASTFlags.AutomaticSemicolon; + if(this.style_requireSemi) { + this.reportParseStyleError("no automatic semicolon"); + } + break; + default: + if(!this.scanner.lastTokenHadNewline()) { + this.reportParseError("Expected ';'"); + } else { + ast.flags |= TypeScript.ASTFlags.AutomaticSemicolon; + if(this.style_requireSemi) { + this.reportParseStyleError("no automatic semicolon"); + } + } + break; + } + } + if(labelList) { + ast = new TypeScript.LabeledStatement(labelList, ast); + } + ast.minChar = minChar; + ast.limChar = TypeScript.max(ast.limChar, this.scanner.lastTokenLimChar()); + if(preComments) { + ast.preComments = ast.preComments ? preComments.concat(ast.preComments) : preComments; + } + if(this.ambientModule && (!this.okAmbientModuleMember(ast))) { + this.reportParseError("statement not permitted within ambient module"); + } + ast.flags |= TypeScript.ASTFlags.IsStatement; + return ast; + }; + Parser.prototype.okAmbientModuleMember = function (ast) { + var nt = ast.nodeType; + return (nt == TypeScript.NodeType.ClassDeclaration) || (nt == TypeScript.NodeType.ImportDeclaration) || (nt == TypeScript.NodeType.InterfaceDeclaration) || (nt == TypeScript.NodeType.ModuleDeclaration) || (nt == TypeScript.NodeType.Empty) || (nt == TypeScript.NodeType.VarDecl) || ((nt == TypeScript.NodeType.Block) && !(ast).isStatementBlock) || ((nt == TypeScript.NodeType.FuncDecl) && ((ast).bod == null)); + }; + Parser.prototype.parseStatementList = function (errorRecoverySet, statements, sourceElms, noLeadingCase, allowedElements, parentModifiers) { + var directivePrologue = sourceElms; + statements.minChar = this.scanner.startPos; + var limChar = this.scanner.pos; + var innerStmts = (allowedElements & TypeScript.AllowedElements.ModuleDeclarations) == TypeScript.AllowedElements.None; + var classNope = (allowedElements & TypeScript.AllowedElements.ClassDeclarations) == TypeScript.AllowedElements.None; + errorRecoverySet |= TypeScript.ErrorRecoverySet.TypeScriptS | TypeScript.ErrorRecoverySet.RCurly; + var oldStrictMode = this.strictMode; + this.nestingLevel++; + for(; ; ) { + if((this.currentToken.tokenId == TypeScript.TokenID.CloseBrace) || (noLeadingCase && ((this.currentToken.tokenId == TypeScript.TokenID.Case) || (this.currentToken.tokenId == TypeScript.TokenID.Default))) || (innerStmts && (this.currentToken.tokenId == TypeScript.TokenID.Export)) || (classNope && (this.currentToken.tokenId == TypeScript.TokenID.Class)) || (this.currentToken.tokenId == TypeScript.TokenID.EndOfFile)) { + statements.limChar = limChar; + if(statements.members.length == 0) { + statements.preComments = this.parseComments(); + } else { + statements.postComments = this.parseComments(); + } + this.strictMode = oldStrictMode; + this.nestingLevel--; + return; + } + var stmt = this.parseStatement(errorRecoverySet & (~(TypeScript.ErrorRecoverySet.Else | TypeScript.ErrorRecoverySet.RParen | TypeScript.ErrorRecoverySet.Catch | TypeScript.ErrorRecoverySet.Colon)), allowedElements, parentModifiers); + if(stmt) { + stmt.postComments = this.combineComments(stmt.postComments, this.parseCommentsForLine(this.scanner.prevLine)); + statements.append(stmt); + limChar = stmt.limChar; + if(directivePrologue) { + if(stmt.nodeType == TypeScript.NodeType.QString) { + var qstring = stmt; + if(qstring.text == "\"use strict\"") { + statements.flags |= TypeScript.ASTFlags.StrictMode; + this.strictMode = true; + } else { + directivePrologue = false; + } + } else { + directivePrologue = false; + } + } + } + } + }; + Parser.prototype.quickParse = function (sourceText, filename, unitIndex) { + var svGenTarget = TypeScript.moduleGenTarget; + try { + TypeScript.moduleGenTarget = TypeScript.ModuleGenTarget.Local; + var script = this.parse(sourceText, filename, unitIndex, TypeScript.AllowedElements.QuickParse); + return new QuickParseResult(script, this.scanner.lexState); + }finally { + TypeScript.moduleGenTarget = svGenTarget; + } + }; + Parser.prototype.parse = function (sourceText, filename, unitIndex, allowedElements) { + if (typeof allowedElements === "undefined") { allowedElements = TypeScript.AllowedElements.Global; } + var _this = this; + this.fname = filename; + this.currentUnitIndex = unitIndex; + this.currentToken = null; + this.needTerminator = false; + this.inFunction = false; + this.inInterfaceDecl = false; + this.inFncDecl = false; + this.ambientModule = false; + this.ambientClass = false; + this.topLevel = true; + this.allowImportDeclaration = true; + this.prevIDTok = null; + this.statementInfoStack = new Array(); + this.hasTopLevelImportOrExport = false; + this.strictMode = false; + this.nestingLevel = 0; + this.prevExpr = null; + this.currentClassDefinition = null; + this.parsingClassConstructorDefinition = false; + this.parsingDeclareFile = false; + this.amdDependencies = []; + this.inferPropertiesFromThisAssignment = false; + this.requiresExtendsBlock = false; + this.scanner.resetComments(); + this.scanner.setErrorHandler(function (message) { + return _this.reportParseError(message); + }); + this.scanner.setSourceText(sourceText, TypeScript.LexMode.File); + var leftCurlyCount = this.scanner.leftCurlyCount; + var rightCurlyCount = this.scanner.rightCurlyCount; + var minChar = this.scanner.pos; + this.currentToken = this.scanner.scan(); + this.pushDeclLists(); + var bod = new TypeScript.ASTList(); + bod.minChar = minChar; + this.parsingDeclareFile = TypeScript.isDSTRFile(filename) || TypeScript.isDTSFile(filename); + while(true) { + this.parseStatementList(TypeScript.ErrorRecoverySet.EOF | TypeScript.ErrorRecoverySet.Func, bod, true, false, allowedElements, TypeScript.Modifiers.None); + if(this.currentToken.tokenId === TypeScript.TokenID.EndOfFile) { + break; + } + var badToken = TypeScript.tokenTable[this.currentToken.tokenId]; + this.reportParseError("Unexpected statement block terminator '" + badToken.text + "'"); + this.currentToken = this.scanner.scan(); + } + bod.limChar = this.scanner.pos; + var topLevelMod = null; + if(TypeScript.moduleGenTarget != TypeScript.ModuleGenTarget.Local && this.hasTopLevelImportOrExport) { + var correctedFileName = TypeScript.switchToForwardSlashes(filename); + var id = new TypeScript.Identifier(correctedFileName); + topLevelMod = new TypeScript.ModuleDeclaration(id, bod, this.topVarList(), null); + topLevelMod.modFlags |= TypeScript.ModuleFlags.IsDynamic; + topLevelMod.modFlags |= TypeScript.ModuleFlags.IsWholeFile; + topLevelMod.modFlags |= TypeScript.ModuleFlags.Exported; + if(this.parsingDeclareFile) { + topLevelMod.modFlags |= TypeScript.ModuleFlags.Ambient; + } + topLevelMod.minChar = minChar; + topLevelMod.limChar = this.scanner.pos; + topLevelMod.prettyName = TypeScript.getPrettyName(correctedFileName); + topLevelMod.containsUnicodeChar = this.scanner.seenUnicodeChar; + topLevelMod.containsUnicodeCharInComment = this.scanner.seenUnicodeCharInComment; + topLevelMod.amdDependencies = this.amdDependencies; + bod = new TypeScript.ASTList(); + bod.minChar = topLevelMod.minChar; + bod.limChar = topLevelMod.limChar; + bod.append(topLevelMod); + } + var script = new TypeScript.Script(this.topVarList(), this.topScopeList()); + script.bod = bod; + this.popDeclLists(); + script.minChar = minChar; + script.limChar = this.scanner.pos; + script.locationInfo = new TypeScript.LocationInfo(filename, this.scanner.lineMap, unitIndex); + script.leftCurlyCount = this.scanner.leftCurlyCount - leftCurlyCount; + script.rightCurlyCount = this.scanner.rightCurlyCount - rightCurlyCount; + script.isDeclareFile = this.parsingDeclareFile; + script.topLevelMod = topLevelMod; + script.containsUnicodeChar = this.scanner.seenUnicodeChar; + script.containsUnicodeCharInComment = this.scanner.seenUnicodeCharInComment; + script.requiresExtendsBlock = this.requiresExtendsBlock; + return script; + }; + return Parser; + })(); + TypeScript.Parser = Parser; + function quickParse(logger, scopeStartAST, sourceText, minChar, limChar, errorCapture) { + var fragment = sourceText.getText(minChar, limChar); + logger.log("Quick parse range (" + minChar + "," + limChar + "): \"" + TypeScript.stringToLiteral(fragment, 100) + "\""); + var quickParser = new Parser(); + quickParser.setErrorRecovery(null); + quickParser.errorCallback = errorCapture; + var quickClassDecl = new TypeScript.ClassDeclaration(null, null, null, null); + quickParser.currentClassDecl = quickClassDecl; + var result = quickParser.quickParse(new TypeScript.StringSourceText(fragment), "", 0); + return result; + } + TypeScript.quickParse = quickParse; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var PrintContext = (function () { + function PrintContext(outfile, parser) { + this.outfile = outfile; + this.parser = parser; + this.builder = ""; + this.indent1 = " "; + this.indentStrings = []; + this.indentAmt = 0; + } + PrintContext.prototype.increaseIndent = function () { + this.indentAmt++; + }; + PrintContext.prototype.decreaseIndent = function () { + this.indentAmt--; + }; + PrintContext.prototype.startLine = function () { + if(this.builder.length > 0) { + TypeScript.CompilerDiagnostics.Alert(this.builder); + } + var indentString = this.indentStrings[this.indentAmt]; + if(indentString === undefined) { + indentString = ""; + for(var i = 0; i < this.indentAmt; i++) { + indentString += this.indent1; + } + this.indentStrings[this.indentAmt] = indentString; + } + this.builder += indentString; + }; + PrintContext.prototype.write = function (s) { + this.builder += s; + }; + PrintContext.prototype.writeLine = function (s) { + this.builder += s; + this.outfile.WriteLine(this.builder); + this.builder = ""; + }; + return PrintContext; + })(); + TypeScript.PrintContext = PrintContext; + function prePrintAST(ast, parent, walker) { + var pc = walker.state; + ast.print(pc); + pc.increaseIndent(); + return ast; + } + TypeScript.prePrintAST = prePrintAST; + function postPrintAST(ast, parent, walker) { + var pc = walker.state; + pc.decreaseIndent(); + return ast; + } + TypeScript.postPrintAST = postPrintAST; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + TypeScript.LexEOF = (-1); + TypeScript.LexCodeNWL = 0x0A; + TypeScript.LexCodeRET = 0x0D; + TypeScript.LexCodeLS = 0x2028; + TypeScript.LexCodePS = 0x2029; + TypeScript.LexCodeTAB = 0x09; + TypeScript.LexCodeVTAB = 0x0B; + TypeScript.LexCode_e = 'e'.charCodeAt(0); + TypeScript.LexCode_E = 'E'.charCodeAt(0); + TypeScript.LexCode_x = 'x'.charCodeAt(0); + TypeScript.LexCode_X = 'X'.charCodeAt(0); + TypeScript.LexCode_a = 'a'.charCodeAt(0); + TypeScript.LexCode_A = 'A'.charCodeAt(0); + TypeScript.LexCode_f = 'f'.charCodeAt(0); + TypeScript.LexCode_F = 'F'.charCodeAt(0); + TypeScript.LexCode_g = 'g'.charCodeAt(0); + TypeScript.LexCode_m = 'm'.charCodeAt(0); + TypeScript.LexCode_i = 'i'.charCodeAt(0); + TypeScript.LexCode_u = 'u'.charCodeAt(0); + TypeScript.LexCode_0 = '0'.charCodeAt(0); + TypeScript.LexCode_9 = '9'.charCodeAt(0); + TypeScript.LexCode_8 = '8'.charCodeAt(0); + TypeScript.LexCode_7 = '7'.charCodeAt(0); + TypeScript.LexCodeBSL = '\\'.charCodeAt(0); + TypeScript.LexCodeSHP = '#'.charCodeAt(0); + TypeScript.LexCodeBNG = '!'.charCodeAt(0); + TypeScript.LexCodeQUO = '"'.charCodeAt(0); + TypeScript.LexCodeAPO = '\''.charCodeAt(0); + TypeScript.LexCodePCT = '%'.charCodeAt(0); + TypeScript.LexCodeAMP = '&'.charCodeAt(0); + TypeScript.LexCodeLPR = '('.charCodeAt(0); + TypeScript.LexCodeRPR = ')'.charCodeAt(0); + TypeScript.LexCodePLS = '+'.charCodeAt(0); + TypeScript.LexCodeMIN = '-'.charCodeAt(0); + TypeScript.LexCodeMUL = '*'.charCodeAt(0); + TypeScript.LexCodeSLH = '/'.charCodeAt(0); + TypeScript.LexCodeXOR = '^'.charCodeAt(0); + TypeScript.LexCodeCMA = ','.charCodeAt(0); + TypeScript.LexCodeDOT = '.'.charCodeAt(0); + TypeScript.LexCodeLT = '<'.charCodeAt(0); + TypeScript.LexCodeEQ = '='.charCodeAt(0); + TypeScript.LexCodeGT = '>'.charCodeAt(0); + TypeScript.LexCodeQUE = '?'.charCodeAt(0); + TypeScript.LexCodeLBR = '['.charCodeAt(0); + TypeScript.LexCodeRBR = ']'.charCodeAt(0); + TypeScript.LexCodeUSC = '_'.charCodeAt(0); + TypeScript.LexCodeLC = '{'.charCodeAt(0); + TypeScript.LexCodeRC = '}'.charCodeAt(0); + TypeScript.LexCodeBAR = '|'.charCodeAt(0); + TypeScript.LexCodeTIL = '~'.charCodeAt(0); + TypeScript.LexCodeCOL = ':'.charCodeAt(0); + TypeScript.LexCodeSMC = ';'.charCodeAt(0); + TypeScript.LexCodeUnderscore = '_'.charCodeAt(0); + TypeScript.LexCodeDollar = '$'.charCodeAt(0); + TypeScript.LexCodeSpace = 32; + TypeScript.LexCodeAtSign = '@'.charCodeAt(0); + TypeScript.LexCodeASCIIChars = 128; + TypeScript.LexKeywordTable = undefined; + var autoToken = new Array(TypeScript.LexCodeASCIIChars); + var lexIdStartTable = new Array(TypeScript.LexCodeASCIIChars); + var unicodeES3IdStart = [ + 170, + 170, + 181, + 181, + 186, + 186, + 192, + 214, + 216, + 246, + 248, + 543, + 546, + 563, + 592, + 685, + 688, + 696, + 699, + 705, + 720, + 721, + 736, + 740, + 750, + 750, + 890, + 890, + 902, + 902, + 904, + 906, + 908, + 908, + 910, + 929, + 931, + 974, + 976, + 983, + 986, + 1011, + 1024, + 1153, + 1164, + 1220, + 1223, + 1224, + 1227, + 1228, + 1232, + 1269, + 1272, + 1273, + 1329, + 1366, + 1369, + 1369, + 1377, + 1415, + 1488, + 1514, + 1520, + 1522, + 1569, + 1594, + 1600, + 1610, + 1649, + 1747, + 1749, + 1749, + 1765, + 1766, + 1786, + 1788, + 1808, + 1808, + 1810, + 1836, + 1920, + 1957, + 2309, + 2361, + 2365, + 2365, + 2384, + 2384, + 2392, + 2401, + 2437, + 2444, + 2447, + 2448, + 2451, + 2472, + 2474, + 2480, + 2482, + 2482, + 2486, + 2489, + 2524, + 2525, + 2527, + 2529, + 2544, + 2545, + 2565, + 2570, + 2575, + 2576, + 2579, + 2600, + 2602, + 2608, + 2610, + 2611, + 2613, + 2614, + 2616, + 2617, + 2649, + 2652, + 2654, + 2654, + 2674, + 2676, + 2693, + 2699, + 2701, + 2701, + 2703, + 2705, + 2707, + 2728, + 2730, + 2736, + 2738, + 2739, + 2741, + 2745, + 2749, + 2749, + 2768, + 2768, + 2784, + 2784, + 2821, + 2828, + 2831, + 2832, + 2835, + 2856, + 2858, + 2864, + 2866, + 2867, + 2870, + 2873, + 2877, + 2877, + 2908, + 2909, + 2911, + 2913, + 2949, + 2954, + 2958, + 2960, + 2962, + 2965, + 2969, + 2970, + 2972, + 2972, + 2974, + 2975, + 2979, + 2980, + 2984, + 2986, + 2990, + 2997, + 2999, + 3001, + 3077, + 3084, + 3086, + 3088, + 3090, + 3112, + 3114, + 3123, + 3125, + 3129, + 3168, + 3169, + 3205, + 3212, + 3214, + 3216, + 3218, + 3240, + 3242, + 3251, + 3253, + 3257, + 3294, + 3294, + 3296, + 3297, + 3333, + 3340, + 3342, + 3344, + 3346, + 3368, + 3370, + 3385, + 3424, + 3425, + 3461, + 3478, + 3482, + 3505, + 3507, + 3515, + 3517, + 3517, + 3520, + 3526, + 3585, + 3632, + 3634, + 3635, + 3648, + 3654, + 3713, + 3714, + 3716, + 3716, + 3719, + 3720, + 3722, + 3722, + 3725, + 3725, + 3732, + 3735, + 3737, + 3743, + 3745, + 3747, + 3749, + 3749, + 3751, + 3751, + 3754, + 3755, + 3757, + 3760, + 3762, + 3763, + 3773, + 3773, + 3776, + 3780, + 3782, + 3782, + 3804, + 3805, + 3840, + 3840, + 3904, + 3911, + 3913, + 3946, + 3976, + 3979, + 4096, + 4129, + 4131, + 4135, + 4137, + 4138, + 4176, + 4181, + 4256, + 4293, + 4304, + 4342, + 4352, + 4441, + 4447, + 4514, + 4520, + 4601, + 4608, + 4614, + 4616, + 4678, + 4680, + 4680, + 4682, + 4685, + 4688, + 4694, + 4696, + 4696, + 4698, + 4701, + 4704, + 4742, + 4744, + 4744, + 4746, + 4749, + 4752, + 4782, + 4784, + 4784, + 4786, + 4789, + 4792, + 4798, + 4800, + 4800, + 4802, + 4805, + 4808, + 4814, + 4816, + 4822, + 4824, + 4846, + 4848, + 4878, + 4880, + 4880, + 4882, + 4885, + 4888, + 4894, + 4896, + 4934, + 4936, + 4954, + 5024, + 5108, + 5121, + 5740, + 5743, + 5750, + 5761, + 5786, + 5792, + 5866, + 6016, + 6067, + 6176, + 6263, + 6272, + 6312, + 7680, + 7835, + 7840, + 7929, + 7936, + 7957, + 7960, + 7965, + 7968, + 8005, + 8008, + 8013, + 8016, + 8023, + 8025, + 8025, + 8027, + 8027, + 8029, + 8029, + 8031, + 8061, + 8064, + 8116, + 8118, + 8124, + 8126, + 8126, + 8130, + 8132, + 8134, + 8140, + 8144, + 8147, + 8150, + 8155, + 8160, + 8172, + 8178, + 8180, + 8182, + 8188, + 8319, + 8319, + 8450, + 8450, + 8455, + 8455, + 8458, + 8467, + 8469, + 8469, + 8473, + 8477, + 8484, + 8484, + 8486, + 8486, + 8488, + 8488, + 8490, + 8493, + 8495, + 8497, + 8499, + 8505, + 8544, + 8579, + 12293, + 12295, + 12321, + 12329, + 12337, + 12341, + 12344, + 12346, + 12353, + 12436, + 12445, + 12446, + 12449, + 12538, + 12540, + 12542, + 12549, + 12588, + 12593, + 12686, + 12704, + 12727, + 13312, + 19893, + 19968, + 40869, + 40960, + 42124, + 44032, + 55203, + 63744, + 64045, + 64256, + 64262, + 64275, + 64279, + 64285, + 64285, + 64287, + 64296, + 64298, + 64310, + 64312, + 64316, + 64318, + 64318, + 64320, + 64321, + 64323, + 64324, + 64326, + 64433, + 64467, + 64829, + 64848, + 64911, + 64914, + 64967, + 65008, + 65019, + 65136, + 65138, + 65140, + 65140, + 65142, + 65276, + 65313, + 65338, + 65345, + 65370, + 65382, + 65470, + 65474, + 65479, + 65482, + 65487, + 65490, + 65495, + 65498, + 65500, + + ]; + var unicodeES3IdCont = [ + 768, + 846, + 864, + 866, + 1155, + 1158, + 1425, + 1441, + 1443, + 1465, + 1467, + 1469, + 1471, + 1471, + 1473, + 1474, + 1476, + 1476, + 1611, + 1621, + 1632, + 1641, + 1648, + 1648, + 1750, + 1756, + 1759, + 1764, + 1767, + 1768, + 1770, + 1773, + 1776, + 1785, + 1809, + 1809, + 1840, + 1866, + 1958, + 1968, + 2305, + 2307, + 2364, + 2364, + 2366, + 2381, + 2385, + 2388, + 2402, + 2403, + 2406, + 2415, + 2433, + 2435, + 2492, + 2492, + 2494, + 2500, + 2503, + 2504, + 2507, + 2509, + 2519, + 2519, + 2530, + 2531, + 2534, + 2543, + 2562, + 2562, + 2620, + 2620, + 2622, + 2626, + 2631, + 2632, + 2635, + 2637, + 2662, + 2673, + 2689, + 2691, + 2748, + 2748, + 2750, + 2757, + 2759, + 2761, + 2763, + 2765, + 2790, + 2799, + 2817, + 2819, + 2876, + 2876, + 2878, + 2883, + 2887, + 2888, + 2891, + 2893, + 2902, + 2903, + 2918, + 2927, + 2946, + 2947, + 3006, + 3010, + 3014, + 3016, + 3018, + 3021, + 3031, + 3031, + 3047, + 3055, + 3073, + 3075, + 3134, + 3140, + 3142, + 3144, + 3146, + 3149, + 3157, + 3158, + 3174, + 3183, + 3202, + 3203, + 3262, + 3268, + 3270, + 3272, + 3274, + 3277, + 3285, + 3286, + 3302, + 3311, + 3330, + 3331, + 3390, + 3395, + 3398, + 3400, + 3402, + 3405, + 3415, + 3415, + 3430, + 3439, + 3458, + 3459, + 3530, + 3530, + 3535, + 3540, + 3542, + 3542, + 3544, + 3551, + 3570, + 3571, + 3633, + 3633, + 3636, + 3642, + 3655, + 3662, + 3664, + 3673, + 3761, + 3761, + 3764, + 3769, + 3771, + 3772, + 3784, + 3789, + 3792, + 3801, + 3864, + 3865, + 3872, + 3881, + 3893, + 3893, + 3895, + 3895, + 3897, + 3897, + 3902, + 3903, + 3953, + 3972, + 3974, + 3975, + 3984, + 3991, + 3993, + 4028, + 4038, + 4038, + 4140, + 4146, + 4150, + 4153, + 4160, + 4169, + 4182, + 4185, + 4969, + 4977, + 6068, + 6099, + 6112, + 6121, + 6160, + 6169, + 6313, + 6313, + 8255, + 8256, + 8400, + 8412, + 8417, + 8417, + 12330, + 12335, + 12441, + 12442, + 12539, + 12539, + 64286, + 64286, + 65056, + 65059, + 65075, + 65076, + 65101, + 65103, + 65296, + 65305, + 65343, + 65343, + 65381, + 65381, + + ]; + var unicodeES5IdStart = [ + 170, + 170, + 181, + 181, + 186, + 186, + 192, + 214, + 216, + 246, + 248, + 705, + 710, + 721, + 736, + 740, + 748, + 748, + 750, + 750, + 880, + 884, + 886, + 887, + 890, + 893, + 902, + 902, + 904, + 906, + 908, + 908, + 910, + 929, + 931, + 1013, + 1015, + 1153, + 1162, + 1319, + 1329, + 1366, + 1369, + 1369, + 1377, + 1415, + 1488, + 1514, + 1520, + 1522, + 1568, + 1610, + 1646, + 1647, + 1649, + 1747, + 1749, + 1749, + 1765, + 1766, + 1774, + 1775, + 1786, + 1788, + 1791, + 1791, + 1808, + 1808, + 1810, + 1839, + 1869, + 1957, + 1969, + 1969, + 1994, + 2026, + 2036, + 2037, + 2042, + 2042, + 2048, + 2069, + 2074, + 2074, + 2084, + 2084, + 2088, + 2088, + 2112, + 2136, + 2208, + 2208, + 2210, + 2220, + 2308, + 2361, + 2365, + 2365, + 2384, + 2384, + 2392, + 2401, + 2417, + 2423, + 2425, + 2431, + 2437, + 2444, + 2447, + 2448, + 2451, + 2472, + 2474, + 2480, + 2482, + 2482, + 2486, + 2489, + 2493, + 2493, + 2510, + 2510, + 2524, + 2525, + 2527, + 2529, + 2544, + 2545, + 2565, + 2570, + 2575, + 2576, + 2579, + 2600, + 2602, + 2608, + 2610, + 2611, + 2613, + 2614, + 2616, + 2617, + 2649, + 2652, + 2654, + 2654, + 2674, + 2676, + 2693, + 2701, + 2703, + 2705, + 2707, + 2728, + 2730, + 2736, + 2738, + 2739, + 2741, + 2745, + 2749, + 2749, + 2768, + 2768, + 2784, + 2785, + 2821, + 2828, + 2831, + 2832, + 2835, + 2856, + 2858, + 2864, + 2866, + 2867, + 2869, + 2873, + 2877, + 2877, + 2908, + 2909, + 2911, + 2913, + 2929, + 2929, + 2947, + 2947, + 2949, + 2954, + 2958, + 2960, + 2962, + 2965, + 2969, + 2970, + 2972, + 2972, + 2974, + 2975, + 2979, + 2980, + 2984, + 2986, + 2990, + 3001, + 3024, + 3024, + 3077, + 3084, + 3086, + 3088, + 3090, + 3112, + 3114, + 3123, + 3125, + 3129, + 3133, + 3133, + 3160, + 3161, + 3168, + 3169, + 3205, + 3212, + 3214, + 3216, + 3218, + 3240, + 3242, + 3251, + 3253, + 3257, + 3261, + 3261, + 3294, + 3294, + 3296, + 3297, + 3313, + 3314, + 3333, + 3340, + 3342, + 3344, + 3346, + 3386, + 3389, + 3389, + 3406, + 3406, + 3424, + 3425, + 3450, + 3455, + 3461, + 3478, + 3482, + 3505, + 3507, + 3515, + 3517, + 3517, + 3520, + 3526, + 3585, + 3632, + 3634, + 3635, + 3648, + 3654, + 3713, + 3714, + 3716, + 3716, + 3719, + 3720, + 3722, + 3722, + 3725, + 3725, + 3732, + 3735, + 3737, + 3743, + 3745, + 3747, + 3749, + 3749, + 3751, + 3751, + 3754, + 3755, + 3757, + 3760, + 3762, + 3763, + 3773, + 3773, + 3776, + 3780, + 3782, + 3782, + 3804, + 3807, + 3840, + 3840, + 3904, + 3911, + 3913, + 3948, + 3976, + 3980, + 4096, + 4138, + 4159, + 4159, + 4176, + 4181, + 4186, + 4189, + 4193, + 4193, + 4197, + 4198, + 4206, + 4208, + 4213, + 4225, + 4238, + 4238, + 4256, + 4293, + 4295, + 4295, + 4301, + 4301, + 4304, + 4346, + 4348, + 4680, + 4682, + 4685, + 4688, + 4694, + 4696, + 4696, + 4698, + 4701, + 4704, + 4744, + 4746, + 4749, + 4752, + 4784, + 4786, + 4789, + 4792, + 4798, + 4800, + 4800, + 4802, + 4805, + 4808, + 4822, + 4824, + 4880, + 4882, + 4885, + 4888, + 4954, + 4992, + 5007, + 5024, + 5108, + 5121, + 5740, + 5743, + 5759, + 5761, + 5786, + 5792, + 5866, + 5870, + 5872, + 5888, + 5900, + 5902, + 5905, + 5920, + 5937, + 5952, + 5969, + 5984, + 5996, + 5998, + 6000, + 6016, + 6067, + 6103, + 6103, + 6108, + 6108, + 6176, + 6263, + 6272, + 6312, + 6314, + 6314, + 6320, + 6389, + 6400, + 6428, + 6480, + 6509, + 6512, + 6516, + 6528, + 6571, + 6593, + 6599, + 6656, + 6678, + 6688, + 6740, + 6823, + 6823, + 6917, + 6963, + 6981, + 6987, + 7043, + 7072, + 7086, + 7087, + 7098, + 7141, + 7168, + 7203, + 7245, + 7247, + 7258, + 7293, + 7401, + 7404, + 7406, + 7409, + 7413, + 7414, + 7424, + 7615, + 7680, + 7957, + 7960, + 7965, + 7968, + 8005, + 8008, + 8013, + 8016, + 8023, + 8025, + 8025, + 8027, + 8027, + 8029, + 8029, + 8031, + 8061, + 8064, + 8116, + 8118, + 8124, + 8126, + 8126, + 8130, + 8132, + 8134, + 8140, + 8144, + 8147, + 8150, + 8155, + 8160, + 8172, + 8178, + 8180, + 8182, + 8188, + 8305, + 8305, + 8319, + 8319, + 8336, + 8348, + 8450, + 8450, + 8455, + 8455, + 8458, + 8467, + 8469, + 8469, + 8473, + 8477, + 8484, + 8484, + 8486, + 8486, + 8488, + 8488, + 8490, + 8493, + 8495, + 8505, + 8508, + 8511, + 8517, + 8521, + 8526, + 8526, + 8544, + 8584, + 11264, + 11310, + 11312, + 11358, + 11360, + 11492, + 11499, + 11502, + 11506, + 11507, + 11520, + 11557, + 11559, + 11559, + 11565, + 11565, + 11568, + 11623, + 11631, + 11631, + 11648, + 11670, + 11680, + 11686, + 11688, + 11694, + 11696, + 11702, + 11704, + 11710, + 11712, + 11718, + 11720, + 11726, + 11728, + 11734, + 11736, + 11742, + 11823, + 11823, + 12293, + 12295, + 12321, + 12329, + 12337, + 12341, + 12344, + 12348, + 12353, + 12438, + 12445, + 12447, + 12449, + 12538, + 12540, + 12543, + 12549, + 12589, + 12593, + 12686, + 12704, + 12730, + 12784, + 12799, + 13312, + 19893, + 19968, + 40908, + 40960, + 42124, + 42192, + 42237, + 42240, + 42508, + 42512, + 42527, + 42538, + 42539, + 42560, + 42606, + 42623, + 42647, + 42656, + 42735, + 42775, + 42783, + 42786, + 42888, + 42891, + 42894, + 42896, + 42899, + 42912, + 42922, + 43000, + 43009, + 43011, + 43013, + 43015, + 43018, + 43020, + 43042, + 43072, + 43123, + 43138, + 43187, + 43250, + 43255, + 43259, + 43259, + 43274, + 43301, + 43312, + 43334, + 43360, + 43388, + 43396, + 43442, + 43471, + 43471, + 43520, + 43560, + 43584, + 43586, + 43588, + 43595, + 43616, + 43638, + 43642, + 43642, + 43648, + 43695, + 43697, + 43697, + 43701, + 43702, + 43705, + 43709, + 43712, + 43712, + 43714, + 43714, + 43739, + 43741, + 43744, + 43754, + 43762, + 43764, + 43777, + 43782, + 43785, + 43790, + 43793, + 43798, + 43808, + 43814, + 43816, + 43822, + 43968, + 44002, + 44032, + 55203, + 55216, + 55238, + 55243, + 55291, + 63744, + 64109, + 64112, + 64217, + 64256, + 64262, + 64275, + 64279, + 64285, + 64285, + 64287, + 64296, + 64298, + 64310, + 64312, + 64316, + 64318, + 64318, + 64320, + 64321, + 64323, + 64324, + 64326, + 64433, + 64467, + 64829, + 64848, + 64911, + 64914, + 64967, + 65008, + 65019, + 65136, + 65140, + 65142, + 65276, + 65313, + 65338, + 65345, + 65370, + 65382, + 65470, + 65474, + 65479, + 65482, + 65487, + 65490, + 65495, + 65498, + 65500, + + ]; + var unicodeES5IdCont = [ + 768, + 879, + 1155, + 1159, + 1425, + 1469, + 1471, + 1471, + 1473, + 1474, + 1476, + 1477, + 1479, + 1479, + 1552, + 1562, + 1611, + 1641, + 1648, + 1648, + 1750, + 1756, + 1759, + 1764, + 1767, + 1768, + 1770, + 1773, + 1776, + 1785, + 1809, + 1809, + 1840, + 1866, + 1958, + 1968, + 1984, + 1993, + 2027, + 2035, + 2070, + 2073, + 2075, + 2083, + 2085, + 2087, + 2089, + 2093, + 2137, + 2139, + 2276, + 2302, + 2304, + 2307, + 2362, + 2364, + 2366, + 2383, + 2385, + 2391, + 2402, + 2403, + 2406, + 2415, + 2433, + 2435, + 2492, + 2492, + 2494, + 2500, + 2503, + 2504, + 2507, + 2509, + 2519, + 2519, + 2530, + 2531, + 2534, + 2543, + 2561, + 2563, + 2620, + 2620, + 2622, + 2626, + 2631, + 2632, + 2635, + 2637, + 2641, + 2641, + 2662, + 2673, + 2677, + 2677, + 2689, + 2691, + 2748, + 2748, + 2750, + 2757, + 2759, + 2761, + 2763, + 2765, + 2786, + 2787, + 2790, + 2799, + 2817, + 2819, + 2876, + 2876, + 2878, + 2884, + 2887, + 2888, + 2891, + 2893, + 2902, + 2903, + 2914, + 2915, + 2918, + 2927, + 2946, + 2946, + 3006, + 3010, + 3014, + 3016, + 3018, + 3021, + 3031, + 3031, + 3046, + 3055, + 3073, + 3075, + 3134, + 3140, + 3142, + 3144, + 3146, + 3149, + 3157, + 3158, + 3170, + 3171, + 3174, + 3183, + 3202, + 3203, + 3260, + 3260, + 3262, + 3268, + 3270, + 3272, + 3274, + 3277, + 3285, + 3286, + 3298, + 3299, + 3302, + 3311, + 3330, + 3331, + 3390, + 3396, + 3398, + 3400, + 3402, + 3405, + 3415, + 3415, + 3426, + 3427, + 3430, + 3439, + 3458, + 3459, + 3530, + 3530, + 3535, + 3540, + 3542, + 3542, + 3544, + 3551, + 3570, + 3571, + 3633, + 3633, + 3636, + 3642, + 3655, + 3662, + 3664, + 3673, + 3761, + 3761, + 3764, + 3769, + 3771, + 3772, + 3784, + 3789, + 3792, + 3801, + 3864, + 3865, + 3872, + 3881, + 3893, + 3893, + 3895, + 3895, + 3897, + 3897, + 3902, + 3903, + 3953, + 3972, + 3974, + 3975, + 3981, + 3991, + 3993, + 4028, + 4038, + 4038, + 4139, + 4158, + 4160, + 4169, + 4182, + 4185, + 4190, + 4192, + 4194, + 4196, + 4199, + 4205, + 4209, + 4212, + 4226, + 4237, + 4239, + 4253, + 4957, + 4959, + 5906, + 5908, + 5938, + 5940, + 5970, + 5971, + 6002, + 6003, + 6068, + 6099, + 6109, + 6109, + 6112, + 6121, + 6155, + 6157, + 6160, + 6169, + 6313, + 6313, + 6432, + 6443, + 6448, + 6459, + 6470, + 6479, + 6576, + 6592, + 6600, + 6601, + 6608, + 6617, + 6679, + 6683, + 6741, + 6750, + 6752, + 6780, + 6783, + 6793, + 6800, + 6809, + 6912, + 6916, + 6964, + 6980, + 6992, + 7001, + 7019, + 7027, + 7040, + 7042, + 7073, + 7085, + 7088, + 7097, + 7142, + 7155, + 7204, + 7223, + 7232, + 7241, + 7248, + 7257, + 7376, + 7378, + 7380, + 7400, + 7405, + 7405, + 7410, + 7412, + 7616, + 7654, + 7676, + 7679, + 8204, + 8205, + 8255, + 8256, + 8276, + 8276, + 8400, + 8412, + 8417, + 8417, + 8421, + 8432, + 11503, + 11505, + 11647, + 11647, + 11744, + 11775, + 12330, + 12335, + 12441, + 12442, + 42528, + 42537, + 42607, + 42607, + 42612, + 42621, + 42655, + 42655, + 42736, + 42737, + 43010, + 43010, + 43014, + 43014, + 43019, + 43019, + 43043, + 43047, + 43136, + 43137, + 43188, + 43204, + 43216, + 43225, + 43232, + 43249, + 43264, + 43273, + 43302, + 43309, + 43335, + 43347, + 43392, + 43395, + 43443, + 43456, + 43472, + 43481, + 43561, + 43574, + 43587, + 43587, + 43596, + 43597, + 43600, + 43609, + 43643, + 43643, + 43696, + 43696, + 43698, + 43700, + 43703, + 43704, + 43710, + 43711, + 43713, + 43713, + 43755, + 43759, + 43765, + 43766, + 44003, + 44010, + 44012, + 44013, + 44016, + 44025, + 64286, + 64286, + 65024, + 65039, + 65056, + 65062, + 65075, + 65076, + 65101, + 65103, + 65296, + 65305, + 65343, + 65343, + + ]; + function LexLookUpUnicodeMap(code, map) { + var lo = 0; + var hi = map.length; + var mid; + while(lo + 1 < hi) { + mid = lo + (hi - lo) / 2; + mid -= mid % 2; + if(map[mid] <= code && code <= map[mid + 1]) { + return true; + } + if(code < map[mid]) { + hi = mid; + } else { + lo = mid + 2; + } + } + return false; + } + TypeScript.LexLookUpUnicodeMap = LexLookUpUnicodeMap; + function LexIsUnicodeDigit(code) { + if(TypeScript.codeGenTarget == TypeScript.CodeGenTarget.ES3) { + return LexLookUpUnicodeMap(code, unicodeES3IdCont); + } else { + return LexLookUpUnicodeMap(code, unicodeES5IdCont); + } + } + TypeScript.LexIsUnicodeDigit = LexIsUnicodeDigit; + function LexIsUnicodeIdStart(code) { + if(TypeScript.codeGenTarget == TypeScript.CodeGenTarget.ES3) { + return LexLookUpUnicodeMap(code, unicodeES3IdStart); + } else { + return LexLookUpUnicodeMap(code, unicodeES5IdStart); + } + } + TypeScript.LexIsUnicodeIdStart = LexIsUnicodeIdStart; + function LexInitialize() { + TypeScript.initializeStaticTokens(); + autoToken[TypeScript.LexCodeLPR] = TypeScript.staticTokens[TypeScript.TokenID.OpenParen]; + autoToken[TypeScript.LexCodeRPR] = TypeScript.staticTokens[TypeScript.TokenID.CloseParen]; + autoToken[TypeScript.LexCodeCMA] = TypeScript.staticTokens[TypeScript.TokenID.Comma]; + autoToken[TypeScript.LexCodeSMC] = TypeScript.staticTokens[TypeScript.TokenID.Semicolon]; + autoToken[TypeScript.LexCodeLBR] = TypeScript.staticTokens[TypeScript.TokenID.OpenBracket]; + autoToken[TypeScript.LexCodeRBR] = TypeScript.staticTokens[TypeScript.TokenID.CloseBracket]; + autoToken[TypeScript.LexCodeTIL] = TypeScript.staticTokens[TypeScript.TokenID.Tilde]; + autoToken[TypeScript.LexCodeQUE] = TypeScript.staticTokens[TypeScript.TokenID.Question]; + autoToken[TypeScript.LexCodeLC] = TypeScript.staticTokens[TypeScript.TokenID.OpenBrace]; + autoToken[TypeScript.LexCodeRC] = TypeScript.staticTokens[TypeScript.TokenID.CloseBrace]; + autoToken[TypeScript.LexCodeCOL] = TypeScript.staticTokens[TypeScript.TokenID.Colon]; + TypeScript.LexKeywordTable = new TypeScript.StringHashTable(); + for(var i in (TypeScript.TokenID)._map) { + if((i) <= TypeScript.TokenID.LimKeyword) { + TypeScript.LexKeywordTable.add((TypeScript.TokenID)._map[i].toLowerCase(), i); + } + } + for(var j = 0; j < TypeScript.LexCodeASCIIChars; j++) { + if(LexIsIdentifierStartChar(j)) { + lexIdStartTable[j] = true; + } else { + lexIdStartTable[j] = false; + } + } + } + TypeScript.LexInitialize = LexInitialize; + function LexAdjustIndent(code, indentAmt) { + if((code == TypeScript.LexCodeLBR) || (code == TypeScript.LexCodeLC) || (code == TypeScript.LexCodeLPR)) { + return indentAmt + 1; + } else if((code == TypeScript.LexCodeRBR) || (code == TypeScript.LexCodeRC) || (code == TypeScript.LexCodeRPR)) { + return indentAmt - 1; + } else { + return indentAmt; + } + } + TypeScript.LexAdjustIndent = LexAdjustIndent; + function LexIsIdentifierStartChar(code) { + return (((code >= 97) && (code <= 122)) || ((code >= 65) && (code <= 90)) || (code == TypeScript.LexCodeDollar) || (code == TypeScript.LexCodeUnderscore)); + } + TypeScript.LexIsIdentifierStartChar = LexIsIdentifierStartChar; + function LexIsDigit(code) { + return ((code >= 48) && (code <= 57)); + } + TypeScript.LexIsDigit = LexIsDigit; + function LexIsIdentifierChar(code) { + return lexIdStartTable[code] || LexIsDigit(code); + } + TypeScript.LexIsIdentifierChar = LexIsIdentifierChar; + function LexMatchingOpen(code) { + if(code == TypeScript.LexCodeRBR) { + return TypeScript.LexCodeLBR; + } else if(code == TypeScript.LexCodeRC) { + return TypeScript.LexCodeLC; + } else if(code == TypeScript.LexCodeRPR) { + return TypeScript.LexCodeLPR; + } else { + return 0; + } + } + TypeScript.LexMatchingOpen = LexMatchingOpen; + (function (NumberScanState) { + NumberScanState._map = []; + NumberScanState._map[0] = "Start"; + NumberScanState.Start = 0; + NumberScanState._map[1] = "InFraction"; + NumberScanState.InFraction = 1; + NumberScanState._map[2] = "InEmptyFraction"; + NumberScanState.InEmptyFraction = 2; + NumberScanState._map[3] = "InExponent"; + NumberScanState.InExponent = 3; + })(TypeScript.NumberScanState || (TypeScript.NumberScanState = {})); + var NumberScanState = TypeScript.NumberScanState; + (function (LexState) { + LexState._map = []; + LexState._map[0] = "Start"; + LexState.Start = 0; + LexState._map[1] = "InMultilineComment"; + LexState.InMultilineComment = 1; + LexState._map[2] = "InMultilineSingleQuoteString"; + LexState.InMultilineSingleQuoteString = 2; + LexState._map[3] = "InMultilineDoubleQuoteString"; + LexState.InMultilineDoubleQuoteString = 3; + })(TypeScript.LexState || (TypeScript.LexState = {})); + var LexState = TypeScript.LexState; + (function (LexMode) { + LexMode._map = []; + LexMode._map[0] = "Line"; + LexMode.Line = 0; + LexMode._map[1] = "File"; + LexMode.File = 1; + })(TypeScript.LexMode || (TypeScript.LexMode = {})); + var LexMode = TypeScript.LexMode; + (function (CommentStyle) { + CommentStyle._map = []; + CommentStyle._map[0] = "Line"; + CommentStyle.Line = 0; + CommentStyle._map[1] = "Block"; + CommentStyle.Block = 1; + })(TypeScript.CommentStyle || (TypeScript.CommentStyle = {})); + var CommentStyle = TypeScript.CommentStyle; + var StringSourceText = (function () { + function StringSourceText(text) { + this.text = text; + } + StringSourceText.prototype.getText = function (start, end) { + return this.text.substring(start, end); + }; + StringSourceText.prototype.getLength = function () { + return this.text.length; + }; + return StringSourceText; + })(); + TypeScript.StringSourceText = StringSourceText; + var SourceTextSegment = (function () { + function SourceTextSegment(segmentStart, segmentEnd, segment) { + this.segmentStart = segmentStart; + this.segmentEnd = segmentEnd; + this.segment = segment; + } + SourceTextSegment.prototype.charCodeAt = function (index) { + return this.segment.charCodeAt(index - this.segmentStart); + }; + SourceTextSegment.prototype.substring = function (start, end) { + return this.segment.substring(start - this.segmentStart, end - this.segmentStart); + }; + return SourceTextSegment; + })(); + TypeScript.SourceTextSegment = SourceTextSegment; + var AggerateSourceTextSegment = (function () { + function AggerateSourceTextSegment(seg1, seg2) { + this.seg1 = seg1; + this.seg2 = seg2; + } + AggerateSourceTextSegment.prototype.charCodeAt = function (index) { + if(this.seg1.segmentStart <= index && index < this.seg1.segmentEnd) { + return this.seg1.segment.charCodeAt(index - this.seg1.segmentStart); + } + return this.seg2.segment.charCodeAt(index - this.seg2.segmentStart); + }; + AggerateSourceTextSegment.prototype.substring = function (start, end) { + if(this.seg1.segmentStart <= start && end <= this.seg1.segmentEnd) { + return this.seg1.segment.substring(start - this.seg1.segmentStart, end - this.seg1.segmentStart); + } + return this.seg2.segment.substring(start - this.seg2.segmentStart) + this.seg1.segment.substring(0, end - this.seg1.segmentStart); + }; + return AggerateSourceTextSegment; + })(); + TypeScript.AggerateSourceTextSegment = AggerateSourceTextSegment; + var ScannerTextStream = (function () { + function ScannerTextStream(sourceText) { + this.sourceText = sourceText; + this.agg = new AggerateSourceTextSegment(ScannerTextStream.emptySegment, ScannerTextStream.emptySegment); + this.len = this.sourceText.getLength(); + } + ScannerTextStream.emptySegment = new SourceTextSegment(0, 0, ""); + ScannerTextStream.prototype.max = function (a, b) { + return a >= b ? a : b; + }; + ScannerTextStream.prototype.min = function (a, b) { + return a <= b ? a : b; + }; + ScannerTextStream.prototype.fetchSegment = function (start, end) { + if(this.agg.seg1.segmentStart <= start && end <= this.agg.seg1.segmentEnd) { + return this.agg.seg1; + } + if(this.agg.seg2.segmentStart <= start && end <= this.agg.seg1.segmentEnd) { + return this.agg; + } + var prev = this.agg.seg1; + var s = prev.segmentEnd; + var e = TypeScript.max(s + 512, end); + e = TypeScript.min(e, this.len); + var src = this.sourceText.getText(s, e); + var newSeg = new SourceTextSegment(s, e, src); + this.agg.seg2 = prev; + this.agg.seg1 = newSeg; + return this.agg; + }; + ScannerTextStream.prototype.charCodeAt = function (index) { + return this.fetchSegment(index, index + 1).charCodeAt(index); + }; + ScannerTextStream.prototype.substring = function (start, end) { + return this.fetchSegment(start, end).substring(start, end); + }; + return ScannerTextStream; + })(); + TypeScript.ScannerTextStream = ScannerTextStream; + var SavedTokens = (function () { + function SavedTokens() { + this.prevToken = null; + this.curSavedToken = null; + this.prevSavedToken = null; + this.prevToken = null; + this.currentToken = 0; + this.tokens = new Array(); + this.seenUnicodeChar = false; + this.seenUnicodeCharInComment = false; + this.prevLine = 1; + this.line = 1; + this.col = 0; + this.lexState = LexState.Start; + this.commentStack = new Array(); + this.lineMap = []; + } + SavedTokens.prototype.previousToken = function () { + return this.prevToken; + }; + SavedTokens.prototype.addToken = function (tok, scanner) { + this.tokens[this.currentToken++] = new TypeScript.SavedToken(tok, scanner.startPos, scanner.pos); + }; + SavedTokens.prototype.scan = function () { + this.startLine = this.line; + this.startPos = this.col; + if(this.currentTokenIndex == this.currentTokens.length) { + if(this.line < this.lineMap.length) { + this.line++; + this.col = 0; + this.currentTokenIndex = 0; + this.currentTokens = this.tokensByLine[this.line]; + } else { + return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; + } + } + if(this.currentTokenIndex < this.currentTokens.length) { + this.prevToken = this.curSavedToken.tok; + this.prevSavedToken = this.curSavedToken; + this.curSavedToken = this.currentTokens[this.currentTokenIndex++]; + var curToken = this.curSavedToken.tok; + this.pos = this.curSavedToken.limChar; + this.col += (this.curSavedToken.limChar - this.curSavedToken.minChar); + this.startPos = this.curSavedToken.minChar; + this.prevLine = this.line; + return curToken; + } else { + return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; + } + }; + SavedTokens.prototype.lastTokenLimChar = function () { + if(this.prevSavedToken !== null) { + return this.prevSavedToken.limChar; + } else { + return 0; + } + }; + SavedTokens.prototype.lastTokenHadNewline = function () { + return this.prevLine != this.startLine; + }; + SavedTokens.prototype.getComments = function () { + var stack = this.commentStack; + this.commentStack = []; + return stack; + }; + SavedTokens.prototype.getCommentsForLine = function (line) { + var comments = null; + while((this.commentStack.length > 0) && (this.commentStack[0].line == line)) { + if(comments == null) { + comments = [ + this.commentStack.shift() + ]; + } else { + comments = comments.concat([ + this.commentStack.shift() + ]); + } + } + return comments; + }; + SavedTokens.prototype.resetComments = function () { + this.commentStack = []; + }; + SavedTokens.prototype.setSourceText = function (newSrc, textMode) { + }; + SavedTokens.prototype.setErrorHandler = function (reportError) { + }; + SavedTokens.prototype.getLookAheadToken = function () { + throw new Error("Invalid operation."); + }; + return SavedTokens; + })(); + TypeScript.SavedTokens = SavedTokens; + var Scanner = (function () { + function Scanner() { + this.prevLine = 1; + this.line = 1; + this.col = 0; + this.pos = 0; + this.startPos = 0; + this.len = 0; + this.lineMap = []; + this.ch = TypeScript.LexEOF; + this.lexState = LexState.Start; + this.mode = LexMode.File; + this.scanComments = true; + this.interveningWhitespace = false; + this.interveningWhitespacePos = 0; + this.leftCurlyCount = 0; + this.rightCurlyCount = 0; + this.commentStack = new Array(); + this.saveScan = null; + this.seenUnicodeChar = false; + this.seenUnicodeCharInComment = false; + this.prevTok = TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; + this.startCol = this.col; + this.startLine = this.line; + this.lineMap[1] = 0; + if(!TypeScript.LexKeywordTable) { + LexInitialize(); + } + } + Scanner.prototype.previousToken = function () { + return this.prevTok; + }; + Scanner.prototype.setSourceText = function (newSrc, textMode) { + this.mode = textMode; + this.scanComments = (this.mode === LexMode.Line); + this.pos = 0; + this.interveningWhitespacePos = 0; + this.startPos = 0; + this.line = 1; + this.col = 0; + this.startCol = this.col; + this.startLine = this.line; + this.len = 0; + this.src = newSrc.getText(0, newSrc.getLength()); + this.len = this.src.length; + this.lineMap = []; + this.lineMap[1] = 0; + this.commentStack = []; + this.leftCurlyCount = 0; + this.rightCurlyCount = 0; + this.seenUnicodeChar = false; + this.seenUnicodeCharInComment = false; + }; + Scanner.prototype.setErrorHandler = function (reportError) { + this.reportError = reportError; + }; + Scanner.prototype.setText = function (newSrc, textMode) { + this.setSourceText(new StringSourceText(newSrc), textMode); + }; + Scanner.prototype.setScanComments = function (value) { + this.scanComments = value; + }; + Scanner.prototype.tokenStart = function () { + this.startPos = this.pos; + this.startLine = this.line; + this.startCol = this.col; + this.interveningWhitespace = false; + }; + Scanner.prototype.peekChar = function () { + if(this.pos < this.len) { + return this.src.charCodeAt(this.pos); + } else { + return TypeScript.LexEOF; + } + }; + Scanner.prototype.peekCharAt = function (index) { + if(index < this.len) { + return this.src.charCodeAt(index); + } else { + return TypeScript.LexEOF; + } + }; + Scanner.prototype.IsHexDigit = function (c) { + return ((c >= TypeScript.LexCode_0) && (c <= TypeScript.LexCode_9)) || ((c >= TypeScript.LexCode_A) && (c <= TypeScript.LexCode_F)) || ((c >= TypeScript.LexCode_a) && (c <= TypeScript.LexCode_f)); + }; + Scanner.prototype.IsOctalDigit = function (c) { + return ((c >= TypeScript.LexCode_0) && (c <= TypeScript.LexCode_7)) || ((c >= TypeScript.LexCode_a) && (c <= TypeScript.LexCode_f)); + }; + Scanner.prototype.scanHexDigits = function () { + var atLeastOneDigit = false; + for(; ; ) { + if(this.IsHexDigit(this.ch)) { + this.nextChar(); + atLeastOneDigit = true; + } else { + if(atLeastOneDigit) { + var text = this.src.substring(this.startPos, this.pos); + return new TypeScript.NumberLiteralToken(parseInt(text), text); + } else { + return null; + } + } + } + }; + Scanner.prototype.scanOctalDigits = function () { + var atLeastOneDigit = false; + for(; ; ) { + if(this.IsOctalDigit(this.ch)) { + this.nextChar(); + atLeastOneDigit = true; + } else { + if(atLeastOneDigit) { + var text = this.src.substring(this.startPos, this.pos); + return new TypeScript.NumberLiteralToken(parseInt(text), text); + } else { + return null; + } + } + } + }; + Scanner.prototype.scanDecimalNumber = function (state) { + var atLeastOneDigit = false; + var svPos = this.pos; + var svCol = this.col; + for(; ; ) { + if(LexIsDigit(this.ch)) { + atLeastOneDigit = true; + if(this.ch != TypeScript.LexCode_0 && state == NumberScanState.InEmptyFraction) { + state = NumberScanState.InFraction; + } + this.nextChar(); + } else if(this.ch == TypeScript.LexCodeDOT) { + if(state == NumberScanState.Start) { + this.nextChar(); + state = NumberScanState.InEmptyFraction; + } else { + if(atLeastOneDigit) { + var text = this.src.substring(this.startPos, this.pos); + return new TypeScript.NumberLiteralToken(parseFloat(text), text); + } else { + this.pos = svPos; + this.col = svCol; + return null; + } + } + } else if((this.ch == TypeScript.LexCode_e) || (this.ch == TypeScript.LexCode_E)) { + if(state == NumberScanState.Start) { + if(atLeastOneDigit) { + atLeastOneDigit = false; + this.nextChar(); + state = NumberScanState.InExponent; + } else { + this.pos = svPos; + this.col = svCol; + return null; + } + } else if(state == NumberScanState.InFraction || state == NumberScanState.InEmptyFraction) { + this.nextChar(); + state = NumberScanState.InExponent; + atLeastOneDigit = false; + } else { + if(atLeastOneDigit) { + var text = this.src.substring(this.startPos, this.pos); + return new TypeScript.NumberLiteralToken(parseFloat(text), text); + } else { + this.pos = svPos; + this.col = svCol; + return null; + } + } + } else if((this.ch == TypeScript.LexCodePLS) || (this.ch == TypeScript.LexCodeMIN)) { + if(state == NumberScanState.InExponent) { + if(!atLeastOneDigit) { + this.nextChar(); + } else { + this.pos = svPos; + this.col = svCol; + return null; + } + } else if(state == NumberScanState.InEmptyFraction || state == NumberScanState.InFraction) { + var text = this.src.substring(this.startPos, this.pos); + return new TypeScript.NumberLiteralToken(parseFloat(text), text); + } else { + if(!atLeastOneDigit) { + this.pos = svPos; + this.col = svCol; + return null; + } else { + var text = this.src.substring(this.startPos, this.pos); + return new TypeScript.NumberLiteralToken(parseFloat(text), text); + } + } + } else { + if(!atLeastOneDigit) { + this.pos = svPos; + this.col = svCol; + return null; + } else { + var text = this.src.substring(this.startPos, this.pos); + return new TypeScript.NumberLiteralToken(parseFloat(text), text); + } + } + } + }; + Scanner.prototype.scanNumber = function () { + if(this.peekChar() == TypeScript.LexCode_0) { + switch(this.peekCharAt(this.pos + 1)) { + case TypeScript.LexCode_x: + case TypeScript.LexCode_X: + this.advanceChar(2); + return this.scanHexDigits(); + case TypeScript.LexCode_8: + case TypeScript.LexCode_9: + case TypeScript.LexCodeDOT: + return this.scanDecimalNumber(NumberScanState.Start); + default: + return this.scanOctalDigits(); + } + } else { + return this.scanDecimalNumber(NumberScanState.Start); + } + }; + Scanner.prototype.scanFraction = function () { + return this.scanDecimalNumber(NumberScanState.InFraction); + }; + Scanner.prototype.newLine = function () { + this.col = 0; + if(this.mode == LexMode.File) { + this.line++; + this.lineMap[this.line] = this.pos + 1; + } + }; + Scanner.prototype.finishMultilineComment = function () { + var ch2; + this.lexState = LexState.InMultilineComment; + while(this.pos < this.len) { + if(this.ch == TypeScript.LexCodeMUL) { + ch2 = this.peekCharAt(this.pos + 1); + if(ch2 == TypeScript.LexCodeSLH) { + this.advanceChar(2); + if(this.mode == LexMode.File) { + this.tokenStart(); + } + this.lexState = LexState.Start; + return true; + } + } else if(this.ch == TypeScript.LexCodeNWL) { + this.newLine(); + if(this.mode == LexMode.Line) { + this.nextChar(); + return false; + } + } else if(this.ch >= TypeScript.LexCodeASCIIChars) { + this.seenUnicodeCharInComment = true; + } + this.nextChar(); + } + return false; + }; + Scanner.prototype.pushComment = function (comment) { + this.commentStack.push(comment); + }; + Scanner.prototype.getComments = function () { + var stack = this.commentStack; + this.commentStack = []; + return stack; + }; + Scanner.prototype.getCommentsForLine = function (line) { + var comments = null; + while((this.commentStack.length > 0) && (this.commentStack[0].line == line)) { + if(comments == null) { + comments = [ + this.commentStack.shift() + ]; + } else { + comments = comments.concat([ + this.commentStack.shift() + ]); + } + } + return comments; + }; + Scanner.prototype.resetComments = function () { + this.commentStack = []; + }; + Scanner.prototype.endsLine = function (c) { + return (c == TypeScript.LexCodeNWL) || (c == TypeScript.LexCodeRET) || (c == TypeScript.LexCodeLS) || (c == TypeScript.LexCodePS); + }; + Scanner.prototype.finishSinglelineComment = function () { + while(this.pos < this.len) { + if(this.endsLine(this.ch)) { + break; + } + if(this.ch >= TypeScript.LexCodeASCIIChars) { + this.seenUnicodeCharInComment = true; + } + this.nextChar(); + } + if(this.mode == LexMode.File) { + this.tokenStart(); + } + }; + Scanner.prototype.findClosingSLH = function () { + var index = this.pos; + var ch2 = this.src.charCodeAt(index); + var prevCh = 0; + var liveEsc = false; + while(!this.endsLine(ch2) && (index < this.len)) { + if((ch2 == TypeScript.LexCodeSLH) && (!liveEsc)) { + return index; + } + prevCh = ch2; + index++; + if(liveEsc) { + liveEsc = false; + } else { + liveEsc = (prevCh == TypeScript.LexCodeBSL); + } + ch2 = this.src.charCodeAt(index); + } + return -1; + }; + Scanner.prototype.speculateRegex = function () { + if(TypeScript.noRegexTable[this.prevTok.tokenId] != undefined) { + return null; + } + var svPos = this.pos; + var svCol = this.col; + var index = this.findClosingSLH(); + if(index > 0) { + var pattern = this.src.substring(svPos, index); + var flags = ""; + this.pos = index + 1; + this.ch = this.peekChar(); + var flagsStart = this.pos; + while((this.ch == TypeScript.LexCode_i) || (this.ch == TypeScript.LexCode_g) || (this.ch == TypeScript.LexCode_m)) { + this.nextChar(); + } + if((this.pos - flagsStart) > 3) { + return null; + } else { + flags = this.src.substring(flagsStart, this.pos); + } + var regex = undefined; + try { + regex = new RegExp(pattern, flags); + } catch (regexException) { + } + if(regex) { + this.col = svCol + (this.pos - this.startPos); + return new TypeScript.RegularExpressionLiteralToken(this.src.substring(svPos - 1, this.pos)); + } + } + this.pos = svPos; + this.col = svCol; + return null; + }; + Scanner.prototype.lastTokenHadNewline = function () { + return this.prevLine != this.startLine; + }; + Scanner.prototype.lastTokenLimChar = function () { + return this.interveningWhitespace ? this.interveningWhitespacePos : this.startPos; + }; + Scanner.prototype.advanceChar = function (amt) { + this.pos += amt; + this.col += amt; + this.ch = this.peekChar(); + }; + Scanner.prototype.nextChar = function () { + this.pos++; + this.col++; + this.ch = this.peekChar(); + }; + Scanner.prototype.getLookAheadToken = function () { + var prevLine = this.prevLine; + var line = this.line; + var col = this.col; + var pos = this.pos; + var startPos = this.startPos; + var startCol = this.startCol; + var startLine = this.startLine; + var ch = this.ch; + var prevTok = this.prevTok; + var lexState = this.lexState; + var interveningWhitespace = this.interveningWhitespace; + var interveningWhitespacePos = this.interveningWhitespacePos; + var leftCurlyCount = this.leftCurlyCount; + var rightCurlyCount = this.rightCurlyCount; + var seenUnicodeChar = this.seenUnicodeChar; + var seenUnicodeCharInComment = this.seenUnicodeCharInComment; + var commentStackLength = this.commentStack.length; + var lookAheadToken = this.scan(); + this.prevLine = prevLine; + this.line = line; + this.col = col; + this.pos = pos; + this.startPos = startPos; + this.startCol = startCol; + this.startLine = startLine; + this.ch = ch; + this.prevTok = prevTok; + this.lexState = lexState; + this.interveningWhitespace = interveningWhitespace; + this.interveningWhitespacePos = interveningWhitespacePos; + this.leftCurlyCount = leftCurlyCount; + this.rightCurlyCount = rightCurlyCount; + this.seenUnicodeChar = seenUnicodeChar; + this.seenUnicodeCharInComment = seenUnicodeCharInComment; + this.commentStack.length = commentStackLength; + return lookAheadToken; + }; + Scanner.prototype.scanInLine = function () { + if((this.lexState == LexState.InMultilineComment) && (this.scanComments)) { + this.ch = this.peekChar(); + var commentLine = this.line; + this.finishMultilineComment(); + if(this.startPos < this.pos) { + var commentText = this.src.substring(this.startPos, this.pos); + this.tokenStart(); + return new TypeScript.CommentToken(TypeScript.TokenID.Comment, commentText, true, this.startPos, commentLine, true); + } else { + return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; + } + } else if(this.lexState == LexState.InMultilineSingleQuoteString && this.pos < this.len) { + this.ch = this.peekChar(); + this.lexState = LexState.Start; + return this.scanStringConstant(TypeScript.LexCodeAPO); + } else if(this.lexState == LexState.InMultilineDoubleQuoteString && this.pos < this.len) { + this.ch = this.peekChar(); + this.lexState = LexState.Start; + return this.scanStringConstant(TypeScript.LexCodeQUO); + } + this.prevLine = this.line; + var prevTok = this.innerScan(); + if(prevTok.tokenId != TypeScript.TokenID.Whitespace) { + this.prevTok = prevTok; + } + return prevTok; + }; + Scanner.prototype.scan = function () { + this.prevLine = this.line; + this.prevTok = this.innerScan(); + if(this.saveScan) { + this.saveScan.addToken(this.prevTok, this); + } + return this.prevTok; + }; + Scanner.prototype.isValidUnicodeIdentifierChar = function () { + var valid = LexIsUnicodeIdStart(this.ch) || LexIsUnicodeDigit(this.ch); + this.seenUnicodeChar = this.seenUnicodeChar || valid; + return valid; + }; + Scanner.prototype.scanStringConstant = function (endCode) { + scanStringConstantLoop: +for(; ; ) { + switch(this.ch) { + case TypeScript.LexEOF: + this.reportScannerError("Unterminated string constant"); + break scanStringConstantLoop; + case TypeScript.LexCodeLS: + case TypeScript.LexCodePS: + this.seenUnicodeChar = true; + case TypeScript.LexCodeRET: + case TypeScript.LexCodeNWL: + this.reportScannerError("Unterminated string constant"); + break scanStringConstantLoop; + case TypeScript.LexCodeAPO: + case TypeScript.LexCodeQUO: + if(this.ch == endCode) { + this.nextChar(); + break scanStringConstantLoop; + } + break; + case TypeScript.LexCodeBSL: + this.nextChar(); + switch(this.ch) { + case TypeScript.LexCodeAPO: + case TypeScript.LexCodeQUO: + case TypeScript.LexCodeBSL: + this.nextChar(); + continue scanStringConstantLoop; + case TypeScript.LexCodeLS: + case TypeScript.LexCodePS: + this.seenUnicodeChar = true; + case TypeScript.LexCodeRET: + case TypeScript.LexCodeNWL: + if(this.ch == TypeScript.LexCodeRET && this.peekCharAt(this.pos + 1) == TypeScript.LexCodeNWL) { + this.nextChar(); + } + this.newLine(); + if(this.mode == LexMode.Line) { + this.nextChar(); + this.lexState = endCode == TypeScript.LexCodeAPO ? LexState.InMultilineSingleQuoteString : LexState.InMultilineDoubleQuoteString; + break scanStringConstantLoop; + } + break; + case TypeScript.LexCode_x: + case TypeScript.LexCode_u: + var expectedHexDigits = this.ch == TypeScript.LexCode_x ? 2 : 4; + this.nextChar(); + for(var i = 0; i < expectedHexDigits; i++) { + if(this.IsHexDigit(this.ch)) { + this.nextChar(); + } else { + this.reportScannerError("Invalid Unicode escape sequence"); + break; + } + } + continue scanStringConstantLoop; + } + break; + } + if(this.ch >= TypeScript.LexCodeASCIIChars) { + this.seenUnicodeChar = true; + } + this.nextChar(); + } + return new TypeScript.StringLiteralToken(this.src.substring(this.startPos, this.pos)); + }; + Scanner.prototype.scanIdentifier = function () { + var hasEscape = false; + var isFirstChar = (this.ch == TypeScript.LexCodeBSL); + var hasUnicode = false; + for(; ; ) { + while(lexIdStartTable[this.ch] || LexIsDigit(this.ch) || (this.ch >= TypeScript.LexCodeASCIIChars && this.isValidUnicodeIdentifierChar())) { + this.nextChar(); + } + if(this.ch == TypeScript.LexCodeBSL) { + this.nextChar(); + if(this.ch == TypeScript.LexCode_u) { + this.nextChar(); + for(var h = 0; h < 4; h++) { + if(this.IsHexDigit(this.ch)) { + this.nextChar(); + } else { + this.reportScannerError("Invalid Unicode escape sequence"); + return TypeScript.staticTokens[TypeScript.TokenID.Error]; + } + } + var hexChar = parseInt(this.src.substring(this.pos - 4, this.pos), 16); + if(lexIdStartTable[hexChar] || (!isFirstChar && LexIsDigit(hexChar)) || (hexChar >= TypeScript.LexCodeASCIIChars && (LexIsUnicodeIdStart(hexChar) || (!isFirstChar && LexIsUnicodeDigit(hexChar))))) { + } else { + this.reportScannerError("Invalid identifier character"); + return TypeScript.staticTokens[TypeScript.TokenID.Error]; + } + hasEscape = true; + isFirstChar = false; + continue; + } + this.reportScannerError("Invalid Unicode escape sequence"); + return TypeScript.staticTokens[TypeScript.TokenID.Error]; + } + break; + } + var id; + var text = this.src.substring(this.startPos, this.pos); + if(!hasEscape && (id = TypeScript.LexKeywordTable.lookup(text)) != null) { + return TypeScript.staticTokens[id]; + } else { + return new TypeScript.IdentifierToken(text, hasEscape); + } + }; + Scanner.prototype.innerScan = function () { + var rtok; + this.tokenStart(); + this.ch = this.peekChar(); + start: +while(this.pos < this.len) { + if(lexIdStartTable[this.ch] || this.ch == TypeScript.LexCodeBSL || (this.ch >= TypeScript.LexCodeASCIIChars && LexIsUnicodeIdStart(this.ch))) { + return this.scanIdentifier(); + } else if(this.ch == TypeScript.LexCodeSpace) { + if(!this.interveningWhitespace) { + this.interveningWhitespacePos = this.pos; + } + do { + this.nextChar(); + }while(this.ch == TypeScript.LexCodeSpace); + if(this.mode == LexMode.Line) { + var whitespaceText = this.src.substring(this.startPos, this.pos); + return new TypeScript.WhitespaceToken(TypeScript.TokenID.Whitespace, whitespaceText); + } else { + this.tokenStart(); + this.interveningWhitespace = true; + } + } else if(this.ch == TypeScript.LexCodeSLH) { + this.nextChar(); + var commentText; + if(this.ch == TypeScript.LexCodeSLH) { + if(!this.interveningWhitespace) { + this.interveningWhitespacePos = this.pos - 1; + } + var commentStartPos = this.pos - 1; + var commentStartLine = this.line; + this.finishSinglelineComment(); + var commentText = this.src.substring(commentStartPos, this.pos); + var commentToken = new TypeScript.CommentToken(TypeScript.TokenID.Comment, commentText, false, commentStartPos, commentStartLine, false); + if(this.scanComments) { + this.startPos = commentStartPos; + return commentToken; + } else { + this.pushComment(commentToken); + } + this.interveningWhitespace = true; + } else if(this.ch == TypeScript.LexCodeMUL) { + if(!this.interveningWhitespace) { + this.interveningWhitespacePos = this.pos - 1; + } + var commentStartPos = this.pos - 1; + var commentStartLine = this.line; + this.nextChar(); + this.finishMultilineComment(); + var commentText = this.src.substring(commentStartPos, this.pos); + var endsLine = this.endsLine(this.peekChar()); + var commentToken = new TypeScript.CommentToken(TypeScript.TokenID.Comment, commentText, true, commentStartPos, commentStartLine, endsLine); + if(this.scanComments) { + this.startPos = commentStartPos; + return commentToken; + } else { + this.pushComment(commentToken); + } + this.interveningWhitespace = true; + } else { + var regexTok = this.speculateRegex(); + if(regexTok) { + return regexTok; + } else { + if(this.peekCharAt(this.pos) == TypeScript.LexCodeEQ) { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.SlashEquals]; + } else { + return TypeScript.staticTokens[TypeScript.TokenID.Slash]; + } + } + } + } else if(this.ch == TypeScript.LexCodeSMC) { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Semicolon]; + } else if((this.ch == TypeScript.LexCodeAPO) || (this.ch == TypeScript.LexCodeQUO)) { + var endCode = this.ch; + this.nextChar(); + return this.scanStringConstant(endCode); + } else if(autoToken[this.ch]) { + var atok = autoToken[this.ch]; + if(atok.tokenId == TypeScript.TokenID.OpenBrace) { + this.leftCurlyCount++; + } else if(atok.tokenId == TypeScript.TokenID.CloseBrace) { + this.rightCurlyCount++; + } + this.nextChar(); + return atok; + } else if((this.ch >= TypeScript.LexCode_0) && (this.ch <= TypeScript.LexCode_9)) { + rtok = this.scanNumber(); + if(rtok) { + return rtok; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Error]; + } + } else { + switch(this.ch) { + case TypeScript.LexCodeTAB: + case TypeScript.LexCodeVTAB: + if(!this.interveningWhitespace) { + this.interveningWhitespacePos = this.pos; + } + if(this.mode == LexMode.Line) { + do { + this.nextChar(); + }while((this.ch == TypeScript.LexCodeSpace) || (this.ch == 9)); + var wsText = this.src.substring(this.startPos, this.pos); + return new TypeScript.WhitespaceToken(TypeScript.TokenID.Whitespace, wsText); + } else { + this.interveningWhitespace = true; + } + case 0xFF: + case 0xFE: + case 0xEF: + case 0xBB: + case 0xBF: + case TypeScript.LexCodeLS: + case TypeScript.LexCodePS: + case TypeScript.LexCodeNWL: + case TypeScript.LexCodeRET: + if(this.ch == TypeScript.LexCodeNWL) { + this.newLine(); + if(this.mode == LexMode.Line) { + return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; + } + } + if(!this.interveningWhitespace) { + this.interveningWhitespacePos = this.pos; + } + this.nextChar(); + this.tokenStart(); + this.interveningWhitespace = true; + break; + case TypeScript.LexCodeDOT: { + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeDOT) { + if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeDOT) { + this.advanceChar(3); + return TypeScript.staticTokens[TypeScript.TokenID.DotDotDot]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Dot]; + } + } else { + this.nextChar(); + rtok = this.scanFraction(); + if(rtok) { + return rtok; + } else { + return TypeScript.staticTokens[TypeScript.TokenID.Dot]; + } + } + } + case TypeScript.LexCodeEQ: + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeEQ) { + this.advanceChar(3); + return TypeScript.staticTokens[TypeScript.TokenID.EqualsEqualsEquals]; + } else { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.EqualsEquals]; + } + } else if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeGT) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.EqualsGreaterThan]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Equals]; + } + case TypeScript.LexCodeBNG: + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeEQ) { + this.advanceChar(3); + return TypeScript.staticTokens[TypeScript.TokenID.ExclamationEqualsEquals]; + } else { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.ExclamationEquals]; + } + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Exclamation]; + } + case TypeScript.LexCodePLS: + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.PlusEquals]; + } else if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodePLS) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.PlusPlus]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Plus]; + } + case TypeScript.LexCodeMIN: + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.MinusEquals]; + } else if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeMIN) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.MinusMinus]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Minus]; + } + case TypeScript.LexCodeMUL: + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.AsteriskEquals]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Asterisk]; + } + case TypeScript.LexCodePCT: + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.PercentEquals]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Percent]; + } + case TypeScript.LexCodeLT: + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeLT) { + if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeEQ) { + this.advanceChar(3); + return TypeScript.staticTokens[TypeScript.TokenID.LessThanLessThanEquals]; + } else { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.LessThanLessThan]; + } + } else if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.LessThanEquals]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.LessThan]; + } + case TypeScript.LexCodeGT: + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeGT) { + if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeEQ) { + this.advanceChar(3); + return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanGreaterThanEquals]; + } else if(this.peekCharAt(this.pos + 2) == TypeScript.LexCodeGT) { + if(this.peekCharAt(this.pos + 3) == TypeScript.LexCodeEQ) { + this.advanceChar(4); + return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanGreaterThanGreaterThanEquals]; + } else { + this.advanceChar(3); + return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanGreaterThanGreaterThan]; + } + } else { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanGreaterThan]; + } + } else if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.GreaterThanEquals]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.GreaterThan]; + } + case TypeScript.LexCodeXOR: + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.CaretEquals]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Caret]; + } + case TypeScript.LexCodeBAR: + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.BarEquals]; + } else if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeBAR) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.BarBar]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.Bar]; + } + case TypeScript.LexCodeAMP: + if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeEQ) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.AmpersandEquals]; + } else if(this.peekCharAt(this.pos + 1) == TypeScript.LexCodeAMP) { + this.advanceChar(2); + return TypeScript.staticTokens[TypeScript.TokenID.AmpersandAmpersand]; + } else { + this.nextChar(); + return TypeScript.staticTokens[TypeScript.TokenID.And]; + } + default: + this.reportScannerError("Invalid character"); + this.nextChar(); + continue start; + } + } + } + return TypeScript.staticTokens[TypeScript.TokenID.EndOfFile]; + }; + Scanner.prototype.reportScannerError = function (message) { + if(this.reportError) { + this.reportError(message); + } + }; + return Scanner; + })(); + TypeScript.Scanner = Scanner; + function convertTokToIDName(tok) { + return convertTokToIDBase(tok, true, false); + } + TypeScript.convertTokToIDName = convertTokToIDName; + function convertTokToID(tok, strictMode) { + return convertTokToIDBase(tok, false, strictMode); + } + TypeScript.convertTokToID = convertTokToID; + function convertTokToIDBase(tok, identifierName, strictMode) { + if(tok.tokenId <= TypeScript.TokenID.LimKeyword) { + var tokInfo = TypeScript.lookupToken(tok.tokenId); + if(tokInfo != undefined) { + var resFlags = TypeScript.Reservation.Javascript | TypeScript.Reservation.JavascriptFuture; + if(strictMode) { + resFlags |= TypeScript.Reservation.JavascriptFutureStrict; + } + if(identifierName || !TypeScript.hasFlag(tokInfo.reservation, resFlags)) { + return true; + } + } else { + return false; + } + } else { + return false; + } + } + function getLineNumberFromPosition(lineMap, position) { + if(position === -1) { + return 0; + } + var min = 0; + var max = lineMap.length - 1; + while(min < max) { + var med = (min + max) >> 1; + if(position < lineMap[med]) { + max = med - 1; + } else if(position < lineMap[med + 1]) { + min = max = med; + } else { + min = med + 1; + } + } + return min; + } + TypeScript.getLineNumberFromPosition = getLineNumberFromPosition; + function getSourceLineColFromMap(lineCol, minChar, lineMap) { + var line = getLineNumberFromPosition(lineMap, minChar); + if(line > 0) { + lineCol.line = line; + lineCol.col = (minChar - lineMap[line]); + } + } + TypeScript.getSourceLineColFromMap = getSourceLineColFromMap; + function getLineColumnFromPosition(script, position) { + var result = { + line: -1, + col: -1 + }; + getSourceLineColFromMap(result, position, script.locationInfo.lineMap); + if(result.col >= 0) { + result.col++; + } + return result; + } + TypeScript.getLineColumnFromPosition = getLineColumnFromPosition; + function getPositionFromLineColumn(script, line, column) { + return script.locationInfo.lineMap[line] + (column - 1); + } + TypeScript.getPositionFromLineColumn = getPositionFromLineColumn; + function isPrimitiveTypeToken(token) { + switch(token.tokenId) { + case TypeScript.TokenID.Any: + case TypeScript.TokenID.Bool: + case TypeScript.TokenID.Number: + case TypeScript.TokenID.String: + return true; + } + return false; + } + TypeScript.isPrimitiveTypeToken = isPrimitiveTypeToken; + function isModifier(token) { + switch(token.tokenId) { + case TypeScript.TokenID.Public: + case TypeScript.TokenID.Private: + case TypeScript.TokenID.Static: + return true; + } + return false; + } + TypeScript.isModifier = isModifier; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var AssignScopeContext = (function () { + function AssignScopeContext(scopeChain, typeFlow, modDeclChain) { + this.scopeChain = scopeChain; + this.typeFlow = typeFlow; + this.modDeclChain = modDeclChain; + } + return AssignScopeContext; + })(); + TypeScript.AssignScopeContext = AssignScopeContext; + function pushAssignScope(scope, context, type, classType, fnc) { + var chain = new TypeScript.ScopeChain(null, context.scopeChain, scope); + chain.thisType = type; + chain.classType = classType; + chain.fnc = fnc; + context.scopeChain = chain; + } + TypeScript.pushAssignScope = pushAssignScope; + function popAssignScope(context) { + context.scopeChain = context.scopeChain.previous; + } + TypeScript.popAssignScope = popAssignScope; + function instanceCompare(a, b) { + if(((a == null) || (!a.isInstanceProperty()))) { + return b; + } else { + return a; + } + } + TypeScript.instanceCompare = instanceCompare; + function instanceFilterStop(s) { + return s.isInstanceProperty(); + } + TypeScript.instanceFilterStop = instanceFilterStop; + var ScopeSearchFilter = (function () { + function ScopeSearchFilter(select, stop) { + this.select = select; + this.stop = stop; + this.result = null; + } + ScopeSearchFilter.prototype.reset = function () { + this.result = null; + }; + ScopeSearchFilter.prototype.update = function (b) { + this.result = this.select(this.result, b); + if(this.result) { + return this.stop(this.result); + } else { + return false; + } + }; + return ScopeSearchFilter; + })(); + TypeScript.ScopeSearchFilter = ScopeSearchFilter; + TypeScript.instanceFilter = new ScopeSearchFilter(instanceCompare, instanceFilterStop); + function preAssignModuleScopes(ast, context) { + var moduleDecl = ast; + var memberScope = null; + var aggScope = null; + if(moduleDecl.name && moduleDecl.mod) { + moduleDecl.name.sym = moduleDecl.mod.symbol; + } + var mod = moduleDecl.mod; + if(!mod) { + return; + } + memberScope = new TypeScript.SymbolTableScope(mod.members, mod.ambientMembers, mod.enclosedTypes, mod.ambientEnclosedTypes, mod.symbol); + mod.memberScope = memberScope; + context.modDeclChain.push(moduleDecl); + context.typeFlow.checker.currentModDecl = moduleDecl; + aggScope = new TypeScript.SymbolAggregateScope(mod.symbol); + aggScope.addParentScope(memberScope); + aggScope.addParentScope(context.scopeChain.scope); + pushAssignScope(aggScope, context, null, null, null); + mod.containedScope = aggScope; + if(mod.symbol) { + context.typeFlow.addLocalsFromScope(mod.containedScope, mod.symbol, moduleDecl.vars, mod.members.privateMembers, true); + } + } + TypeScript.preAssignModuleScopes = preAssignModuleScopes; + function preAssignClassScopes(ast, context) { + var classDecl = ast; + var memberScope = null; + var aggScope = null; + if(classDecl.name && classDecl.type) { + classDecl.name.sym = classDecl.type.symbol; + } + var classType = ast.type; + if(classType) { + var classSym = classType.symbol; + memberScope = context.typeFlow.checker.scopeOf(classType); + aggScope = new TypeScript.SymbolAggregateScope(classType.symbol); + aggScope.addParentScope(memberScope); + aggScope.addParentScope(context.scopeChain.scope); + classType.containedScope = aggScope; + classType.memberScope = memberScope; + var instanceType = classType.instanceType; + memberScope = context.typeFlow.checker.scopeOf(instanceType); + instanceType.memberScope = memberScope; + aggScope = new TypeScript.SymbolAggregateScope(instanceType.symbol); + aggScope.addParentScope(context.scopeChain.scope); + pushAssignScope(aggScope, context, instanceType, classType, null); + instanceType.containedScope = aggScope; + } else { + ast.type = context.typeFlow.anyType; + } + } + TypeScript.preAssignClassScopes = preAssignClassScopes; + function preAssignInterfaceScopes(ast, context) { + var interfaceDecl = ast; + var memberScope = null; + var aggScope = null; + if(interfaceDecl.name && interfaceDecl.type) { + interfaceDecl.name.sym = interfaceDecl.type.symbol; + } + var interfaceType = ast.type; + memberScope = context.typeFlow.checker.scopeOf(interfaceType); + interfaceType.memberScope = memberScope; + aggScope = new TypeScript.SymbolAggregateScope(interfaceType.symbol); + aggScope.addParentScope(memberScope); + aggScope.addParentScope(context.scopeChain.scope); + pushAssignScope(aggScope, context, null, null, null); + interfaceType.containedScope = aggScope; + } + TypeScript.preAssignInterfaceScopes = preAssignInterfaceScopes; + function preAssignWithScopes(ast, context) { + var withStmt = ast; + var withType = withStmt.type; + var members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + var ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + var withType = new TypeScript.Type(); + var withSymbol = new TypeScript.WithSymbol(withStmt.minChar, context.typeFlow.checker.locationInfo.unitIndex, withType); + withType.members = members; + withType.ambientMembers = ambientMembers; + withType.symbol = withSymbol; + withType.setHasImplementation(); + withStmt.type = withType; + var withScope = new TypeScript.SymbolScopeBuilder(withType.members, withType.ambientMembers, null, null, context.scopeChain.scope, withType.symbol); + pushAssignScope(withScope, context, null, null, null); + withType.containedScope = withScope; + } + TypeScript.preAssignWithScopes = preAssignWithScopes; + function preAssignFuncDeclScopes(ast, context) { + var funcDecl = ast; + var container = null; + var localContainer = null; + if(funcDecl.type) { + localContainer = ast.type.symbol; + } + var isStatic = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static); + var isInnerStatic = isStatic && context.scopeChain.fnc != null; + var parentScope = isInnerStatic ? context.scopeChain.fnc.type.memberScope : context.scopeChain.scope; + if(context.scopeChain.thisType && (!funcDecl.isConstructor || TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod))) { + var instType = context.scopeChain.thisType; + if(!(instType.typeFlags & TypeScript.TypeFlags.IsClass) && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { + if(!funcDecl.isMethod() || isStatic) { + parentScope = instType.constructorScope; + } else { + parentScope = instType.containedScope; + } + } else { + if(context.scopeChain.previous.scope.container && context.scopeChain.previous.scope.container.declAST && context.scopeChain.previous.scope.container.declAST.nodeType == TypeScript.NodeType.FuncDecl && (context.scopeChain.previous.scope.container.declAST).isConstructor) { + parentScope = instType.constructorScope; + } else if(isStatic && context.scopeChain.classType) { + parentScope = context.scopeChain.classType.containedScope; + } else { + parentScope = instType.containedScope; + } + } + container = instType.symbol; + } else if(funcDecl.isConstructor && context.scopeChain.thisType) { + container = context.scopeChain.thisType.symbol; + } + if(funcDecl.type == null || TypeScript.hasFlag(funcDecl.type.symbol.flags, TypeScript.SymbolFlags.TypeSetDuringScopeAssignment)) { + if(context.scopeChain.fnc && context.scopeChain.fnc.type) { + container = context.scopeChain.fnc.type.symbol; + } + var funcScope = null; + var outerFnc = context.scopeChain.fnc; + var nameText = funcDecl.name ? funcDecl.name.actualText : null; + var fgSym = null; + if(isStatic) { + if(outerFnc.type.members == null && container.getType().memberScope) { + outerFnc.type.members = ((container).type.memberScope).valueMembers; + } + funcScope = context.scopeChain.fnc.type.memberScope; + outerFnc.innerStaticFuncs[outerFnc.innerStaticFuncs.length] = funcDecl; + } else { + funcScope = context.scopeChain.scope; + } + if(nameText && nameText != "__missing" && !funcDecl.isAccessor()) { + if(isStatic) { + fgSym = funcScope.findLocal(nameText, false, false); + } else { + fgSym = funcScope.findLocal(nameText, false, false); + } + } + context.typeFlow.checker.createFunctionSignature(funcDecl, container, funcScope, fgSym, fgSym == null); + if(!funcDecl.accessorSymbol && (funcDecl.fncFlags & TypeScript.FncFlags.ClassMethod) && container && ((!fgSym || fgSym.declAST.nodeType != TypeScript.NodeType.FuncDecl) && funcDecl.isAccessor()) || (fgSym && fgSym.isAccessor())) { + funcDecl.accessorSymbol = context.typeFlow.checker.createAccessorSymbol(funcDecl, fgSym, container.getType(), (funcDecl.isMethod() && isStatic), true, funcScope, container); + } + funcDecl.type.symbol.flags |= TypeScript.SymbolFlags.TypeSetDuringScopeAssignment; + } + if(funcDecl.name && funcDecl.type) { + funcDecl.name.sym = funcDecl.type.symbol; + } + funcDecl.scopeType = funcDecl.type; + if(funcDecl.isOverload) { + return; + } + var funcTable = new TypeScript.StringHashTable(); + var funcMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(funcTable, new TypeScript.StringHashTable())); + var ambientFuncTable = new TypeScript.StringHashTable(); + var ambientFuncMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(ambientFuncTable, new TypeScript.StringHashTable())); + var funcStaticTable = new TypeScript.StringHashTable(); + var funcStaticMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(funcStaticTable, new TypeScript.StringHashTable())); + var ambientFuncStaticTable = new TypeScript.StringHashTable(); + var ambientFuncStaticMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(ambientFuncStaticTable, new TypeScript.StringHashTable())); + funcDecl.unitIndex = context.typeFlow.checker.locationInfo.unitIndex; + var locals = new TypeScript.SymbolScopeBuilder(funcMembers, ambientFuncMembers, null, null, parentScope, localContainer); + var statics = new TypeScript.SymbolScopeBuilder(funcStaticMembers, ambientFuncStaticMembers, null, null, parentScope, null); + if(funcDecl.isConstructor && context.scopeChain.thisType) { + context.scopeChain.thisType.constructorScope = locals; + } + funcDecl.symbols = funcTable; + if(!funcDecl.isSpecialFn()) { + var group = funcDecl.type; + var signature = funcDecl.signature; + if(!funcDecl.isConstructor) { + group.containedScope = locals; + locals.container = group.symbol; + group.memberScope = statics; + statics.container = group.symbol; + } + funcDecl.enclosingFnc = context.scopeChain.fnc; + group.enclosingType = isStatic ? context.scopeChain.classType : context.scopeChain.thisType; + var fgSym = ast.type.symbol; + if(((funcDecl.fncFlags & TypeScript.FncFlags.Signature) == TypeScript.FncFlags.None) && funcDecl.vars) { + context.typeFlow.addLocalsFromScope(locals, fgSym, funcDecl.vars, funcTable, false); + context.typeFlow.addLocalsFromScope(statics, fgSym, funcDecl.statics, funcStaticTable, false); + } + if(signature.parameters) { + var len = signature.parameters.length; + for(var i = 0; i < len; i++) { + var paramSym = signature.parameters[i]; + context.typeFlow.checker.resolveTypeLink(locals, paramSym.parameter.typeLink, true); + } + } + context.typeFlow.checker.resolveTypeLink(locals, signature.returnType, funcDecl.isSignature()); + } + if(!funcDecl.isConstructor || TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { + var thisType = (funcDecl.isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) ? context.scopeChain.thisType : null; + pushAssignScope(locals, context, thisType, null, funcDecl); + } + if(funcDecl.name && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFunctionExpression) && !funcDecl.isAccessor()) { + if(funcDecl.name.sym) { + funcTable.add(funcDecl.name.actualText, funcDecl.name.sym); + } + } + } + TypeScript.preAssignFuncDeclScopes = preAssignFuncDeclScopes; + function preAssignCatchScopes(ast, context) { + var catchBlock = ast; + if(catchBlock.param) { + var catchTable = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + var catchLocals = new TypeScript.SymbolScopeBuilder(catchTable, null, null, null, context.scopeChain.scope, context.scopeChain.scope.container); + catchBlock.containedScope = catchLocals; + pushAssignScope(catchLocals, context, context.scopeChain.thisType, context.scopeChain.classType, context.scopeChain.fnc); + } + } + TypeScript.preAssignCatchScopes = preAssignCatchScopes; + function preAssignScopes(ast, parent, walker) { + var context = walker.state; + var go = true; + if(ast) { + if(ast.nodeType == TypeScript.NodeType.List) { + var list = ast; + list.enclosingScope = context.scopeChain.scope; + } else if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { + preAssignModuleScopes(ast, context); + } else if(ast.nodeType == TypeScript.NodeType.ClassDeclaration) { + preAssignClassScopes(ast, context); + } else if(ast.nodeType == TypeScript.NodeType.InterfaceDeclaration) { + preAssignInterfaceScopes(ast, context); + } else if(ast.nodeType == TypeScript.NodeType.With) { + preAssignWithScopes(ast, context); + } else if(ast.nodeType == TypeScript.NodeType.FuncDecl) { + preAssignFuncDeclScopes(ast, context); + } else if(ast.nodeType == TypeScript.NodeType.Catch) { + preAssignCatchScopes(ast, context); + } else if(ast.nodeType == TypeScript.NodeType.TypeRef) { + go = false; + } + } + walker.options.goChildren = go; + return ast; + } + TypeScript.preAssignScopes = preAssignScopes; + function postAssignScopes(ast, parent, walker) { + var context = walker.state; + var go = true; + if(ast) { + if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { + var prevModDecl = ast; + popAssignScope(context); + context.modDeclChain.pop(); + if(context.modDeclChain.length >= 1) { + context.typeFlow.checker.currentModDecl = context.modDeclChain[context.modDeclChain.length - 1]; + } + } else if(ast.nodeType == TypeScript.NodeType.ClassDeclaration) { + popAssignScope(context); + } else if(ast.nodeType == TypeScript.NodeType.InterfaceDeclaration) { + popAssignScope(context); + } else if(ast.nodeType == TypeScript.NodeType.With) { + popAssignScope(context); + } else if(ast.nodeType == TypeScript.NodeType.FuncDecl) { + var funcDecl = ast; + if((!funcDecl.isConstructor || TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) && !funcDecl.isOverload) { + popAssignScope(context); + } + } else if(ast.nodeType == TypeScript.NodeType.Catch) { + var catchBlock = ast; + if(catchBlock.param) { + popAssignScope(context); + } + } else { + go = false; + } + } + walker.options.goChildren = go; + return ast; + } + TypeScript.postAssignScopes = postAssignScopes; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var TypeCollectionContext = (function () { + function TypeCollectionContext(scopeChain, checker) { + this.scopeChain = scopeChain; + this.checker = checker; + this.script = null; + } + return TypeCollectionContext; + })(); + TypeScript.TypeCollectionContext = TypeCollectionContext; + var MemberScopeContext = (function () { + function MemberScopeContext(flow, pos, matchFlag) { + this.flow = flow; + this.pos = pos; + this.matchFlag = matchFlag; + this.type = null; + this.ast = null; + this.options = new TypeScript.AstWalkOptions(); + } + return MemberScopeContext; + })(); + TypeScript.MemberScopeContext = MemberScopeContext; + var EnclosingScopeContext = (function () { + function EnclosingScopeContext(logger, script, text, pos, isMemberCompletion) { + this.logger = logger; + this.script = script; + this.text = text; + this.pos = pos; + this.isMemberCompletion = isMemberCompletion; + this.scopeGetter = null; + this.objectLiteralScopeGetter = null; + this.scopeStartAST = null; + this.skipNextFuncDeclForClass = false; + this.deepestModuleDecl = null; + this.enclosingClassDecl = null; + this.enclosingObjectLit = null; + this.publicsOnly = true; + this.useFullAst = false; + } + EnclosingScopeContext.prototype.getScope = function () { + return this.scopeGetter(); + }; + EnclosingScopeContext.prototype.getObjectLiteralScope = function () { + return this.objectLiteralScopeGetter(); + }; + EnclosingScopeContext.prototype.getScopeAST = function () { + return this.scopeStartAST; + }; + EnclosingScopeContext.prototype.getScopePosition = function () { + return this.scopeStartAST.minChar; + }; + EnclosingScopeContext.prototype.getScriptFragmentStartAST = function () { + return this.scopeStartAST; + }; + EnclosingScopeContext.prototype.getScriptFragmentPosition = function () { + return this.getScriptFragmentStartAST().minChar; + }; + EnclosingScopeContext.prototype.getScriptFragment = function () { + if(this.scriptFragment == null) { + var ast = this.getScriptFragmentStartAST(); + var minChar = ast.minChar; + var limChar = (this.isMemberCompletion ? this.pos : this.pos + 1); + this.scriptFragment = TypeScript.quickParse(this.logger, ast, this.text, minChar, limChar, null).Script; + } + return this.scriptFragment; + }; + return EnclosingScopeContext; + })(); + TypeScript.EnclosingScopeContext = EnclosingScopeContext; + function preFindMemberScope(ast, parent, walker) { + var memScope = walker.state; + if(TypeScript.hasFlag(ast.flags, memScope.matchFlag) && ((memScope.pos < 0) || (memScope.pos == ast.limChar))) { + memScope.ast = ast; + if((ast.type == null) && (memScope.pos >= 0)) { + memScope.flow.inScopeTypeCheck(ast, memScope.scope); + } + memScope.type = ast.type; + memScope.options.stopWalk(); + } + return ast; + } + TypeScript.preFindMemberScope = preFindMemberScope; + function pushTypeCollectionScope(container, valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, context, thisType, classType, moduleDecl) { + var builder = new TypeScript.SymbolScopeBuilder(valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, null, container); + var chain = new TypeScript.ScopeChain(container, context.scopeChain, builder); + chain.thisType = thisType; + chain.classType = classType; + chain.moduleDecl = moduleDecl; + context.scopeChain = chain; + } + TypeScript.pushTypeCollectionScope = pushTypeCollectionScope; + function popTypeCollectionScope(context) { + context.scopeChain = context.scopeChain.previous; + } + TypeScript.popTypeCollectionScope = popTypeCollectionScope; + function preFindEnclosingScope(ast, parent, walker) { + var context = walker.state; + var minChar = ast.minChar; + var limChar = ast.limChar; + if(ast.nodeType == TypeScript.NodeType.Script && context.pos > limChar) { + limChar = context.pos; + } + if((minChar <= context.pos) && (limChar >= context.pos)) { + switch(ast.nodeType) { + case TypeScript.NodeType.Script: + var script = ast; + context.scopeGetter = function () { + return script.bod === null ? null : script.bod.enclosingScope; + }; + context.scopeStartAST = script; + break; + case TypeScript.NodeType.ClassDeclaration: + context.scopeGetter = function () { + return (ast.type === null || ast.type.instanceType.containedScope === null) ? null : ast.type.instanceType.containedScope; + }; + context.scopeStartAST = ast; + context.enclosingClassDecl = ast; + break; + case TypeScript.NodeType.ObjectLit: + var objectLit = ast; + if(objectLit.targetType) { + context.scopeGetter = function () { + return objectLit.targetType.containedScope; + }; + context.objectLiteralScopeGetter = function () { + return objectLit.targetType.memberScope; + }; + context.enclosingObjectLit = objectLit; + } + break; + case TypeScript.NodeType.ModuleDeclaration: + context.deepestModuleDecl = ast; + context.scopeGetter = function () { + return ast.type === null ? null : ast.type.containedScope; + }; + context.scopeStartAST = ast; + break; + case TypeScript.NodeType.InterfaceDeclaration: + context.scopeGetter = function () { + return (ast.type === null) ? null : ast.type.containedScope; + }; + context.scopeStartAST = ast; + break; + case TypeScript.NodeType.FuncDecl: + { + var funcDecl = ast; + if(context.skipNextFuncDeclForClass) { + context.skipNextFuncDeclForClass = false; + } else { + context.scopeGetter = function () { + if(funcDecl.isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { + if(ast.type && ast.type.enclosingType) { + return ast.type.enclosingType.constructorScope; + } + } + if(funcDecl.scopeType) { + return funcDecl.scopeType.containedScope; + } + if(funcDecl.type) { + return funcDecl.type.containedScope; + } + return null; + }; + context.scopeStartAST = ast; + } + } + break; + } + walker.options.goChildren = true; + } else { + walker.options.goChildren = false; + } + return ast; + } + TypeScript.preFindEnclosingScope = preFindEnclosingScope; + function findEnclosingScopeAt(logger, script, text, pos, isMemberCompletion) { + var context = new EnclosingScopeContext(logger, script, text, pos, isMemberCompletion); + TypeScript.getAstWalkerFactory().walk(script, preFindEnclosingScope, null, null, context); + if(context.scopeStartAST === null) { + return null; + } + return context; + } + TypeScript.findEnclosingScopeAt = findEnclosingScopeAt; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Signature = (function () { + function Signature() { + this.hasVariableArgList = false; + this.parameters = null; + this.declAST = null; + this.typeCheckStatus = TypeScript.TypeCheckStatus.NotStarted; + this.nonOptionalParameterCount = 0; + } + Signature.prototype.specializeType = function (pattern, replacement, checker) { + var result = new Signature(); + if(this.hasVariableArgList) { + result.hasVariableArgList = true; + } + result.returnType = new TypeScript.TypeLink(); + if(this.returnType.type) { + result.returnType.type = this.returnType.type.specializeType(pattern, replacement, checker, false); + } else { + result.returnType.type = checker.anyType; + } + if(this.parameters) { + result.parameters = []; + for(var i = 0, len = this.parameters.length; i < len; i++) { + var oldSym = this.parameters[i]; + var paramDef = new TypeScript.ValueLocation(); + var paramSym = new TypeScript.ParameterSymbol(oldSym.name, oldSym.location, checker.locationInfo.unitIndex, paramDef); + paramSym.declAST = this.declAST; + paramDef.symbol = paramSym; + paramDef.typeLink = new TypeScript.TypeLink(); + result.parameters[i] = paramSym; + var oldType = oldSym.getType(); + if(oldType) { + paramDef.typeLink.type = oldType.specializeType(pattern, replacement, checker, false); + } else { + paramDef.typeLink.type = checker.anyType; + } + } + } + result.nonOptionalParameterCount = this.nonOptionalParameterCount; + result.declAST = this.declAST; + return result; + }; + Signature.prototype.toString = function () { + return this.toStringHelper(false, false, null); + }; + Signature.prototype.toStringHelper = function (shortform, brackets, scope) { + return this.toStringHelperEx(shortform, brackets, scope).toString(); + }; + Signature.prototype.toStringHelperEx = function (shortform, brackets, scope, prefix) { + if (typeof prefix === "undefined") { prefix = ""; } + var builder = new TypeScript.MemberNameArray(); + if(brackets) { + builder.prefix = prefix + "["; + } else { + builder.prefix = prefix + "("; + } + var paramLen = this.parameters.length; + var len = this.hasVariableArgList ? paramLen - 1 : paramLen; + for(var i = 0; i < len; i++) { + builder.add(TypeScript.MemberName.create(this.parameters[i].name + (this.parameters[i].isOptional() ? "?" : "") + ": ")); + builder.add(this.parameters[i].getType().getScopedTypeNameEx(scope)); + if(i < paramLen - 1) { + builder.add(TypeScript.MemberName.create(", ")); + } + } + if(this.hasVariableArgList) { + builder.add(TypeScript.MemberName.create("..." + this.parameters[i].name + ": ")); + builder.add(this.parameters[i].getType().getScopedTypeNameEx(scope)); + } + if(shortform) { + if(brackets) { + builder.add(TypeScript.MemberName.create("] => ")); + } else { + builder.add(TypeScript.MemberName.create(") => ")); + } + } else { + if(brackets) { + builder.add(TypeScript.MemberName.create("]: ")); + } else { + builder.add(TypeScript.MemberName.create("): ")); + } + } + if(this.returnType.type) { + builder.add(this.returnType.type.getScopedTypeNameEx(scope)); + } else { + builder.add(TypeScript.MemberName.create("any")); + } + return builder; + }; + return Signature; + })(); + TypeScript.Signature = Signature; + var SignatureGroup = (function () { + function SignatureGroup() { + this.signatures = []; + this.hasImplementation = true; + this.definitionSignature = null; + this.hasBeenTypechecked = false; + this.flags = TypeScript.SignatureFlags.None; + } + SignatureGroup.prototype.addSignature = function (signature) { + if(this.signatures == null) { + this.signatures = new Array(); + } + this.signatures[this.signatures.length] = signature; + if(signature.declAST && !signature.declAST.isOverload && !signature.declAST.isSignature() && !TypeScript.hasFlag(signature.declAST.fncFlags, TypeScript.FncFlags.Ambient) && !TypeScript.hasFlag(signature.declAST.fncFlags, TypeScript.FncFlags.Signature)) { + this.definitionSignature = signature; + } + }; + SignatureGroup.prototype.toString = function () { + return this.signatures.toString(); + }; + SignatureGroup.prototype.toStrings = function (prefix, shortform, scope, getPrettyTypeName, useSignature) { + var _this = this; + var result = []; + var len = this.signatures.length; + if(!getPrettyTypeName && len > 1) { + shortform = false; + } + var getMemberNameOfSignature = function (signature) { + if(_this.flags & TypeScript.SignatureFlags.IsIndexer) { + return signature.toStringHelperEx(shortform, true, scope); + } else { + return signature.toStringHelperEx(shortform, false, scope, prefix); + } + }; + if(useSignature) { + result.push(getMemberNameOfSignature(useSignature)); + } else { + for(var i = 0; i < len; i++) { + if(len > 1 && this.signatures[i] == this.definitionSignature) { + continue; + } + result.push(getMemberNameOfSignature(this.signatures[i])); + if(getPrettyTypeName) { + break; + } + } + } + if(getPrettyTypeName && len > 1) { + var lastMemberName = result[result.length - 1]; + var overloadString = " (+ " + ((this.definitionSignature != null) ? len - 2 : len - 1) + " overload(s))"; + lastMemberName.add(TypeScript.MemberName.create(overloadString)); + } + return result; + }; + SignatureGroup.prototype.specializeType = function (pattern, replacement, checker) { + var result = new SignatureGroup(); + if(this.signatures) { + for(var i = 0, len = this.signatures.length; i < len; i++) { + result.addSignature(this.signatures[i].specializeType(pattern, replacement, checker)); + } + } + return result; + }; + SignatureGroup.prototype.verifySignatures = function (checker) { + var len = 0; + if(this.signatures && ((len = this.signatures.length) > 0)) { + for(var i = 0; i < len; i++) { + for(var j = i + 1; j < len; j++) { + if(this.signatures[i].declAST && this.signatures[j].declAST && (TypeScript.hasFlag(this.signatures[i].declAST.fncFlags, TypeScript.FncFlags.Signature) && TypeScript.hasFlag(this.signatures[j].declAST.fncFlags, TypeScript.FncFlags.Signature)) && checker.signaturesAreIdentical(this.signatures[i], this.signatures[j])) { + checker.errorReporter.simpleError(this.signatures[i].declAST, (this.signatures[i].declAST && this.signatures[i].declAST.name) ? "Signature for '" + this.signatures[i].declAST.name.actualText + "' is duplicated" : "Signature is duplicated"); + } + } + if(this.definitionSignature) { + if(!checker.signatureIsAssignableToTarget(this.definitionSignature, this.signatures[i])) { + checker.errorReporter.simpleError(this.signatures[i].declAST, "Overload signature is not compatible with function definition"); + } + } + } + } + }; + SignatureGroup.prototype.typeCheck = function (checker, ast, hasConstruct) { + if(this.hasBeenTypechecked) { + return; + } + this.hasBeenTypechecked = true; + var len = 0; + if(this.signatures && ((len = this.signatures.length) > 0)) { + for(var i = 0; i < len; i++) { + if(!hasConstruct && !this.definitionSignature && this.signatures[i].declAST && this.signatures[i].declAST.isOverload && !TypeScript.hasFlag(this.signatures[i].declAST.fncFlags, TypeScript.FncFlags.Ambient)) { + checker.errorReporter.simpleError(this.signatures[i].declAST, "Overload declaration lacks definition"); + } + if(this.signatures[i].declAST && this.signatures[i].declAST.isConstructor && this.signatures[i].declAST.classDecl && this.signatures[i].declAST.classDecl.type.symbol.typeCheckStatus == TypeScript.TypeCheckStatus.NotStarted) { + checker.typeFlow.typeCheck(this.signatures[i].declAST.classDecl); + } + checker.typeFlow.typeCheck(this.signatures[i].declAST); + } + this.verifySignatures(checker); + } + }; + return SignatureGroup; + })(); + TypeScript.SignatureGroup = SignatureGroup; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (TypeCheckStatus) { + TypeCheckStatus._map = []; + TypeCheckStatus._map[0] = "NotStarted"; + TypeCheckStatus.NotStarted = 0; + TypeCheckStatus._map[1] = "Started"; + TypeCheckStatus.Started = 1; + TypeCheckStatus._map[2] = "Finished"; + TypeCheckStatus.Finished = 2; + })(TypeScript.TypeCheckStatus || (TypeScript.TypeCheckStatus = {})); + var TypeCheckStatus = TypeScript.TypeCheckStatus; + function aLexicallyEnclosesB(a, b) { + if(a.declAST && b && b.declAST && a.declAST.nodeType == TypeScript.NodeType.FuncDecl) { + return a.declAST.minChar <= b.declAST.minChar && a.declAST.limChar >= b.declAST.limChar; + } else { + return false; + } + } + TypeScript.aLexicallyEnclosesB = aLexicallyEnclosesB; + function aEnclosesB(a, b) { + while(a.container) { + if(a == b || aLexicallyEnclosesB(a.container, b)) { + return true; + } + a = a.container; + } + return false; + } + TypeScript.aEnclosesB = aEnclosesB; + var Symbol = (function () { + function Symbol(name, location, length, unitIndex) { + this.name = name; + this.location = location; + this.length = length; + this.unitIndex = unitIndex; + this.bound = false; + this.flags = TypeScript.SymbolFlags.None; + this.isObjectLitField = false; + this.declAST = null; + this.declModule = null; + this.passSymbolCreated = TypeScript.CompilerDiagnostics.analysisPass; + } + Symbol.prototype.instanceScope = function () { + return null; + }; + Symbol.prototype.isVariable = function () { + return false; + }; + Symbol.prototype.isMember = function () { + return false; + }; + Symbol.prototype.isInferenceSymbol = function () { + return false; + }; + Symbol.prototype.isWith = function () { + return false; + }; + Symbol.prototype.writeable = function () { + return false; + }; + Symbol.prototype.isType = function () { + return false; + }; + Symbol.prototype.getType = function () { + return null; + }; + Symbol.prototype.isAccessor = function () { + return false; + }; + Symbol.prototype.isInstanceProperty = function () { + return TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Property) && (!TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.ModuleMember)); + }; + Symbol.prototype.getTypeName = function (scope) { + return this.getTypeNameEx(scope).toString(); + }; + Symbol.prototype.getTypeNameEx = function (scope) { + return TypeScript.MemberName.create(this.toString()); + }; + Symbol.prototype.getOptionalNameString = function () { + return TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Optional) ? "?" : ""; + }; + Symbol.prototype.pathToRoot = function () { + var path = new Array(); + var node = this; + while(node && (node.name != TypeScript.globalId)) { + path[path.length] = node; + node = node.container; + } + return path; + }; + Symbol.prototype.findCommonAncestorPath = function (b) { + if(this.container == null) { + return new Array(); + } + var aPath = this.container.pathToRoot(); + var bPath; + if(b) { + bPath = b.pathToRoot(); + } else { + bPath = new Array(); + } + var commonNodeIndex = -1; + for(var i = 0, aLen = aPath.length; i < aLen; i++) { + var aNode = aPath[i]; + for(var j = 0, bLen = bPath.length; j < bLen; j++) { + var bNode = bPath[j]; + if(aNode == bNode) { + commonNodeIndex = i; + break; + } + } + if(commonNodeIndex >= 0) { + break; + } + } + if(commonNodeIndex >= 0) { + return aPath.slice(0, commonNodeIndex); + } else { + return aPath; + } + }; + Symbol.prototype.getPrettyName = function (scopeSymbol) { + return this.name; + }; + Symbol.prototype.scopeRelativeName = function (scope) { + if(scope == null) { + return this.getPrettyName(null) + this.getOptionalNameString(); + } + var lca = this.findCommonAncestorPath(scope.container); + var builder = ""; + for(var i = 0, len = lca.length; i < len; i++) { + var prettyName = lca[i].getPrettyName(i == len - 1 ? scope.container : lca[i + 1]); + builder = prettyName + "." + builder; + } + builder += this.getPrettyName(len == 0 ? scope.container : lca[0]) + this.getOptionalNameString(); + return builder; + }; + Symbol.prototype.fullName = function (scope) { + var scopeSymbol = !scope ? null : scope.container; + var scopeRootPath = !scopeSymbol ? [] : scopeSymbol.pathToRoot(); + var dynamicModuleRoot = null; + if(scopeRootPath.length > 0 && scopeRootPath[scopeRootPath.length - 1].declAST && scopeRootPath[scopeRootPath.length - 1].declAST.nodeType == TypeScript.NodeType.ModuleDeclaration && (scopeRootPath[scopeRootPath.length - 1].declAST).isWholeFile()) { + dynamicModuleRoot = scopeRootPath[scopeRootPath.length - 1]; + } + var builder = this.getPrettyName(scopeSymbol); + var ancestor = this.container; + while(ancestor && (ancestor.name != TypeScript.globalId) && ancestor != dynamicModuleRoot) { + builder = ancestor.getPrettyName(scopeSymbol) + "." + builder; + ancestor = ancestor.container; + } + return builder; + }; + Symbol.prototype.isExternallyVisible = function (checker) { + if(this == checker.gloMod) { + return true; + } + if(TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Private)) { + return false; + } + if(!TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Exported)) { + return this.container == checker.gloMod; + } + return this.container.isExternallyVisible(checker); + }; + Symbol.prototype.visible = function (scope, checker) { + if(checker == null || this.container == checker.gloMod) { + return true; + } + if(TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.ModuleMember)) { + if(TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Exported)) { + if(!TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Private)) { + return true; + } else { + return aEnclosesB(this, scope.container); + } + } else { + return checker && (checker.currentModDecl == this.declModule) || (checker.currentModDecl && checker.currentModDecl.mod && checker.currentModDecl.mod.symbol && this.declModule && this.declModule.mod && this.declModule.mod.symbol && aEnclosesB(checker.currentModDecl.mod.symbol, this.declModule.mod.symbol)); + } + } else { + var isFunction = this.declAST && this.declAST.nodeType == TypeScript.NodeType.FuncDecl; + var isMethod = isFunction && (this.declAST).isMethod(); + var isStaticFunction = isFunction && TypeScript.hasFlag((this.declAST).fncFlags, TypeScript.FncFlags.Static); + var isPrivateMethod = isMethod && TypeScript.hasFlag((this.declAST).fncFlags, TypeScript.FncFlags.Private); + var isAlias = this.isType() && (this).aliasLink; + if(this.isMember() || isMethod || isStaticFunction || isAlias) { + if(TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Private) || isPrivateMethod) { + if(scope.container == null && this.container != scope.container) { + return false; + } else { + return this.container == null ? true : aEnclosesB(scope.container, this.container); + } + } else { + return true; + } + } else if(this.container) { + return aEnclosesB(this, scope.container); + } else { + return true; + } + } + }; + Symbol.prototype.addRef = function (identifier) { + if(!this.refs) { + this.refs = []; + } + this.refs[this.refs.length] = identifier; + }; + Symbol.prototype.toString = function () { + if(this.name) { + return this.name; + } else { + return "_anonymous"; + } + }; + Symbol.prototype.print = function (outfile) { + outfile.Write(this.toString()); + }; + Symbol.prototype.specializeType = function (pattern, replacement, checker) { + throw new Error("please implement in derived class"); + }; + Symbol.prototype.setType = function (type) { + throw new Error("please implement in derived class"); + }; + Symbol.prototype.kind = function () { + throw new Error("please implement in derived class"); + }; + Symbol.prototype.getInterfaceDeclFromSymbol = function (checker) { + if(this.declAST != null) { + if(this.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) { + return this.declAST; + } else if(this.container != null && this.container != checker.gloMod && this.container.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) { + return this.container.declAST; + } + } + return null; + }; + Symbol.prototype.getVarDeclFromSymbol = function () { + if(this.declAST != null && this.declAST.nodeType == TypeScript.NodeType.VarDecl) { + return this.declAST; + } + return null; + }; + Symbol.prototype.getDocComments = function () { + if(this.declAST != null) { + return this.declAST.getDocComments(); + } + return []; + }; + Symbol.prototype.isStatic = function () { + return TypeScript.hasFlag(this.flags, TypeScript.SymbolFlags.Static); + }; + return Symbol; + })(); + TypeScript.Symbol = Symbol; + var ValueLocation = (function () { + function ValueLocation() { } + return ValueLocation; + })(); + TypeScript.ValueLocation = ValueLocation; + var InferenceSymbol = (function (_super) { + __extends(InferenceSymbol, _super); + function InferenceSymbol(name, location, length, unitIndex) { + _super.call(this, name, location, length, unitIndex); + this.typeCheckStatus = TypeCheckStatus.NotStarted; + } + InferenceSymbol.prototype.isInferenceSymbol = function () { + return true; + }; + InferenceSymbol.prototype.transferVarFlags = function (varFlags) { + if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Ambient)) { + this.flags |= TypeScript.SymbolFlags.Ambient; + } + if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Constant)) { + this.flags |= TypeScript.SymbolFlags.Constant; + } + if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Static)) { + this.flags |= TypeScript.SymbolFlags.Static; + } + if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Property)) { + this.flags |= TypeScript.SymbolFlags.Property; + } + if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Private)) { + this.flags |= TypeScript.SymbolFlags.Private; + } + if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Public)) { + this.flags |= TypeScript.SymbolFlags.Public; + } + if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Readonly)) { + this.flags |= TypeScript.SymbolFlags.Readonly; + } + if(TypeScript.hasFlag(varFlags, TypeScript.VarFlags.Exported)) { + this.flags |= TypeScript.SymbolFlags.Exported; + } + }; + return InferenceSymbol; + })(Symbol); + TypeScript.InferenceSymbol = InferenceSymbol; + var TypeSymbol = (function (_super) { + __extends(TypeSymbol, _super); + function TypeSymbol(locName, location, length, unitIndex, type) { + _super.call(this, locName, location, length, unitIndex); + this.type = type; + this.expansions = []; + this.expansionsDeclAST = []; + this.isDynamic = false; + this.isMethod = false; + this.aliasLink = null; + this.onlyReferencedAsTypeRef = TypeScript.optimizeModuleCodeGen; + this.prettyName = this.name; + } + TypeSymbol.prototype.addLocation = function (loc) { + if(this.additionalLocations == null) { + this.additionalLocations = []; + } + this.additionalLocations[this.additionalLocations.length] = loc; + }; + TypeSymbol.prototype.kind = function () { + return TypeScript.SymbolKind.Type; + }; + TypeSymbol.prototype.isType = function () { + return true; + }; + TypeSymbol.prototype.getType = function () { + return this.type; + }; + TypeSymbol.prototype.getTypeNameEx = function (scope) { + return this.type.getMemberTypeNameEx(this.name ? this.name + this.getOptionalNameString() : "", false, false, scope); + }; + TypeSymbol.prototype.instanceScope = function () { + if(!(this.type.typeFlags & TypeScript.TypeFlags.IsClass) && this.type.isClass()) { + return this.type.instanceType.constructorScope; + } else { + return this.type.containedScope; + } + }; + TypeSymbol.prototype.toString = function () { + var result = this.type.getTypeName(); + if(this.name) { + result = this.name + ":" + result; + } + return result; + }; + TypeSymbol.prototype.isClass = function () { + return this.instanceType != null; + }; + TypeSymbol.prototype.isFunction = function () { + return this.declAST != null && this.declAST.nodeType == TypeScript.NodeType.FuncDecl; + }; + TypeSymbol.prototype.specializeType = function (pattern, replacement, checker) { + if(this.type == pattern) { + return replacement.symbol; + } else { + var replType = this.type.specializeType(pattern, replacement, checker, false); + if(replType != this.type) { + var result = new TypeSymbol(this.name, -1, 0, -1, replType); + return result; + } else { + return this; + } + } + }; + TypeSymbol.prototype.getPrettyName = function (scopeSymbol) { + if(!!scopeSymbol && TypeScript.isQuoted(this.prettyName) && this.type.isModuleType()) { + var symbolPath = scopeSymbol.pathToRoot(); + var prettyName = this.getPrettyNameOfDynamicModule(symbolPath); + if(prettyName != null) { + return prettyName.name; + } + } + return this.prettyName; + }; + TypeSymbol.prototype.getPrettyNameOfDynamicModule = function (scopeSymbolPath) { + var scopeSymbolPathLength = scopeSymbolPath.length; + var externalSymbol = null; + if(scopeSymbolPath.length > 0 && scopeSymbolPath[scopeSymbolPathLength - 1].getType().isModuleType() && (scopeSymbolPath[scopeSymbolPathLength - 1]).isDynamic) { + if(scopeSymbolPathLength > 1 && scopeSymbolPath[scopeSymbolPathLength - 2].getType().isModuleType() && (scopeSymbolPath[scopeSymbolPathLength - 2]).isDynamic) { + var moduleType = scopeSymbolPath[scopeSymbolPathLength - 2].getType(); + externalSymbol = moduleType.findDynamicModuleName(this.type); + } + if(externalSymbol == null) { + var moduleType = scopeSymbolPath[scopeSymbolPathLength - 1].getType(); + externalSymbol = moduleType.findDynamicModuleName(this.type); + } + } + return externalSymbol; + }; + TypeSymbol.prototype.getDocComments = function () { + var comments = []; + if(this.declAST != null) { + comments = comments.concat(this.declAST.getDocComments()); + } + for(var i = 0; i < this.expansionsDeclAST.length; i++) { + comments = comments.concat(this.expansionsDeclAST[i].getDocComments()); + } + return comments; + }; + return TypeSymbol; + })(InferenceSymbol); + TypeScript.TypeSymbol = TypeSymbol; + var WithSymbol = (function (_super) { + __extends(WithSymbol, _super); + function WithSymbol(location, unitIndex, withType) { + _super.call(this, "with", location, 4, unitIndex, withType); + } + WithSymbol.prototype.isWith = function () { + return true; + }; + return WithSymbol; + })(TypeSymbol); + TypeScript.WithSymbol = WithSymbol; + var FieldSymbol = (function (_super) { + __extends(FieldSymbol, _super); + function FieldSymbol(name, location, unitIndex, canWrite, field) { + _super.call(this, name, location, name.length, unitIndex); + this.canWrite = canWrite; + this.field = field; + this.getter = null; + this.setter = null; + this.hasBeenEmitted = false; + this.name = name; + this.location = location; + } + FieldSymbol.prototype.kind = function () { + return TypeScript.SymbolKind.Field; + }; + FieldSymbol.prototype.writeable = function () { + return this.isAccessor() ? this.setter != null : this.canWrite; + }; + FieldSymbol.prototype.getType = function () { + return this.field.typeLink.type; + }; + FieldSymbol.prototype.getTypeNameEx = function (scope) { + return TypeScript.MemberName.create(this.field.typeLink.type ? this.field.typeLink.type.getScopedTypeNameEx(scope) : TypeScript.MemberName.create("any"), this.name + this.getOptionalNameString() + ": ", ""); + }; + FieldSymbol.prototype.isMember = function () { + return true; + }; + FieldSymbol.prototype.setType = function (type) { + this.field.typeLink.type = type; + }; + FieldSymbol.prototype.isAccessor = function () { + return this.getter != null || this.setter != null; + }; + FieldSymbol.prototype.isVariable = function () { + return true; + }; + FieldSymbol.prototype.toString = function () { + return this.getTypeNameEx(null).toString(); + }; + FieldSymbol.prototype.specializeType = function (pattern, replacement, checker) { + var rType = this.field.typeLink.type.specializeType(pattern, replacement, checker, false); + if(rType != this.field.typeLink.type) { + var fieldDef = new ValueLocation(); + var result = new FieldSymbol(this.name, 0, checker.locationInfo.unitIndex, this.canWrite, fieldDef); + result.flags = this.flags; + fieldDef.symbol = result; + fieldDef.typeLink = new TypeScript.TypeLink(); + result.setType(rType); + result.typeCheckStatus = TypeCheckStatus.Finished; + return result; + } else { + return this; + } + }; + FieldSymbol.prototype.getDocComments = function () { + if(this.getter != null || this.setter != null) { + var comments = []; + if(this.getter != null) { + comments = comments.concat(this.getter.getDocComments()); + } + if(this.setter != null) { + comments = comments.concat(this.setter.getDocComments()); + } + return comments; + } else if(this.declAST != null) { + return this.declAST.getDocComments(); + } + return []; + }; + return FieldSymbol; + })(InferenceSymbol); + TypeScript.FieldSymbol = FieldSymbol; + var ParameterSymbol = (function (_super) { + __extends(ParameterSymbol, _super); + function ParameterSymbol(name, location, unitIndex, parameter) { + _super.call(this, name, location, name.length, unitIndex); + this.parameter = parameter; + this.paramDocComment = null; + this.funcDecl = null; + this.argsOffset = (-1); + this.name = name; + this.location = location; + } + ParameterSymbol.prototype.kind = function () { + return TypeScript.SymbolKind.Parameter; + }; + ParameterSymbol.prototype.writeable = function () { + return true; + }; + ParameterSymbol.prototype.getType = function () { + return this.parameter.typeLink.type; + }; + ParameterSymbol.prototype.setType = function (type) { + this.parameter.typeLink.type = type; + }; + ParameterSymbol.prototype.isVariable = function () { + return true; + }; + ParameterSymbol.prototype.isOptional = function () { + if(this.parameter && this.parameter.symbol && this.parameter.symbol.declAST) { + return (this.parameter.symbol.declAST).isOptional; + } else { + return false; + } + }; + ParameterSymbol.prototype.getTypeNameEx = function (scope) { + return TypeScript.MemberName.create(this.getType().getScopedTypeNameEx(scope), this.name + (this.isOptional() ? "?" : "") + ": ", ""); + }; + ParameterSymbol.prototype.toString = function () { + return this.getTypeNameEx(null).toString(); + }; + ParameterSymbol.prototype.specializeType = function (pattern, replacement, checker) { + var rType = this.parameter.typeLink.type.specializeType(pattern, replacement, checker, false); + if(this.parameter.typeLink.type != rType) { + var paramDef = new ValueLocation(); + var result = new ParameterSymbol(this.name, 0, checker.locationInfo.unitIndex, paramDef); + paramDef.symbol = result; + result.setType(rType); + return result; + } else { + return this; + } + }; + ParameterSymbol.prototype.getParameterDocComments = function () { + if(!this.paramDocComment) { + var parameterComments = []; + if(this.funcDecl) { + var fncDocComments = this.funcDecl.getDocComments(); + var paramComment = TypeScript.Comment.getParameterDocCommentText(this.name, fncDocComments); + if(paramComment != "") { + parameterComments.push(paramComment); + } + } + var docComments = TypeScript.Comment.getDocCommentText(this.getDocComments()); + if(docComments != "") { + parameterComments.push(docComments); + } + this.paramDocComment = parameterComments.join("\n"); + } + return this.paramDocComment; + }; + ParameterSymbol.prototype.fullName = function () { + return this.name; + }; + return ParameterSymbol; + })(InferenceSymbol); + TypeScript.ParameterSymbol = ParameterSymbol; + var VariableSymbol = (function (_super) { + __extends(VariableSymbol, _super); + function VariableSymbol(name, location, unitIndex, variable) { + _super.call(this, name, location, name.length, unitIndex); + this.variable = variable; + } + VariableSymbol.prototype.kind = function () { + return TypeScript.SymbolKind.Variable; + }; + VariableSymbol.prototype.writeable = function () { + return true; + }; + VariableSymbol.prototype.getType = function () { + return this.variable.typeLink.type; + }; + VariableSymbol.prototype.getTypeNameEx = function (scope) { + return TypeScript.MemberName.create(this.getType().getScopedTypeNameEx(scope), this.name + ": ", ""); + }; + VariableSymbol.prototype.setType = function (type) { + this.variable.typeLink.type = type; + }; + VariableSymbol.prototype.isVariable = function () { + return true; + }; + return VariableSymbol; + })(InferenceSymbol); + TypeScript.VariableSymbol = VariableSymbol; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ScopedMembers = (function () { + function ScopedMembers(dualMembers) { + this.dualMembers = dualMembers; + this.allMembers = this.dualMembers; + this.publicMembers = this.dualMembers.primaryTable; + this.privateMembers = this.dualMembers.secondaryTable; + } + ScopedMembers.prototype.addPublicMember = function (key, data) { + return this.dualMembers.primaryTable.add(key, data); + }; + ScopedMembers.prototype.addPrivateMember = function (key, data) { + return this.dualMembers.secondaryTable.add(key, data); + }; + return ScopedMembers; + })(); + TypeScript.ScopedMembers = ScopedMembers; + (function (SymbolKind) { + SymbolKind._map = []; + SymbolKind._map[0] = "None"; + SymbolKind.None = 0; + SymbolKind._map[1] = "Type"; + SymbolKind.Type = 1; + SymbolKind._map[2] = "Field"; + SymbolKind.Field = 2; + SymbolKind._map[3] = "Parameter"; + SymbolKind.Parameter = 3; + SymbolKind._map[4] = "Variable"; + SymbolKind.Variable = 4; + })(TypeScript.SymbolKind || (TypeScript.SymbolKind = {})); + var SymbolKind = TypeScript.SymbolKind; + var SymbolScope = (function () { + function SymbolScope(container) { + this.container = container; + } + SymbolScope.prototype.printLabel = function () { + return "base"; + }; + SymbolScope.prototype.getAllSymbolNames = function (members) { + return [ + "please", + "implement", + "in", + "derived", + "classes" + ]; + }; + SymbolScope.prototype.getAllTypeSymbolNames = function (members) { + return [ + "please", + "implement", + "in", + "derived", + "classes" + ]; + }; + SymbolScope.prototype.getAllValueSymbolNames = function (members) { + return [ + "please", + "implement", + "in", + "derived", + "classes" + ]; + }; + SymbolScope.prototype.search = function (filter, name, publicOnly, typespace) { + return null; + }; + SymbolScope.prototype.findLocal = function (name, publicOnly, typespace) { + return null; + }; + SymbolScope.prototype.find = function (name, publicOnly, typespace) { + return null; + }; + SymbolScope.prototype.findImplementation = function (name, publicOnly, typespace) { + return null; + }; + SymbolScope.prototype.findAmbient = function (name, publicOnly, typespace) { + return null; + }; + SymbolScope.prototype.print = function (outfile) { + if(this.container) { + outfile.WriteLine(this.printLabel() + " scope with container: " + this.container.name + "..."); + } else { + outfile.WriteLine(this.printLabel() + " scope..."); + } + }; + SymbolScope.prototype.enter = function (container, ast, symbol, errorReporter, publicOnly, typespace, ambient) { + throw new Error("please implement in derived class"); + }; + SymbolScope.prototype.getTable = function () { + throw new Error("please implement in derived class"); + }; + return SymbolScope; + })(); + TypeScript.SymbolScope = SymbolScope; + function symbolCanBeUsed(sym, publicOnly) { + return publicOnly ? !(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Private) || (sym.declAST && sym.declAST.nodeType == TypeScript.NodeType.FuncDecl && TypeScript.hasFlag((sym.declAST).fncFlags, TypeScript.FncFlags.Private))) : true; + } + var SymbolAggregateScope = (function (_super) { + __extends(SymbolAggregateScope, _super); + function SymbolAggregateScope(container) { + _super.call(this, container); + this.valueCache = null; + this.valueImplCache = null; + this.valueAmbientCache = null; + this.typeCache = null; + this.typeImplCache = null; + this.typeAmbientCache = null; + this.parents = null; + this.container = container; + } + SymbolAggregateScope.prototype.printLabel = function () { + return "agg"; + }; + SymbolAggregateScope.prototype.search = function (filter, name, publicOnly, typespace) { + if(this.parents) { + for(var i = 0; i < this.parents.length; i++) { + var sym = this.parents[i].search(filter, name, publicOnly, typespace); + if(sym) { + if(filter.update(sym)) { + return sym; + } + } + } + } + return filter.result; + }; + SymbolAggregateScope.prototype.getAllSymbolNames = function (members) { + var result = []; + if(this.parents) { + for(var i = 0; i < this.parents.length; i++) { + var parentResult = this.parents[i].getAllSymbolNames(members); + if(parentResult) { + result = result.concat(parentResult); + } + } + } + return result; + }; + SymbolAggregateScope.prototype.getAllTypeSymbolNames = function (members) { + var result = []; + if(this.parents) { + for(var i = 0; i < this.parents.length; i++) { + var parentResult = this.parents[i].getAllTypeSymbolNames(members); + if(parentResult) { + result = result.concat(parentResult); + } + } + } + return result; + }; + SymbolAggregateScope.prototype.getAllValueSymbolNames = function (members) { + var result = []; + if(this.parents) { + for(var i = 0; i < this.parents.length; i++) { + var parentResult = this.parents[i].getAllValueSymbolNames(members); + if(parentResult) { + result = result.concat(parentResult); + } + } + } + return result; + }; + SymbolAggregateScope.prototype.print = function (outfile) { + _super.prototype.print.call(this, outfile); + if(this.parents) { + for(var i = 0; i < this.parents.length; i++) { + this.parents[i].print(outfile); + } + } + }; + SymbolAggregateScope.prototype.findImplementation = function (name, publicOnly, typespace) { + var sym = null; + var i = 0; + var implCache = this.valueImplCache; + if(typespace) { + implCache = this.typeImplCache; + } + if(implCache && ((sym = implCache.lookup(name)) != null) && (publicOnly ? !(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Private) || (sym.declAST && sym.declAST.nodeType == TypeScript.NodeType.FuncDecl && TypeScript.hasFlag((sym.declAST).fncFlags, TypeScript.FncFlags.Private))) : true)) { + return sym; + } + if(this.parents) { + for(i = 0; i < this.parents.length; i++) { + sym = this.parents[i].findImplementation(name, publicOnly, typespace); + if(sym) { + break; + } + } + } + if(implCache) { + if(typespace) { + this.typeImplCache = new TypeScript.StringHashTable(); + implCache = this.typeImplCache; + } else { + this.valueImplCache = new TypeScript.StringHashTable(); + implCache = this.valueImplCache; + } + } + implCache.add(name, sym); + return sym; + }; + SymbolAggregateScope.prototype.find = function (name, publicOnly, typespace) { + var sym = null; + var i = 0; + var cache = this.valueCache; + if(typespace) { + cache = this.typeCache; + } + if(cache && ((sym = cache.lookup(name)) != null) && (publicOnly ? !(TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.Private) || (sym.declAST && sym.declAST.nodeType == TypeScript.NodeType.FuncDecl && TypeScript.hasFlag((sym.declAST).fncFlags, TypeScript.FncFlags.Private))) : true)) { + return sym; + } + if(this.parents) { + for(i = 0; i < this.parents.length; i++) { + sym = this.parents[i].find(name, publicOnly, typespace); + if(sym) { + break; + } + } + } + if(cache == null) { + if(typespace) { + this.typeCache = new TypeScript.StringHashTable(); + cache = this.typeCache; + } else { + this.valueCache = new TypeScript.StringHashTable(); + cache = this.valueCache; + } + } + cache.add(name, sym); + return sym; + }; + SymbolAggregateScope.prototype.findAmbient = function (name, publicOnly, typespace) { + var sym = null; + var i = 0; + var cache = this.valueAmbientCache; + if(typespace) { + cache = this.typeAmbientCache; + } + if(cache && ((sym = cache.lookup(name)) != null)) { + return sym; + } + if(this.parents) { + for(i = 0; i < this.parents.length; i++) { + sym = this.parents[i].findAmbient(name, publicOnly, typespace); + if(sym) { + break; + } + } + } + if(cache == null) { + if(typespace) { + this.typeAmbientCache = new TypeScript.StringHashTable(); + cache = this.typeAmbientCache; + } else { + this.valueAmbientCache = new TypeScript.StringHashTable(); + cache = this.valueAmbientCache; + } + } + cache.add(name, sym); + return sym; + }; + SymbolAggregateScope.prototype.addParentScope = function (parent) { + if(this.parents == null) { + this.parents = new Array(); + } + this.parents[this.parents.length] = parent; + }; + return SymbolAggregateScope; + })(SymbolScope); + TypeScript.SymbolAggregateScope = SymbolAggregateScope; + var SymbolTableScope = (function (_super) { + __extends(SymbolTableScope, _super); + function SymbolTableScope(valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, container) { + _super.call(this, container); + this.valueMembers = valueMembers; + this.ambientValueMembers = ambientValueMembers; + this.enclosedTypes = enclosedTypes; + this.ambientEnclosedTypes = ambientEnclosedTypes; + this.container = container; + } + SymbolTableScope.prototype.printLabel = function () { + return "table"; + }; + SymbolTableScope.prototype.getAllSymbolNames = function (members) { + var result = this.getAllTypeSymbolNames(members); + return result.concat(this.getAllValueSymbolNames(members)); + }; + SymbolTableScope.prototype.getAllTypeSymbolNames = function (members) { + var result = []; + if(this.ambientEnclosedTypes) { + result = result.concat(this.ambientEnclosedTypes.allMembers.getAllKeys()); + } + if(this.enclosedTypes) { + result = result.concat(this.enclosedTypes.allMembers.getAllKeys()); + } + return result; + }; + SymbolTableScope.prototype.getAllValueSymbolNames = function (members) { + var result = []; + if(this.ambientValueMembers) { + result = result.concat(this.ambientValueMembers.allMembers.getAllKeys()); + } + if(this.valueMembers) { + result = result.concat(this.valueMembers.allMembers.getAllKeys()); + } + return result; + }; + SymbolTableScope.prototype.search = function (filter, name, publicOnly, typespace) { + var sym = this.find(name, publicOnly, typespace); + filter.update(sym); + return filter.result; + }; + SymbolTableScope.prototype.find = function (name, publicOnly, typespace) { + var table = null; + var ambientTable = null; + if(typespace) { + table = (this.enclosedTypes == null) ? null : publicOnly ? this.enclosedTypes.publicMembers : this.enclosedTypes.allMembers; + ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; + } else { + table = (this.valueMembers == null) ? null : publicOnly ? this.valueMembers.publicMembers : this.valueMembers.allMembers; + ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; + } + if(ambientTable) { + var s = ambientTable.lookup(name); + if(s) { + return s; + } + } + if(table) { + var s = table.lookup(name); + if(s) { + return s; + } + } + return null; + }; + SymbolTableScope.prototype.findAmbient = function (name, publicOnly, typespace) { + var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; + if(typespace) { + ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; + } + if(ambientTable) { + var s = ambientTable.lookup(name); + if(s) { + return s; + } + } + return null; + }; + SymbolTableScope.prototype.print = function (outfile) { + _super.prototype.print.call(this, outfile); + if(this.ambientValueMembers) { + this.ambientValueMembers.allMembers.map(function (key, sym, context) { + outfile.WriteLine(" " + key); + }, null); + } + if(this.valueMembers) { + this.valueMembers.allMembers.map(function (key, sym, context) { + outfile.WriteLine(" " + key); + }, null); + } + if(this.ambientEnclosedTypes) { + this.ambientEnclosedTypes.allMembers.map(function (key, sym, context) { + outfile.WriteLine(" " + key); + }, null); + } + if(this.enclosedTypes) { + this.enclosedTypes.allMembers.map(function (key, sym, context) { + outfile.WriteLine(" " + key); + }, null); + } + }; + SymbolTableScope.prototype.findImplementation = function (name, publicOnly, typespace) { + var sym = this.find(name, publicOnly, typespace); + if(sym) { + if(sym.kind() == SymbolKind.Type) { + var typeSym = sym; + if(!typeSym.type.hasImplementation()) { + sym = null; + } + } else if(sym.container) { + if(sym.container.kind() == SymbolKind.Type) { + var ctypeSym = sym.container; + if(!ctypeSym.type.hasImplementation()) { + sym = null; + } + } + } + } + return sym; + }; + SymbolTableScope.prototype.getTable = function () { + return this.valueMembers.publicMembers; + }; + return SymbolTableScope; + })(SymbolScope); + TypeScript.SymbolTableScope = SymbolTableScope; + var SymbolScopeBuilder = (function (_super) { + __extends(SymbolScopeBuilder, _super); + function SymbolScopeBuilder(valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, parent, container) { + _super.call(this, container); + this.valueMembers = valueMembers; + this.ambientValueMembers = ambientValueMembers; + this.enclosedTypes = enclosedTypes; + this.ambientEnclosedTypes = ambientEnclosedTypes; + this.parent = parent; + this.container = container; + } + SymbolScopeBuilder.prototype.printLabel = function () { + return "builder"; + }; + SymbolScopeBuilder.prototype.getAllSymbolNames = function (members) { + var result = this.getAllTypeSymbolNames(members); + return result.concat(this.getAllValueSymbolNames(members)); + }; + SymbolScopeBuilder.prototype.getAllTypeSymbolNames = function (members) { + var result = []; + if(this.ambientEnclosedTypes) { + result = result.concat(this.ambientEnclosedTypes.allMembers.getAllKeys()); + } + if(this.enclosedTypes) { + result = result.concat(this.enclosedTypes.allMembers.getAllKeys()); + } + if(!members && this.parent) { + var parentResult = this.parent.getAllTypeSymbolNames(members); + if(parentResult) { + result = result.concat(parentResult); + } + } + return result; + }; + SymbolScopeBuilder.prototype.getAllValueSymbolNames = function (members) { + var result = []; + if(this.ambientValueMembers) { + result = result.concat(this.ambientValueMembers.allMembers.getAllKeys()); + } + if(this.valueMembers) { + result = result.concat(this.valueMembers.allMembers.getAllKeys()); + } + if(!members && this.parent) { + var parentResult = this.parent.getAllValueSymbolNames(members); + if(parentResult) { + result = result.concat(parentResult); + } + } + return result; + }; + SymbolScopeBuilder.prototype.search = function (filter, name, publicOnly, typespace) { + var sym = null; + var table = (this.valueMembers == null) ? null : publicOnly ? this.valueMembers.publicMembers : this.valueMembers.allMembers; + var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; + if(typespace) { + table = (this.enclosedTypes == null) ? null : publicOnly ? this.enclosedTypes.publicMembers : this.enclosedTypes.allMembers; + ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; + } + if(ambientTable) { + if((sym = ambientTable.lookup(name)) != null) { + if(filter.update(sym)) { + return sym; + } + } + } + if(table) { + if((sym = table.lookup(name)) != null) { + if(filter.update(sym)) { + return sym; + } + } + } + if(this.parent) { + sym = this.parent.search(filter, name, publicOnly, typespace); + if(sym) { + if(filter.update(sym)) { + return sym; + } + } + } + return filter.result; + }; + SymbolScopeBuilder.prototype.print = function (outfile) { + _super.prototype.print.call(this, outfile); + if(this.ambientValueMembers) { + this.ambientValueMembers.allMembers.map(function (key, s, context) { + var sym = s; + outfile.WriteLine(" " + key); + }, null); + } + if(this.valueMembers) { + this.valueMembers.allMembers.map(function (key, s, context) { + var sym = s; + outfile.WriteLine(" " + key); + }, null); + } + if(this.ambientEnclosedTypes) { + this.ambientEnclosedTypes.allMembers.map(function (key, s, context) { + var sym = s; + outfile.WriteLine(" " + key); + }, null); + } + if(this.enclosedTypes) { + this.enclosedTypes.allMembers.map(function (key, s, context) { + var sym = s; + outfile.WriteLine(" " + key); + }, null); + } + if(this.parent) { + this.parent.print(outfile); + } + }; + SymbolScopeBuilder.prototype.find = function (name, publicOnly, typespace) { + var sym = null; + var table = (this.valueMembers == null) ? null : publicOnly ? this.valueMembers.publicMembers : this.valueMembers.allMembers; + var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; + if(typespace) { + table = (this.enclosedTypes == null) ? null : publicOnly ? this.enclosedTypes.publicMembers : this.enclosedTypes.allMembers; + ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; + } + if(ambientTable && ((sym = ambientTable.lookup(name)) != null)) { + return sym; + } + if(table && ((sym = table.lookup(name)) != null)) { + return sym; + } + if(this.parent) { + return this.parent.find(name, publicOnly, typespace); + } + return null; + }; + SymbolScopeBuilder.prototype.findAmbient = function (name, publicOnly, typespace) { + var sym = null; + var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; + if(typespace) { + ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; + } + if(ambientTable && ((sym = ambientTable.lookup(name)) != null)) { + return sym; + } + if(this.parent) { + return this.parent.findAmbient(name, publicOnly, typespace); + } + return null; + }; + SymbolScopeBuilder.prototype.findLocal = function (name, publicOnly, typespace) { + var sym = null; + var table = (this.valueMembers == null) ? null : publicOnly ? this.valueMembers.publicMembers : this.valueMembers.allMembers; + var ambientTable = (this.ambientValueMembers == null) ? null : publicOnly ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.allMembers; + if(typespace) { + table = (this.enclosedTypes == null) ? null : publicOnly ? this.enclosedTypes.publicMembers : this.enclosedTypes.allMembers; + ambientTable = (this.ambientEnclosedTypes == null) ? null : publicOnly ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.allMembers; + } + if(table) { + if((sym = table.lookup(name)) != null) { + if(sym) { + return sym; + } + } + } + if(ambientTable) { + if((sym = ambientTable.lookup(name)) != null) { + if(sym) { + return sym; + } + } + } + return null; + }; + SymbolScopeBuilder.prototype.enter = function (container, ast, symbol, errorReporter, insertAsPublic, typespace, ambient) { + var table = null; + if(ambient) { + if(typespace) { + table = (this.ambientEnclosedTypes == null) ? null : insertAsPublic ? this.ambientEnclosedTypes.publicMembers : this.ambientEnclosedTypes.privateMembers; + } else { + table = (this.ambientValueMembers == null) ? null : insertAsPublic ? this.ambientValueMembers.publicMembers : this.ambientValueMembers.privateMembers; + } + } else { + if(typespace) { + table = (this.enclosedTypes == null) ? null : insertAsPublic ? this.enclosedTypes.publicMembers : this.enclosedTypes.privateMembers; + } else { + table = (this.valueMembers == null) ? null : insertAsPublic ? this.valueMembers.publicMembers : this.valueMembers.privateMembers; + } + } + if(table) { + if(!table.add(symbol.name, symbol)) { + errorReporter.duplicateIdentifier(ast, symbol.name); + } + } else { + TypeScript.CompilerDiagnostics.Alert("YYYYY"); + } + symbol.container = container; + }; + SymbolScopeBuilder.prototype.getTable = function () { + return this.valueMembers.allMembers; + }; + return SymbolScopeBuilder; + })(SymbolScope); + TypeScript.SymbolScopeBuilder = SymbolScopeBuilder; + var FilteredSymbolScope = (function (_super) { + __extends(FilteredSymbolScope, _super); + function FilteredSymbolScope(scope, container, filter) { + _super.call(this, container); + this.scope = scope; + this.filter = filter; + } + FilteredSymbolScope.prototype.print = function (outfile) { + this.scope.print(outfile); + }; + FilteredSymbolScope.prototype.find = function (name, publicOnly, typespace) { + this.filter.reset(); + return this.scope.search(this.filter, name, publicOnly, typespace); + }; + FilteredSymbolScope.prototype.findLocal = function (name, publicOnly, typespace) { + return this.scope.findLocal(name, publicOnly, typespace); + }; + return FilteredSymbolScope; + })(SymbolScope); + TypeScript.FilteredSymbolScope = FilteredSymbolScope; + var FilteredSymbolScopeBuilder = (function (_super) { + __extends(FilteredSymbolScopeBuilder, _super); + function FilteredSymbolScopeBuilder(valueMembers, parent, container, filter) { + _super.call(this, valueMembers, null, null, null, parent, container); + this.filter = filter; + } + FilteredSymbolScopeBuilder.prototype.findLocal = function (name, publicOnly, typespace) { + var sym = _super.prototype.findLocal.call(this, name, publicOnly, typespace); + if(sym) { + if(!this.filter(sym)) { + return null; + } + } + return sym; + }; + FilteredSymbolScopeBuilder.prototype.search = function (filter, name, publicOnly, typespace) { + throw new Error("please implement"); + }; + FilteredSymbolScopeBuilder.prototype.find = function (name, publicOnly, typespace) { + var sym = _super.prototype.findLocal.call(this, name, publicOnly, typespace); + if(sym) { + if(!this.filter(sym)) { + return null; + } + } + return _super.prototype.find.call(this, name, publicOnly, typespace); + }; + return FilteredSymbolScopeBuilder; + })(SymbolScopeBuilder); + TypeScript.FilteredSymbolScopeBuilder = FilteredSymbolScopeBuilder; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (TokenID) { + TokenID._map = []; + TokenID._map[0] = "Any"; + TokenID.Any = 0; + TokenID._map[1] = "Bool"; + TokenID.Bool = 1; + TokenID._map[2] = "Break"; + TokenID.Break = 2; + TokenID._map[3] = "Case"; + TokenID.Case = 3; + TokenID._map[4] = "Catch"; + TokenID.Catch = 4; + TokenID._map[5] = "Class"; + TokenID.Class = 5; + TokenID._map[6] = "Const"; + TokenID.Const = 6; + TokenID._map[7] = "Continue"; + TokenID.Continue = 7; + TokenID._map[8] = "Debugger"; + TokenID.Debugger = 8; + TokenID._map[9] = "Default"; + TokenID.Default = 9; + TokenID._map[10] = "Delete"; + TokenID.Delete = 10; + TokenID._map[11] = "Do"; + TokenID.Do = 11; + TokenID._map[12] = "Else"; + TokenID.Else = 12; + TokenID._map[13] = "Enum"; + TokenID.Enum = 13; + TokenID._map[14] = "Export"; + TokenID.Export = 14; + TokenID._map[15] = "Extends"; + TokenID.Extends = 15; + TokenID._map[16] = "Declare"; + TokenID.Declare = 16; + TokenID._map[17] = "False"; + TokenID.False = 17; + TokenID._map[18] = "Finally"; + TokenID.Finally = 18; + TokenID._map[19] = "For"; + TokenID.For = 19; + TokenID._map[20] = "Function"; + TokenID.Function = 20; + TokenID._map[21] = "Constructor"; + TokenID.Constructor = 21; + TokenID._map[22] = "Get"; + TokenID.Get = 22; + TokenID._map[23] = "If"; + TokenID.If = 23; + TokenID._map[24] = "Implements"; + TokenID.Implements = 24; + TokenID._map[25] = "Import"; + TokenID.Import = 25; + TokenID._map[26] = "In"; + TokenID.In = 26; + TokenID._map[27] = "InstanceOf"; + TokenID.InstanceOf = 27; + TokenID._map[28] = "Interface"; + TokenID.Interface = 28; + TokenID._map[29] = "Let"; + TokenID.Let = 29; + TokenID._map[30] = "Module"; + TokenID.Module = 30; + TokenID._map[31] = "New"; + TokenID.New = 31; + TokenID._map[32] = "Number"; + TokenID.Number = 32; + TokenID._map[33] = "Null"; + TokenID.Null = 33; + TokenID._map[34] = "Package"; + TokenID.Package = 34; + TokenID._map[35] = "Private"; + TokenID.Private = 35; + TokenID._map[36] = "Protected"; + TokenID.Protected = 36; + TokenID._map[37] = "Public"; + TokenID.Public = 37; + TokenID._map[38] = "Return"; + TokenID.Return = 38; + TokenID._map[39] = "Set"; + TokenID.Set = 39; + TokenID._map[40] = "Static"; + TokenID.Static = 40; + TokenID._map[41] = "String"; + TokenID.String = 41; + TokenID._map[42] = "Super"; + TokenID.Super = 42; + TokenID._map[43] = "Switch"; + TokenID.Switch = 43; + TokenID._map[44] = "This"; + TokenID.This = 44; + TokenID._map[45] = "Throw"; + TokenID.Throw = 45; + TokenID._map[46] = "True"; + TokenID.True = 46; + TokenID._map[47] = "Try"; + TokenID.Try = 47; + TokenID._map[48] = "TypeOf"; + TokenID.TypeOf = 48; + TokenID._map[49] = "Var"; + TokenID.Var = 49; + TokenID._map[50] = "Void"; + TokenID.Void = 50; + TokenID._map[51] = "With"; + TokenID.With = 51; + TokenID._map[52] = "While"; + TokenID.While = 52; + TokenID._map[53] = "Yield"; + TokenID.Yield = 53; + TokenID._map[54] = "Semicolon"; + TokenID.Semicolon = 54; + TokenID._map[55] = "OpenParen"; + TokenID.OpenParen = 55; + TokenID._map[56] = "CloseParen"; + TokenID.CloseParen = 56; + TokenID._map[57] = "OpenBracket"; + TokenID.OpenBracket = 57; + TokenID._map[58] = "CloseBracket"; + TokenID.CloseBracket = 58; + TokenID._map[59] = "OpenBrace"; + TokenID.OpenBrace = 59; + TokenID._map[60] = "CloseBrace"; + TokenID.CloseBrace = 60; + TokenID._map[61] = "Comma"; + TokenID.Comma = 61; + TokenID._map[62] = "Equals"; + TokenID.Equals = 62; + TokenID._map[63] = "PlusEquals"; + TokenID.PlusEquals = 63; + TokenID._map[64] = "MinusEquals"; + TokenID.MinusEquals = 64; + TokenID._map[65] = "AsteriskEquals"; + TokenID.AsteriskEquals = 65; + TokenID._map[66] = "SlashEquals"; + TokenID.SlashEquals = 66; + TokenID._map[67] = "PercentEquals"; + TokenID.PercentEquals = 67; + TokenID._map[68] = "AmpersandEquals"; + TokenID.AmpersandEquals = 68; + TokenID._map[69] = "CaretEquals"; + TokenID.CaretEquals = 69; + TokenID._map[70] = "BarEquals"; + TokenID.BarEquals = 70; + TokenID._map[71] = "LessThanLessThanEquals"; + TokenID.LessThanLessThanEquals = 71; + TokenID._map[72] = "GreaterThanGreaterThanEquals"; + TokenID.GreaterThanGreaterThanEquals = 72; + TokenID._map[73] = "GreaterThanGreaterThanGreaterThanEquals"; + TokenID.GreaterThanGreaterThanGreaterThanEquals = 73; + TokenID._map[74] = "Question"; + TokenID.Question = 74; + TokenID._map[75] = "Colon"; + TokenID.Colon = 75; + TokenID._map[76] = "BarBar"; + TokenID.BarBar = 76; + TokenID._map[77] = "AmpersandAmpersand"; + TokenID.AmpersandAmpersand = 77; + TokenID._map[78] = "Bar"; + TokenID.Bar = 78; + TokenID._map[79] = "Caret"; + TokenID.Caret = 79; + TokenID._map[80] = "And"; + TokenID.And = 80; + TokenID._map[81] = "EqualsEquals"; + TokenID.EqualsEquals = 81; + TokenID._map[82] = "ExclamationEquals"; + TokenID.ExclamationEquals = 82; + TokenID._map[83] = "EqualsEqualsEquals"; + TokenID.EqualsEqualsEquals = 83; + TokenID._map[84] = "ExclamationEqualsEquals"; + TokenID.ExclamationEqualsEquals = 84; + TokenID._map[85] = "LessThan"; + TokenID.LessThan = 85; + TokenID._map[86] = "LessThanEquals"; + TokenID.LessThanEquals = 86; + TokenID._map[87] = "GreaterThan"; + TokenID.GreaterThan = 87; + TokenID._map[88] = "GreaterThanEquals"; + TokenID.GreaterThanEquals = 88; + TokenID._map[89] = "LessThanLessThan"; + TokenID.LessThanLessThan = 89; + TokenID._map[90] = "GreaterThanGreaterThan"; + TokenID.GreaterThanGreaterThan = 90; + TokenID._map[91] = "GreaterThanGreaterThanGreaterThan"; + TokenID.GreaterThanGreaterThanGreaterThan = 91; + TokenID._map[92] = "Plus"; + TokenID.Plus = 92; + TokenID._map[93] = "Minus"; + TokenID.Minus = 93; + TokenID._map[94] = "Asterisk"; + TokenID.Asterisk = 94; + TokenID._map[95] = "Slash"; + TokenID.Slash = 95; + TokenID._map[96] = "Percent"; + TokenID.Percent = 96; + TokenID._map[97] = "Tilde"; + TokenID.Tilde = 97; + TokenID._map[98] = "Exclamation"; + TokenID.Exclamation = 98; + TokenID._map[99] = "PlusPlus"; + TokenID.PlusPlus = 99; + TokenID._map[100] = "MinusMinus"; + TokenID.MinusMinus = 100; + TokenID._map[101] = "Dot"; + TokenID.Dot = 101; + TokenID._map[102] = "DotDotDot"; + TokenID.DotDotDot = 102; + TokenID._map[103] = "Error"; + TokenID.Error = 103; + TokenID._map[104] = "EndOfFile"; + TokenID.EndOfFile = 104; + TokenID._map[105] = "EqualsGreaterThan"; + TokenID.EqualsGreaterThan = 105; + TokenID._map[106] = "Identifier"; + TokenID.Identifier = 106; + TokenID._map[107] = "StringLiteral"; + TokenID.StringLiteral = 107; + TokenID._map[108] = "RegularExpressionLiteral"; + TokenID.RegularExpressionLiteral = 108; + TokenID._map[109] = "NumberLiteral"; + TokenID.NumberLiteral = 109; + TokenID._map[110] = "Whitespace"; + TokenID.Whitespace = 110; + TokenID._map[111] = "Comment"; + TokenID.Comment = 111; + TokenID._map[112] = "Lim"; + TokenID.Lim = 112; + TokenID.LimFixed = TokenID.EqualsGreaterThan; + TokenID.LimKeyword = TokenID.Yield; + })(TypeScript.TokenID || (TypeScript.TokenID = {})); + var TokenID = TypeScript.TokenID; + TypeScript.tokenTable = new Array(); + TypeScript.nodeTypeTable = new Array(); + TypeScript.nodeTypeToTokTable = new Array(); + TypeScript.noRegexTable = new Array(); + TypeScript.noRegexTable[TokenID.Identifier] = true; + TypeScript.noRegexTable[TokenID.StringLiteral] = true; + TypeScript.noRegexTable[TokenID.NumberLiteral] = true; + TypeScript.noRegexTable[TokenID.RegularExpressionLiteral] = true; + TypeScript.noRegexTable[TokenID.This] = true; + TypeScript.noRegexTable[TokenID.PlusPlus] = true; + TypeScript.noRegexTable[TokenID.MinusMinus] = true; + TypeScript.noRegexTable[TokenID.CloseParen] = true; + TypeScript.noRegexTable[TokenID.CloseBracket] = true; + TypeScript.noRegexTable[TokenID.CloseBrace] = true; + TypeScript.noRegexTable[TokenID.True] = true; + TypeScript.noRegexTable[TokenID.False] = true; + (function (OperatorPrecedence) { + OperatorPrecedence._map = []; + OperatorPrecedence._map[0] = "None"; + OperatorPrecedence.None = 0; + OperatorPrecedence._map[1] = "Comma"; + OperatorPrecedence.Comma = 1; + OperatorPrecedence._map[2] = "Assignment"; + OperatorPrecedence.Assignment = 2; + OperatorPrecedence._map[3] = "Conditional"; + OperatorPrecedence.Conditional = 3; + OperatorPrecedence._map[4] = "LogicalOr"; + OperatorPrecedence.LogicalOr = 4; + OperatorPrecedence._map[5] = "LogicalAnd"; + OperatorPrecedence.LogicalAnd = 5; + OperatorPrecedence._map[6] = "BitwiseOr"; + OperatorPrecedence.BitwiseOr = 6; + OperatorPrecedence._map[7] = "BitwiseExclusiveOr"; + OperatorPrecedence.BitwiseExclusiveOr = 7; + OperatorPrecedence._map[8] = "BitwiseAnd"; + OperatorPrecedence.BitwiseAnd = 8; + OperatorPrecedence._map[9] = "Equality"; + OperatorPrecedence.Equality = 9; + OperatorPrecedence._map[10] = "Relational"; + OperatorPrecedence.Relational = 10; + OperatorPrecedence._map[11] = "Shift"; + OperatorPrecedence.Shift = 11; + OperatorPrecedence._map[12] = "Additive"; + OperatorPrecedence.Additive = 12; + OperatorPrecedence._map[13] = "Multiplicative"; + OperatorPrecedence.Multiplicative = 13; + OperatorPrecedence._map[14] = "Unary"; + OperatorPrecedence.Unary = 14; + OperatorPrecedence._map[15] = "Lim"; + OperatorPrecedence.Lim = 15; + })(TypeScript.OperatorPrecedence || (TypeScript.OperatorPrecedence = {})); + var OperatorPrecedence = TypeScript.OperatorPrecedence; + (function (Reservation) { + Reservation._map = []; + Reservation.None = 0; + Reservation.Javascript = 1; + Reservation.JavascriptFuture = 2; + Reservation.TypeScript = 4; + Reservation.JavascriptFutureStrict = 8; + Reservation.TypeScriptAndJS = Reservation.Javascript | Reservation.TypeScript; + Reservation.TypeScriptAndJSFuture = Reservation.JavascriptFuture | Reservation.TypeScript; + Reservation.TypeScriptAndJSFutureStrict = Reservation.JavascriptFutureStrict | Reservation.TypeScript; + })(TypeScript.Reservation || (TypeScript.Reservation = {})); + var Reservation = TypeScript.Reservation; + var TokenInfo = (function () { + function TokenInfo(tokenId, reservation, binopPrecedence, binopNodeType, unopPrecedence, unopNodeType, text, ers) { + this.tokenId = tokenId; + this.reservation = reservation; + this.binopPrecedence = binopPrecedence; + this.binopNodeType = binopNodeType; + this.unopPrecedence = unopPrecedence; + this.unopNodeType = unopNodeType; + this.text = text; + this.ers = ers; + } + return TokenInfo; + })(); + TypeScript.TokenInfo = TokenInfo; + function setTokenInfo(tokenId, reservation, binopPrecedence, binopNodeType, unopPrecedence, unopNodeType, text, ers) { + if(tokenId !== undefined) { + TypeScript.tokenTable[tokenId] = new TokenInfo(tokenId, reservation, binopPrecedence, binopNodeType, unopPrecedence, unopNodeType, text, ers); + if(binopNodeType != TypeScript.NodeType.None) { + TypeScript.nodeTypeTable[binopNodeType] = text; + TypeScript.nodeTypeToTokTable[binopNodeType] = tokenId; + } + if(unopNodeType != TypeScript.NodeType.None) { + TypeScript.nodeTypeTable[unopNodeType] = text; + } + } + } + setTokenInfo(TokenID.Any, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "any", TypeScript.ErrorRecoverySet.PrimType); + setTokenInfo(TokenID.Bool, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "bool", TypeScript.ErrorRecoverySet.PrimType); + setTokenInfo(TokenID.Break, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "break", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.Case, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "case", TypeScript.ErrorRecoverySet.SCase); + setTokenInfo(TokenID.Catch, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "catch", TypeScript.ErrorRecoverySet.Catch); + setTokenInfo(TokenID.Class, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "class", TypeScript.ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.Const, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "const", TypeScript.ErrorRecoverySet.Var); + setTokenInfo(TokenID.Continue, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "continue", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.Debugger, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.Debugger, "debugger", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.Default, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "default", TypeScript.ErrorRecoverySet.SCase); + setTokenInfo(TokenID.Delete, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.Delete, "delete", TypeScript.ErrorRecoverySet.Prefix); + setTokenInfo(TokenID.Do, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "do", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.Else, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "else", TypeScript.ErrorRecoverySet.Else); + setTokenInfo(TokenID.Enum, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "enum", TypeScript.ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.Export, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "export", TypeScript.ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.Extends, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "extends", TypeScript.ErrorRecoverySet.None); + setTokenInfo(TokenID.Declare, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "declare", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.False, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "false", TypeScript.ErrorRecoverySet.RLit); + setTokenInfo(TokenID.Finally, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "finally", TypeScript.ErrorRecoverySet.Catch); + setTokenInfo(TokenID.For, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "for", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.Function, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "function", TypeScript.ErrorRecoverySet.Func); + setTokenInfo(TokenID.Constructor, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "constructor", TypeScript.ErrorRecoverySet.Func); + setTokenInfo(TokenID.Get, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "get", TypeScript.ErrorRecoverySet.Func); + setTokenInfo(TokenID.Set, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "set", TypeScript.ErrorRecoverySet.Func); + setTokenInfo(TokenID.If, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "if", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.Implements, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "implements", TypeScript.ErrorRecoverySet.None); + setTokenInfo(TokenID.Import, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "import", TypeScript.ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.In, Reservation.TypeScriptAndJS, OperatorPrecedence.Relational, TypeScript.NodeType.In, OperatorPrecedence.None, TypeScript.NodeType.None, "in", TypeScript.ErrorRecoverySet.None); + setTokenInfo(TokenID.InstanceOf, Reservation.TypeScriptAndJS, OperatorPrecedence.Relational, TypeScript.NodeType.InstOf, OperatorPrecedence.None, TypeScript.NodeType.None, "instanceof", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.Interface, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "interface", TypeScript.ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.Let, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "let", TypeScript.ErrorRecoverySet.None); + setTokenInfo(TokenID.Module, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "module", TypeScript.ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.New, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "new", TypeScript.ErrorRecoverySet.PreOp); + setTokenInfo(TokenID.Number, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "number", TypeScript.ErrorRecoverySet.PrimType); + setTokenInfo(TokenID.Null, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "null", TypeScript.ErrorRecoverySet.RLit); + setTokenInfo(TokenID.Package, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "package", TypeScript.ErrorRecoverySet.None); + setTokenInfo(TokenID.Private, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "private", TypeScript.ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.Protected, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "protected", TypeScript.ErrorRecoverySet.None); + setTokenInfo(TokenID.Public, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "public", TypeScript.ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.Return, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "return", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.Static, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "static", TypeScript.ErrorRecoverySet.None); + setTokenInfo(TokenID.String, Reservation.TypeScript, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "string", TypeScript.ErrorRecoverySet.PrimType); + setTokenInfo(TokenID.Super, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "super", TypeScript.ErrorRecoverySet.RLit); + setTokenInfo(TokenID.Switch, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "switch", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.This, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "this", TypeScript.ErrorRecoverySet.RLit); + setTokenInfo(TokenID.Throw, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "throw", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.True, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "true", TypeScript.ErrorRecoverySet.RLit); + setTokenInfo(TokenID.Try, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "try", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.TypeOf, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.Typeof, "typeof", TypeScript.ErrorRecoverySet.Prefix); + setTokenInfo(TokenID.Var, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "var", TypeScript.ErrorRecoverySet.Var); + setTokenInfo(TokenID.Void, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.Void, "void", TypeScript.ErrorRecoverySet.Prefix); + setTokenInfo(TokenID.With, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.With, "with", TypeScript.ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.While, Reservation.TypeScriptAndJS, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "while", TypeScript.ErrorRecoverySet.While); + setTokenInfo(TokenID.Yield, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "yield", TypeScript.ErrorRecoverySet.None); + setTokenInfo(TokenID.Identifier, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "identifier", TypeScript.ErrorRecoverySet.ID); + setTokenInfo(TokenID.NumberLiteral, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "numberLiteral", TypeScript.ErrorRecoverySet.Literal); + setTokenInfo(TokenID.RegularExpressionLiteral, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "regex", TypeScript.ErrorRecoverySet.RegExp); + setTokenInfo(TokenID.StringLiteral, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "qstring", TypeScript.ErrorRecoverySet.Literal); + setTokenInfo(TokenID.Semicolon, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, ";", TypeScript.ErrorRecoverySet.SColon); + setTokenInfo(TokenID.CloseParen, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, ")", TypeScript.ErrorRecoverySet.RParen); + setTokenInfo(TokenID.CloseBracket, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "]", TypeScript.ErrorRecoverySet.RBrack); + setTokenInfo(TokenID.OpenBrace, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "{", TypeScript.ErrorRecoverySet.LCurly); + setTokenInfo(TokenID.CloseBrace, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "}", TypeScript.ErrorRecoverySet.RCurly); + setTokenInfo(TokenID.DotDotDot, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "...", TypeScript.ErrorRecoverySet.None); + setTokenInfo(TokenID.Comma, Reservation.None, OperatorPrecedence.Comma, TypeScript.NodeType.Comma, OperatorPrecedence.None, TypeScript.NodeType.None, ",", TypeScript.ErrorRecoverySet.Comma); + setTokenInfo(TokenID.Equals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.Asg, OperatorPrecedence.None, TypeScript.NodeType.None, "=", TypeScript.ErrorRecoverySet.Asg); + setTokenInfo(TokenID.PlusEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgAdd, OperatorPrecedence.None, TypeScript.NodeType.None, "+=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.MinusEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgSub, OperatorPrecedence.None, TypeScript.NodeType.None, "-=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.AsteriskEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgMul, OperatorPrecedence.None, TypeScript.NodeType.None, "*=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.SlashEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgDiv, OperatorPrecedence.None, TypeScript.NodeType.None, "/=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.PercentEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgMod, OperatorPrecedence.None, TypeScript.NodeType.None, "%=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.AmpersandEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgAnd, OperatorPrecedence.None, TypeScript.NodeType.None, "&=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.CaretEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgXor, OperatorPrecedence.None, TypeScript.NodeType.None, "^=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.BarEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgOr, OperatorPrecedence.None, TypeScript.NodeType.None, "|=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.LessThanLessThanEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgLsh, OperatorPrecedence.None, TypeScript.NodeType.None, "<<=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.GreaterThanGreaterThanEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgRsh, OperatorPrecedence.None, TypeScript.NodeType.None, ">>=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.GreaterThanGreaterThanGreaterThanEquals, Reservation.None, OperatorPrecedence.Assignment, TypeScript.NodeType.AsgRs2, OperatorPrecedence.None, TypeScript.NodeType.None, ">>>=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.Question, Reservation.None, OperatorPrecedence.Conditional, TypeScript.NodeType.ConditionalExpression, OperatorPrecedence.None, TypeScript.NodeType.None, "?", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.Colon, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, ":", TypeScript.ErrorRecoverySet.Colon); + setTokenInfo(TokenID.BarBar, Reservation.None, OperatorPrecedence.LogicalOr, TypeScript.NodeType.LogOr, OperatorPrecedence.None, TypeScript.NodeType.None, "||", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.AmpersandAmpersand, Reservation.None, OperatorPrecedence.LogicalAnd, TypeScript.NodeType.LogAnd, OperatorPrecedence.None, TypeScript.NodeType.None, "&&", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.Bar, Reservation.None, OperatorPrecedence.BitwiseOr, TypeScript.NodeType.Or, OperatorPrecedence.None, TypeScript.NodeType.None, "|", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.Caret, Reservation.None, OperatorPrecedence.BitwiseExclusiveOr, TypeScript.NodeType.Xor, OperatorPrecedence.None, TypeScript.NodeType.None, "^", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.And, Reservation.None, OperatorPrecedence.BitwiseAnd, TypeScript.NodeType.And, OperatorPrecedence.None, TypeScript.NodeType.None, "&", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.EqualsEquals, Reservation.None, OperatorPrecedence.Equality, TypeScript.NodeType.Eq, OperatorPrecedence.None, TypeScript.NodeType.None, "==", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.ExclamationEquals, Reservation.None, OperatorPrecedence.Equality, TypeScript.NodeType.Ne, OperatorPrecedence.None, TypeScript.NodeType.None, "!=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.EqualsEqualsEquals, Reservation.None, OperatorPrecedence.Equality, TypeScript.NodeType.Eqv, OperatorPrecedence.None, TypeScript.NodeType.None, "===", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.ExclamationEqualsEquals, Reservation.None, OperatorPrecedence.Equality, TypeScript.NodeType.NEqv, OperatorPrecedence.None, TypeScript.NodeType.None, "!==", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.LessThan, Reservation.None, OperatorPrecedence.Relational, TypeScript.NodeType.Lt, OperatorPrecedence.None, TypeScript.NodeType.None, "<", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.LessThanEquals, Reservation.None, OperatorPrecedence.Relational, TypeScript.NodeType.Le, OperatorPrecedence.None, TypeScript.NodeType.None, "<=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.GreaterThan, Reservation.None, OperatorPrecedence.Relational, TypeScript.NodeType.Gt, OperatorPrecedence.None, TypeScript.NodeType.None, ">", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.GreaterThanEquals, Reservation.None, OperatorPrecedence.Relational, TypeScript.NodeType.Ge, OperatorPrecedence.None, TypeScript.NodeType.None, ">=", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.LessThanLessThan, Reservation.None, OperatorPrecedence.Shift, TypeScript.NodeType.Lsh, OperatorPrecedence.None, TypeScript.NodeType.None, "<<", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.GreaterThanGreaterThan, Reservation.None, OperatorPrecedence.Shift, TypeScript.NodeType.Rsh, OperatorPrecedence.None, TypeScript.NodeType.None, ">>", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.GreaterThanGreaterThanGreaterThan, Reservation.None, OperatorPrecedence.Shift, TypeScript.NodeType.Rs2, OperatorPrecedence.None, TypeScript.NodeType.None, ">>>", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.Plus, Reservation.None, OperatorPrecedence.Additive, TypeScript.NodeType.Add, OperatorPrecedence.Unary, TypeScript.NodeType.Pos, "+", TypeScript.ErrorRecoverySet.AddOp); + setTokenInfo(TokenID.Minus, Reservation.None, OperatorPrecedence.Additive, TypeScript.NodeType.Sub, OperatorPrecedence.Unary, TypeScript.NodeType.Neg, "-", TypeScript.ErrorRecoverySet.AddOp); + setTokenInfo(TokenID.Asterisk, Reservation.None, OperatorPrecedence.Multiplicative, TypeScript.NodeType.Mul, OperatorPrecedence.None, TypeScript.NodeType.None, "*", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.Slash, Reservation.None, OperatorPrecedence.Multiplicative, TypeScript.NodeType.Div, OperatorPrecedence.None, TypeScript.NodeType.None, "/", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.Percent, Reservation.None, OperatorPrecedence.Multiplicative, TypeScript.NodeType.Mod, OperatorPrecedence.None, TypeScript.NodeType.None, "%", TypeScript.ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.Tilde, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.Not, "~", TypeScript.ErrorRecoverySet.PreOp); + setTokenInfo(TokenID.Exclamation, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.LogNot, "!", TypeScript.ErrorRecoverySet.PreOp); + setTokenInfo(TokenID.PlusPlus, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.IncPre, "++", TypeScript.ErrorRecoverySet.PreOp); + setTokenInfo(TokenID.MinusMinus, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.Unary, TypeScript.NodeType.DecPre, "--", TypeScript.ErrorRecoverySet.PreOp); + setTokenInfo(TokenID.OpenParen, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "(", TypeScript.ErrorRecoverySet.LParen); + setTokenInfo(TokenID.OpenBracket, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "[", TypeScript.ErrorRecoverySet.LBrack); + setTokenInfo(TokenID.Dot, Reservation.None, OperatorPrecedence.Unary, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, ".", TypeScript.ErrorRecoverySet.Dot); + setTokenInfo(TokenID.EndOfFile, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "", TypeScript.ErrorRecoverySet.EOF); + setTokenInfo(TokenID.EqualsGreaterThan, Reservation.None, OperatorPrecedence.None, TypeScript.NodeType.None, OperatorPrecedence.None, TypeScript.NodeType.None, "=>", TypeScript.ErrorRecoverySet.None); + function lookupToken(tokenId) { + return TypeScript.tokenTable[tokenId]; + } + TypeScript.lookupToken = lookupToken; + (function (TokenClass) { + TokenClass._map = []; + TokenClass._map[0] = "Punctuation"; + TokenClass.Punctuation = 0; + TokenClass._map[1] = "Keyword"; + TokenClass.Keyword = 1; + TokenClass._map[2] = "Operator"; + TokenClass.Operator = 2; + TokenClass._map[3] = "Comment"; + TokenClass.Comment = 3; + TokenClass._map[4] = "Whitespace"; + TokenClass.Whitespace = 4; + TokenClass._map[5] = "Identifier"; + TokenClass.Identifier = 5; + TokenClass._map[6] = "NumberLiteral"; + TokenClass.NumberLiteral = 6; + TokenClass._map[7] = "StringLiteral"; + TokenClass.StringLiteral = 7; + TokenClass._map[8] = "RegExpLiteral"; + TokenClass.RegExpLiteral = 8; + })(TypeScript.TokenClass || (TypeScript.TokenClass = {})); + var TokenClass = TypeScript.TokenClass; + var SavedToken = (function () { + function SavedToken(tok, minChar, limChar) { + this.tok = tok; + this.minChar = minChar; + this.limChar = limChar; + } + return SavedToken; + })(); + TypeScript.SavedToken = SavedToken; + var Token = (function () { + function Token(tokenId) { + this.tokenId = tokenId; + } + Token.prototype.toString = function () { + return "token: " + this.tokenId + " " + this.getText() + " (" + (TokenID)._map[this.tokenId] + ")"; + }; + Token.prototype.print = function (line, outfile) { + outfile.WriteLine(this.toString() + ",on line" + line); + }; + Token.prototype.getText = function () { + return TypeScript.tokenTable[this.tokenId].text; + }; + Token.prototype.classification = function () { + if(this.tokenId <= TokenID.LimKeyword) { + return TokenClass.Keyword; + } else { + var tokenInfo = lookupToken(this.tokenId); + if(tokenInfo != undefined) { + if((tokenInfo.unopNodeType != TypeScript.NodeType.None) || (tokenInfo.binopNodeType != TypeScript.NodeType.None)) { + return TokenClass.Operator; + } + } + } + return TokenClass.Punctuation; + }; + return Token; + })(); + TypeScript.Token = Token; + var NumberLiteralToken = (function (_super) { + __extends(NumberLiteralToken, _super); + function NumberLiteralToken(value, text) { + _super.call(this, TokenID.NumberLiteral); + this.value = value; + this.text = text; + } + NumberLiteralToken.prototype.getText = function () { + return this.text; + }; + NumberLiteralToken.prototype.classification = function () { + return TokenClass.NumberLiteral; + }; + return NumberLiteralToken; + })(Token); + TypeScript.NumberLiteralToken = NumberLiteralToken; + var StringLiteralToken = (function (_super) { + __extends(StringLiteralToken, _super); + function StringLiteralToken(value) { + _super.call(this, TokenID.StringLiteral); + this.value = value; + } + StringLiteralToken.prototype.getText = function () { + return this.value; + }; + StringLiteralToken.prototype.classification = function () { + return TokenClass.StringLiteral; + }; + return StringLiteralToken; + })(Token); + TypeScript.StringLiteralToken = StringLiteralToken; + var IdentifierToken = (function (_super) { + __extends(IdentifierToken, _super); + function IdentifierToken(value, hasEscapeSequence) { + _super.call(this, TokenID.Identifier); + this.value = value; + this.hasEscapeSequence = hasEscapeSequence; + } + IdentifierToken.prototype.getText = function () { + return this.value; + }; + IdentifierToken.prototype.classification = function () { + return TokenClass.Identifier; + }; + return IdentifierToken; + })(Token); + TypeScript.IdentifierToken = IdentifierToken; + var WhitespaceToken = (function (_super) { + __extends(WhitespaceToken, _super); + function WhitespaceToken(tokenId, value) { + _super.call(this, tokenId); + this.value = value; + } + WhitespaceToken.prototype.getText = function () { + return this.value; + }; + WhitespaceToken.prototype.classification = function () { + return TokenClass.Whitespace; + }; + return WhitespaceToken; + })(Token); + TypeScript.WhitespaceToken = WhitespaceToken; + var CommentToken = (function (_super) { + __extends(CommentToken, _super); + function CommentToken(tokenID, value, isBlock, startPos, line, endsLine) { + _super.call(this, tokenID); + this.value = value; + this.isBlock = isBlock; + this.startPos = startPos; + this.line = line; + this.endsLine = endsLine; + } + CommentToken.prototype.getText = function () { + return this.value; + }; + CommentToken.prototype.classification = function () { + return TokenClass.Comment; + }; + return CommentToken; + })(Token); + TypeScript.CommentToken = CommentToken; + var RegularExpressionLiteralToken = (function (_super) { + __extends(RegularExpressionLiteralToken, _super); + function RegularExpressionLiteralToken(text) { + _super.call(this, TokenID.RegularExpressionLiteral); + this.text = text; + } + RegularExpressionLiteralToken.prototype.getText = function () { + return this.text; + }; + RegularExpressionLiteralToken.prototype.classification = function () { + return TokenClass.RegExpLiteral; + }; + return RegularExpressionLiteralToken; + })(Token); + TypeScript.RegularExpressionLiteralToken = RegularExpressionLiteralToken; + TypeScript.staticTokens = new Array(); + function initializeStaticTokens() { + for(var i = 0; i <= TokenID.LimFixed; i++) { + TypeScript.staticTokens[i] = new Token(i); + } + } + TypeScript.initializeStaticTokens = initializeStaticTokens; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ArrayCache = (function () { + function ArrayCache() { + this.arrayBase = null; + } + ArrayCache.prototype.specialize = function (arrInstType, checker) { + if(this.arrayBase == null) { + this.arrayBase = arrInstType.specializeType(checker.wildElm.type, this.arrayType.elementType, checker, true); + } + return this.arrayBase; + }; + return ArrayCache; + })(); + TypeScript.ArrayCache = ArrayCache; + var TypeComparisonInfo = (function () { + function TypeComparisonInfo() { + this.onlyCaptureFirstError = false; + this.flags = TypeScript.TypeRelationshipFlags.SuccessfulComparison; + this.message = ""; + } + TypeComparisonInfo.prototype.addMessageToFront = function (message) { + if(!this.onlyCaptureFirstError) { + this.message = this.message ? message + ":\n\t" + this.message : message; + } else { + this.setMessage(message); + } + }; + TypeComparisonInfo.prototype.setMessage = function (message) { + this.message = message; + }; + return TypeComparisonInfo; + })(); + TypeScript.TypeComparisonInfo = TypeComparisonInfo; + (function (TypeCheckCollectionMode) { + TypeCheckCollectionMode._map = []; + TypeCheckCollectionMode._map[0] = "Resident"; + TypeCheckCollectionMode.Resident = 0; + TypeCheckCollectionMode._map[1] = "Transient"; + TypeCheckCollectionMode.Transient = 1; + })(TypeScript.TypeCheckCollectionMode || (TypeScript.TypeCheckCollectionMode = {})); + var TypeCheckCollectionMode = TypeScript.TypeCheckCollectionMode; + var PersistentGlobalTypeState = (function () { + function PersistentGlobalTypeState(errorReporter) { + this.errorReporter = errorReporter; + this.importedGlobalsTable = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + this.importedGlobalsTypeTable = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + this.globals = null; + this.globalTypes = null; + this.ambientGlobals = null; + this.ambientGlobalTypes = null; + this.residentGlobalValues = new TypeScript.StringHashTable(); + this.residentGlobalTypes = new TypeScript.StringHashTable(); + this.residentGlobalAmbientValues = new TypeScript.StringHashTable(); + this.residentGlobalAmbientTypes = new TypeScript.StringHashTable(); + this.residentTypeCheck = true; + this.mod = null; + this.gloMod = null; + this.wildElm = null; + this.importedGlobals = new TypeScript.SymbolScopeBuilder(null, this.importedGlobalsTable, null, this.importedGlobalsTypeTable, null, null); + this.dualGlobalValues = new TypeScript.DualStringHashTable(this.residentGlobalValues, new TypeScript.StringHashTable()); + this.dualGlobalTypes = new TypeScript.DualStringHashTable(this.residentGlobalTypes, new TypeScript.StringHashTable()); + this.dualAmbientGlobalValues = new TypeScript.DualStringHashTable(this.residentGlobalAmbientValues, new TypeScript.StringHashTable()); + this.dualAmbientGlobalTypes = new TypeScript.DualStringHashTable(this.residentGlobalAmbientTypes, new TypeScript.StringHashTable()); + var dualGlobalScopedMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(this.dualGlobalValues, new TypeScript.StringHashTable())); + var dualGlobalScopedAmbientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(this.dualAmbientGlobalValues, new TypeScript.StringHashTable())); + var dualGlobalScopedEnclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(this.dualGlobalTypes, new TypeScript.StringHashTable())); + var dualGlobalScopedAmbientEnclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(this.dualAmbientGlobalTypes, new TypeScript.StringHashTable())); + this.globalScope = new TypeScript.SymbolScopeBuilder(dualGlobalScopedMembers, dualGlobalScopedAmbientMembers, dualGlobalScopedEnclosedTypes, dualGlobalScopedAmbientEnclosedTypes, this.importedGlobals, null); + this.voidType = this.enterPrimitive(TypeScript.Primitive.Void, "void"); + this.booleanType = this.enterPrimitive(TypeScript.Primitive.Boolean, "bool"); + this.doubleType = this.enterPrimitive(TypeScript.Primitive.Double, "number"); + this.importedGlobals.ambientEnclosedTypes.addPublicMember("number", this.doubleType.symbol); + this.stringType = this.enterPrimitive(TypeScript.Primitive.String, "string"); + this.anyType = this.enterPrimitive(TypeScript.Primitive.Any, "any"); + this.nullType = this.enterPrimitive(TypeScript.Primitive.Null, "null"); + this.undefinedType = this.enterPrimitive(TypeScript.Primitive.Undefined, "undefined"); + this.setCollectionMode(TypeCheckCollectionMode.Resident); + this.wildElm = new TypeScript.TypeSymbol("_element", -1, 0, -1, new TypeScript.Type()); + this.importedGlobalsTypeTable.addPublicMember(this.wildElm.name, this.wildElm); + this.mod = new TypeScript.ModuleType(dualGlobalScopedEnclosedTypes, dualGlobalScopedAmbientEnclosedTypes); + this.mod.members = dualGlobalScopedMembers; + this.mod.ambientMembers = dualGlobalScopedAmbientMembers; + this.mod.containedScope = this.globalScope; + this.gloMod = new TypeScript.TypeSymbol(TypeScript.globalId, -1, 0, -1, this.mod); + this.mod.members.addPublicMember(this.gloMod.name, this.gloMod); + this.defineGlobalValue("undefined", this.undefinedType); + } + PersistentGlobalTypeState.prototype.enterPrimitive = function (flags, name) { + var primitive = new TypeScript.Type(); + primitive.primitiveTypeClass = flags; + var symbol = new TypeScript.TypeSymbol(name, -1, name.length, -1, primitive); + symbol.typeCheckStatus = TypeScript.TypeCheckStatus.Finished; + primitive.symbol = symbol; + this.importedGlobals.enter(null, null, symbol, this.errorReporter, true, true, true); + return primitive; + }; + PersistentGlobalTypeState.prototype.setCollectionMode = function (mode) { + this.residentTypeCheck = this.dualGlobalValues.insertPrimary = this.dualGlobalTypes.insertPrimary = this.dualAmbientGlobalValues.insertPrimary = this.dualAmbientGlobalTypes.insertPrimary = mode == TypeCheckCollectionMode.Resident; + }; + PersistentGlobalTypeState.prototype.refreshPersistentState = function () { + this.globals = new TypeScript.StringHashTable(); + this.globalTypes = new TypeScript.StringHashTable(); + this.ambientGlobals = new TypeScript.StringHashTable(); + this.ambientGlobalTypes = new TypeScript.StringHashTable(); + this.globalTypes.add(this.voidType.symbol.name, this.voidType.symbol); + this.globalTypes.add(this.booleanType.symbol.name, this.booleanType.symbol); + this.globalTypes.add(this.doubleType.symbol.name, this.doubleType.symbol); + this.globalTypes.add("number", this.doubleType.symbol); + this.globalTypes.add(this.stringType.symbol.name, this.stringType.symbol); + this.globalTypes.add(this.anyType.symbol.name, this.anyType.symbol); + this.globalTypes.add(this.nullType.symbol.name, this.nullType.symbol); + this.globalTypes.add(this.undefinedType.symbol.name, this.undefinedType.symbol); + this.dualGlobalValues.secondaryTable = this.globals; + this.dualGlobalTypes.secondaryTable = this.globalTypes; + this.dualAmbientGlobalValues.secondaryTable = this.ambientGlobals; + this.dualAmbientGlobalTypes.secondaryTable = this.ambientGlobalTypes; + }; + PersistentGlobalTypeState.prototype.defineGlobalValue = function (name, type) { + var valueLocation = new TypeScript.ValueLocation(); + valueLocation.typeLink = new TypeScript.TypeLink(); + var sym = new TypeScript.VariableSymbol(name, 0, -1, valueLocation); + sym.setType(type); + sym.typeCheckStatus = TypeScript.TypeCheckStatus.Finished; + sym.container = this.gloMod; + this.importedGlobalsTable.addPublicMember(name, sym); + }; + return PersistentGlobalTypeState; + })(); + TypeScript.PersistentGlobalTypeState = PersistentGlobalTypeState; + var ContextualTypeContext = (function () { + function ContextualTypeContext(contextualType, provisional, contextID) { + this.contextualType = contextualType; + this.provisional = provisional; + this.contextID = contextID; + this.targetSig = null; + this.targetThis = null; + this.targetAccessorType = null; + } + return ContextualTypeContext; + })(); + TypeScript.ContextualTypeContext = ContextualTypeContext; + var ContextualTypingContextStack = (function () { + function ContextualTypingContextStack(checker) { + this.checker = checker; + this.contextStack = []; + this.hadProvisionalErrors = false; + } + ContextualTypingContextStack.contextID = TypeScript.TypeCheckStatus.Finished + 1; + ContextualTypingContextStack.prototype.pushContextualType = function (type, provisional) { + this.contextStack.push(new ContextualTypeContext(type, provisional, ContextualTypingContextStack.contextID++)); + this.checker.errorReporter.pushToErrorSink = provisional; + }; + ContextualTypingContextStack.prototype.popContextualType = function () { + var tc = this.contextStack.pop(); + this.checker.errorReporter.pushToErrorSink = this.isProvisional(); + this.hadProvisionalErrors = this.hadProvisionalErrors || (tc.provisional && (this.checker.errorReporter.getCapturedErrors().length)); + this.checker.errorReporter.freeCapturedErrors(); + return tc; + }; + ContextualTypingContextStack.prototype.getContextualType = function () { + return (!this.contextStack.length ? null : this.contextStack[this.contextStack.length - 1]); + }; + ContextualTypingContextStack.prototype.getContextID = function () { + return (!this.contextStack.length ? TypeScript.TypeCheckStatus.Finished : this.contextStack[this.contextStack.length - 1].contextID); + }; + ContextualTypingContextStack.prototype.isProvisional = function () { + return (!this.contextStack.length ? false : this.contextStack[this.contextStack.length - 1].provisional); + }; + return ContextualTypingContextStack; + })(); + TypeScript.ContextualTypingContextStack = ContextualTypingContextStack; + var TypeChecker = (function () { + function TypeChecker(persistentState) { + this.persistentState = persistentState; + this.errorReporter = null; + this.checkControlFlow = false; + this.printControlFlowGraph = false; + this.checkControlFlowUseDef = false; + this.styleSettings = null; + this.units = null; + this.anon = "_anonymous"; + this.locationInfo = null; + this.typeFlow = null; + this.currentCompareA = null; + this.currentCompareB = null; + this.currentModDecl = null; + this.inBind = false; + this.inWith = false; + this.errorsOnWith = true; + this.currentContextualTypeContext = null; + this.resolvingBases = false; + this.canCallDefinitionSignature = false; + this.assignableCache = { + }; + this.subtypeCache = { + }; + this.identicalCache = { + }; + this.provisionalStartedTypecheckObjects = []; + this.mustCaptureGlobalThis = false; + this.voidType = this.persistentState.voidType; + this.booleanType = this.persistentState.booleanType; + this.numberType = this.persistentState.doubleType; + this.stringType = this.persistentState.stringType; + this.anyType = this.persistentState.anyType; + this.nullType = this.persistentState.nullType; + this.undefinedType = this.persistentState.undefinedType; + this.globals = this.persistentState.dualGlobalValues; + this.globalTypes = this.persistentState.dualGlobalTypes; + this.ambientGlobals = this.persistentState.dualAmbientGlobalValues; + this.ambientGlobalTypes = this.persistentState.dualAmbientGlobalTypes; + this.gloModType = this.persistentState.mod; + this.gloMod = this.persistentState.gloMod; + this.wildElm = this.persistentState.wildElm; + this.globalScope = this.persistentState.globalScope; + this.typingContextStack = new ContextualTypingContextStack(this); + } + TypeChecker.prototype.setStyleOptions = function (style) { + this.styleSettings = style; + }; + TypeChecker.prototype.setContextualType = function (type, provisional) { + this.typingContextStack.pushContextualType(type, provisional); + this.currentContextualTypeContext = this.typingContextStack.getContextualType(); + }; + TypeChecker.prototype.unsetContextualType = function () { + var lastTC = this.typingContextStack.popContextualType(); + this.currentContextualTypeContext = this.typingContextStack.getContextualType(); + return lastTC; + }; + TypeChecker.prototype.hadProvisionalErrors = function () { + return this.typingContextStack.hadProvisionalErrors; + }; + TypeChecker.prototype.resetProvisionalErrors = function () { + if(!this.typingContextStack.getContextualType()) { + this.typingContextStack.hadProvisionalErrors = false; + } + }; + TypeChecker.prototype.typeCheckWithContextualType = function (contextType, provisional, condition, ast) { + if(condition) { + this.setContextualType(contextType, this.typingContextStack.isProvisional() || provisional); + } + this.typeFlow.typeCheck(ast); + if(condition) { + this.unsetContextualType(); + } + }; + TypeChecker.prototype.resetTargetType = function () { + this.currentContextualTypeContext = this.typingContextStack.getContextualType(); + }; + TypeChecker.prototype.killCurrentContextualType = function () { + this.currentContextualTypeContext = null; + this.errorReporter.pushToErrorSink = false; + }; + TypeChecker.prototype.hasTargetType = function () { + return this.currentContextualTypeContext && this.currentContextualTypeContext.contextualType; + }; + TypeChecker.prototype.getTargetTypeContext = function () { + return this.currentContextualTypeContext; + }; + TypeChecker.prototype.inProvisionalTypecheckMode = function () { + return this.typingContextStack.isProvisional(); + }; + TypeChecker.prototype.getTypeCheckFinishedStatus = function () { + if(this.inProvisionalTypecheckMode()) { + return this.typingContextStack.getContextID(); + } + return TypeScript.TypeCheckStatus.Finished; + }; + TypeChecker.prototype.typeStatusIsFinished = function (status) { + return status == TypeScript.TypeCheckStatus.Finished || (this.inProvisionalTypecheckMode() && status == this.typingContextStack.getContextID()); + }; + TypeChecker.prototype.addStartedPTO = function (pto) { + if(this.inProvisionalTypecheckMode()) { + this.provisionalStartedTypecheckObjects[this.provisionalStartedTypecheckObjects.length] = pto; + } + }; + TypeChecker.prototype.cleanStartedPTO = function () { + for(var i = 0; i < this.provisionalStartedTypecheckObjects.length; i++) { + if(this.provisionalStartedTypecheckObjects[i].typeCheckStatus >= this.typingContextStack.getContextID()) { + this.provisionalStartedTypecheckObjects[i].typeCheckStatus = TypeScript.TypeCheckStatus.NotStarted; + } + } + this.provisionalStartedTypecheckObjects = []; + }; + TypeChecker.prototype.collectTypes = function (ast) { + if(ast.nodeType == TypeScript.NodeType.Script) { + var script = ast; + this.locationInfo = script.locationInfo; + } + var globalChain = new TypeScript.ScopeChain(this.gloMod, null, this.globalScope); + var context = new TypeScript.TypeCollectionContext(globalChain, this); + TypeScript.getAstWalkerFactory().walk(ast, TypeScript.preCollectTypes, TypeScript.postCollectTypes, null, context); + }; + TypeChecker.prototype.makeArrayType = function (type) { + if(type.arrayCache == null) { + type.arrayCache = new ArrayCache(); + type.arrayCache.arrayType = new TypeScript.Type(); + type.arrayCache.arrayType.elementType = type; + type.arrayCache.arrayType.symbol = type.symbol; + } + return type.arrayCache.arrayType; + }; + TypeChecker.prototype.getParameterList = function (funcDecl, container) { + var args = funcDecl.arguments; + var parameterTable = null; + var parameterBuilder = null; + var len = args.members.length; + var nonOptionalParams = 0; + var result = []; + if(len > 0) { + parameterTable = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + parameterBuilder = new TypeScript.SymbolScopeBuilder(parameterTable, null, null, null, null, container); + for(var i = 0; i < len; i++) { + var parameter = args.members[i]; + var paramDef = new TypeScript.ValueLocation(); + var parameterSymbol = new TypeScript.ParameterSymbol(parameter.id.text, parameter.minChar, this.locationInfo.unitIndex, paramDef); + parameterSymbol.declAST = parameter; + parameterSymbol.funcDecl = funcDecl; + parameter.id.sym = parameterSymbol; + parameter.sym = parameterSymbol; + paramDef.symbol = parameterSymbol; + paramDef.typeLink = TypeScript.getTypeLink(parameter.typeExpr, this, false); + parameterBuilder.enter(null, parameter, parameterSymbol, this.errorReporter, true, false, false); + result[result.length] = parameterSymbol; + if(!parameter.isOptionalArg()) { + nonOptionalParams++; + } + } + } + return { + parameters: result, + nonOptionalParameterCount: nonOptionalParams + }; + }; + TypeChecker.prototype.createFunctionSignature = function (funcDecl, container, scope, overloadGroupSym, addToScope) { + var isExported = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Exported | TypeScript.FncFlags.ClassPropertyMethodExported) || container == this.gloMod; + var isStatic = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static); + var isPrivate = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Private); + var isDefinition = !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Signature); + var isAmbient = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Ambient); + var isConstructor = funcDecl.isConstructMember() || funcDecl.isConstructor; + var isGlobal = container == this.gloMod; + var signature = new TypeScript.Signature(); + var isLambda = funcDecl.fncFlags & TypeScript.FncFlags.IsFunctionExpression; + if(funcDecl.returnTypeAnnotation || isDefinition) { + signature.returnType = TypeScript.getTypeLink(funcDecl.returnTypeAnnotation, this, false); + } else { + signature.returnType = new TypeScript.TypeLink(); + signature.returnType.type = this.anyType; + } + signature.hasVariableArgList = funcDecl.variableArgList; + var sigData = this.getParameterList(funcDecl, container); + signature.parameters = sigData.parameters; + signature.nonOptionalParameterCount = sigData.nonOptionalParameterCount; + funcDecl.signature = signature; + signature.declAST = funcDecl; + var useOverloadGroupSym = overloadGroupSym && overloadGroupSym.getType() && !overloadGroupSym.isAccessor() && (funcDecl.isSignature() || (isAmbient == TypeScript.hasFlag(overloadGroupSym.flags, TypeScript.SymbolFlags.Ambient))); + if(useOverloadGroupSym && isPrivate != TypeScript.hasFlag(overloadGroupSym.flags, TypeScript.SymbolFlags.Private)) { + this.errorReporter.simpleError(funcDecl, "Public/Private visibility of overloads does not agree"); + } + var groupType = useOverloadGroupSym ? overloadGroupSym.getType() : new TypeScript.Type(); + if(isConstructor) { + if(groupType.construct == null) { + groupType.construct = new TypeScript.SignatureGroup(); + } + groupType.construct.addSignature(signature); + groupType.construct.hasImplementation = !(funcDecl.isSignature()); + if(groupType.construct.hasImplementation) { + groupType.setHasImplementation(); + } + } else if(funcDecl.isIndexerMember()) { + if(groupType.index == null) { + groupType.index = new TypeScript.SignatureGroup(); + groupType.index.flags |= TypeScript.SignatureFlags.IsIndexer; + } + groupType.index.addSignature(signature); + groupType.index.hasImplementation = !(funcDecl.isSignature()); + if(groupType.index.hasImplementation) { + groupType.setHasImplementation(); + } + } else { + if(groupType.call == null) { + groupType.call = new TypeScript.SignatureGroup(); + } + groupType.call.addSignature(signature); + groupType.call.hasImplementation = !(funcDecl.isSignature()); + if(groupType.call.hasImplementation) { + groupType.setHasImplementation(); + } + } + var instanceType = groupType.instanceType; + var funcName = null; + var usedHint = false; + if(funcDecl.name && !funcDecl.name.isMissing()) { + funcName = funcDecl.name.text; + } else if(funcDecl.hint) { + funcName = funcDecl.hint; + usedHint = true; + } + if(groupType.symbol == null) { + groupType.symbol = new TypeScript.TypeSymbol(funcName ? funcName : this.anon, funcDecl.minChar, funcDecl.limChar - funcDecl.minChar, this.locationInfo.unitIndex, groupType); + if(!useOverloadGroupSym) { + groupType.symbol.declAST = funcDecl; + } + } + if(isStatic) { + groupType.symbol.flags |= TypeScript.SymbolFlags.Static; + } + if(isAmbient) { + groupType.symbol.flags |= TypeScript.SymbolFlags.Ambient; + } + if(isPrivate) { + groupType.symbol.flags |= TypeScript.SymbolFlags.Private; + } + groupType.symbol.isMethod = funcDecl.isMethod(); + if(groupType.symbol.isMethod) { + groupType.symbol.flags |= TypeScript.SymbolFlags.Property; + } + funcDecl.type = groupType; + if(!isConstructor) { + if(funcName && !isLambda && !funcDecl.isAccessor() && !usedHint) { + if(addToScope) { + if(funcDecl.isMethod() && isStatic) { + if(!(container).type.members.publicMembers.add(funcName, groupType.symbol)) { + this.errorReporter.duplicateIdentifier(funcDecl, funcName); + } + groupType.symbol.container = container; + } else if(overloadGroupSym == null || (overloadGroupSym.declAST && !(overloadGroupSym.declAST).isOverload && (container.isType()))) { + scope.enter(container, funcDecl, groupType.symbol, this.errorReporter, !isPrivate && (isExported || isStatic || isGlobal), false, isAmbient); + } + } else if(!funcDecl.isSpecialFn()) { + groupType.symbol.container = container; + } + } else if(!funcDecl.isSpecialFn()) { + groupType.symbol.container = container; + } + } + if(useOverloadGroupSym) { + var overloadGroupType = overloadGroupSym ? overloadGroupSym.getType() : null; + var classType = groupType; + if(classType != overloadGroupType) { + if(classType.construct == null) { + if(overloadGroupType && overloadGroupType.construct) { + classType.construct = overloadGroupType.construct; + } else { + classType.construct = new TypeScript.SignatureGroup(); + } + } else if(overloadGroupType) { + if(overloadGroupType.construct) { + classType.construct.signatures.concat(overloadGroupType.construct.signatures); + } + } + if(overloadGroupType) { + if(classType.call == null) { + classType.call = overloadGroupType.call; + } else if(overloadGroupType.call) { + classType.call.signatures.concat(overloadGroupType.call.signatures); + } + if(!isStatic) { + if(classType.instanceType == null) { + classType.instanceType = overloadGroupType.instanceType; + } + var instanceType = classType.instanceType; + if(instanceType) { + if(instanceType.call == null) { + instanceType.call = overloadGroupType.call; + } else if(overloadGroupType.call) { + instanceType.call.signatures.concat(overloadGroupType.call.signatures); + } + } + } + if(classType.index == null) { + classType.index = overloadGroupType.index; + } else if(overloadGroupType.index) { + classType.index.signatures.concat(overloadGroupType.index.signatures); + } + } + } + } + return signature; + }; + TypeChecker.prototype.createAccessorSymbol = function (funcDecl, fgSym, enclosingClass, addToMembers, isClassProperty, scope, container) { + var accessorSym = null; + var sig = funcDecl.signature; + var nameText = funcDecl.name.text; + var isStatic = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static); + var isPrivate = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Private); + if(fgSym == null) { + var field = new TypeScript.ValueLocation(); + accessorSym = new TypeScript.FieldSymbol(nameText, funcDecl.minChar, this.locationInfo.unitIndex, false, field); + field.symbol = accessorSym; + accessorSym.declAST = funcDecl; + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { + if(accessorSym.getter) { + this.errorReporter.simpleError(funcDecl, "Redeclaration of property getter"); + } + accessorSym.getter = sig.declAST.type.symbol; + } else { + if(accessorSym.setter) { + this.errorReporter.simpleError(funcDecl, "Redeclaration of property setter"); + } + accessorSym.setter = sig.declAST.type.symbol; + } + field.typeLink = TypeScript.getTypeLink(null, this, false); + if(addToMembers) { + if(enclosingClass) { + if(!enclosingClass.members.publicMembers.add(nameText, accessorSym)) { + this.errorReporter.duplicateIdentifier(funcDecl, accessorSym.name); + } + accessorSym.container = enclosingClass.symbol; + } else { + this.errorReporter.simpleError(funcDecl, "Accessor property may not be added in this context"); + } + } else { + scope.enter(container, funcDecl, accessorSym, this.errorReporter, !isPrivate || isStatic, false, false); + } + if(isClassProperty) { + accessorSym.flags |= TypeScript.SymbolFlags.Property; + } + if(isStatic) { + accessorSym.flags |= TypeScript.SymbolFlags.Static; + } + if(isPrivate) { + accessorSym.flags |= TypeScript.SymbolFlags.Private; + } else { + accessorSym.flags |= TypeScript.SymbolFlags.Public; + } + } else { + accessorSym = (fgSym); + if(isPrivate != TypeScript.hasFlag(accessorSym.flags, TypeScript.SymbolFlags.Private)) { + this.errorReporter.simpleError(funcDecl, "Getter and setter accessors do not agree in visibility"); + } + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { + if(accessorSym.getter) { + this.errorReporter.simpleError(funcDecl, "Redeclaration of property getter"); + } + accessorSym.getter = funcDecl.type.symbol; + } else { + if(accessorSym.setter) { + this.errorReporter.simpleError(funcDecl, "Redeclaration of property setter"); + } + accessorSym.setter = funcDecl.type.symbol; + } + } + return accessorSym; + }; + TypeChecker.prototype.addBases = function (resultScope, type, baseContext) { + resultScope.addParentScope(new TypeScript.SymbolTableScope(type.members, type.ambientMembers, type.getAllEnclosedTypes(), type.getAllAmbientEnclosedTypes(), type.symbol)); + var i = 0; + var parent; + if(type.extendsList) { + for(var len = type.extendsList.length; i < len; i++) { + parent = type.extendsList[i]; + if(baseContext.baseId == parent.typeID) { + this.errorReporter.reportErrorFromSym(parent.symbol, "Type '" + baseContext.base + "' is recursively referenced as a base class of itself"); + parent.symbol.flags |= TypeScript.SymbolFlags.RecursivelyReferenced; + break; + } + this.addBases(resultScope, parent, baseContext); + } + } + }; + TypeChecker.prototype.scopeOf = function (type) { + var resultScope = new TypeScript.SymbolAggregateScope(type.symbol); + var baseContext = { + base: type.symbol && type.symbol.name ? type.symbol.name : "{}", + baseId: type.typeID + }; + this.addBases(resultScope, type, baseContext); + return resultScope; + }; + TypeChecker.prototype.lookupMemberTypeSymbol = function (containingType, name) { + var symbol = null; + if(containingType.containedScope) { + symbol = containingType.containedScope.find(name, false, true); + } else if(containingType.members) { + symbol = containingType.members.allMembers.lookup(name); + if(symbol == null && containingType.ambientMembers) { + symbol = containingType.ambientMembers.allMembers.lookup(name); + } + } + if(symbol == null || !symbol.isType()) { + var typeMembers = containingType.getAllEnclosedTypes(); + var ambientTypeMembers = containingType.getAllAmbientEnclosedTypes(); + if(typeMembers) { + symbol = typeMembers.allMembers.lookup(name); + if(symbol == null && ambientTypeMembers) { + symbol = ambientTypeMembers.allMembers.lookup(name); + } + } + } + if(symbol && symbol.isType()) { + return symbol; + } else { + return null; + } + }; + TypeChecker.prototype.findSymbolForDynamicModule = function (idText, currentFileName, search) { + var originalIdText = idText; + var symbol = search(idText); + if(symbol == null) { + if(!symbol) { + idText = TypeScript.swapQuotes(originalIdText); + symbol = search(idText); + } + if(!symbol) { + idText = TypeScript.stripQuotes(originalIdText) + ".ts"; + symbol = search(idText); + } + if(!symbol) { + idText = TypeScript.stripQuotes(originalIdText) + ".str"; + symbol = search(idText); + } + if(!symbol) { + idText = TypeScript.stripQuotes(originalIdText) + ".d.ts"; + symbol = search(idText); + } + if(!symbol) { + idText = TypeScript.stripQuotes(originalIdText) + ".d.str"; + symbol = search(idText); + } + if(!symbol && !TypeScript.isRelative(originalIdText)) { + idText = originalIdText; + var strippedIdText = TypeScript.stripQuotes(idText); + var path = TypeScript.getRootFilePath(TypeScript.switchToForwardSlashes(currentFileName)); + while(symbol == null && path != "") { + idText = TypeScript.normalizePath(path + strippedIdText + ".ts"); + symbol = search(idText); + if(symbol == null) { + idText = TypeScript.changePathToSTR(idText); + symbol = search(idText); + } + if(symbol == null) { + idText = TypeScript.changePathToDTS(idText); + symbol = search(idText); + } + if(symbol == null) { + idText = TypeScript.changePathToDSTR(idText); + symbol = search(idText); + } + if(symbol == null) { + if(path === '/') { + path = ''; + } else { + path = TypeScript.normalizePath(path + ".."); + path = path && path != '/' ? path + '/' : path; + } + } + } + } + } + return symbol; + }; + TypeChecker.prototype.resolveTypeMember = function (scope, dotNode) { + var lhs = dotNode.operand1; + var rhs = dotNode.operand2; + var resultType = this.anyType; + var lhsType = this.anyType; + if(lhs && rhs && (rhs.nodeType == TypeScript.NodeType.Name)) { + if(lhs.nodeType == TypeScript.NodeType.Dot) { + lhsType = this.resolveTypeMember(scope, lhs); + } else if(lhs.nodeType == TypeScript.NodeType.Name) { + var identifier = lhs; + var symbol = scope.find(identifier.text, false, true); + if(symbol == null) { + this.errorReporter.unresolvedSymbol(identifier, identifier.actualText); + } else if(symbol.isType()) { + var typeSymbol = symbol; + if(typeSymbol.aliasLink && !typeSymbol.type && typeSymbol.aliasLink.alias.nodeType == TypeScript.NodeType.Name) { + var modPath = (typeSymbol.aliasLink.alias).text; + var modSym = this.findSymbolForDynamicModule(modPath, this.locationInfo.filename, function (id) { + return scope.find(id, false, true); + }); + if(modSym) { + typeSymbol.type = modSym.getType(); + } + } + if(TypeScript.optimizeModuleCodeGen && symbol) { + var symType = symbol.getType(); + if(symType && typeSymbol.aliasLink && typeSymbol.onlyReferencedAsTypeRef) { + var modDecl = symType.symbol.declAST; + if(modDecl && TypeScript.hasFlag(modDecl.modFlags, TypeScript.ModuleFlags.IsDynamic)) { + typeSymbol.onlyReferencedAsTypeRef = !this.resolvingBases; + } + } + } + if(!symbol.visible(scope, this)) { + this.errorReporter.simpleError(lhs, "The symbol '" + identifier.actualText + "' is not visible at this point"); + } + lhsType = symbol.getType(); + identifier.sym = symbol; + } else { + this.errorReporter.simpleError(lhs, "Expected type"); + } + } + if(!lhsType) { + lhsType = this.anyType; + } + if(lhsType != this.anyType) { + var rhsIdentifier = rhs; + var resultSymbol = this.lookupMemberTypeSymbol(lhsType, rhsIdentifier.text); + if(resultSymbol == null) { + resultType = this.anyType; + this.errorReporter.simpleError(dotNode, "Expected type"); + } else { + resultType = resultSymbol.getType(); + if(!resultSymbol.visible(scope, this)) { + this.errorReporter.simpleError(lhs, "The symbol '" + (rhs).actualText + "' is not visible at this point"); + } + } + rhsIdentifier.sym = resultType.symbol; + } + } + if(resultType.isClass()) { + resultType = resultType.instanceType; + } + return resultType; + }; + TypeChecker.prototype.resolveFuncDecl = function (funcDecl, scope, fgSym) { + var functionGroupSymbol = this.createFunctionSignature(funcDecl, scope.container, scope, fgSym, false).declAST.type.symbol; + var signatures; + if(funcDecl.isConstructMember()) { + signatures = functionGroupSymbol.type.construct.signatures; + } else if(funcDecl.isIndexerMember()) { + signatures = functionGroupSymbol.type.getInstanceType().index.signatures; + } else { + signatures = functionGroupSymbol.type.call.signatures; + } + var signature = signatures[signatures.length - 1]; + var len = signature.parameters.length; + for(var i = 0; i < len; i++) { + var paramSym = signature.parameters[i]; + this.resolveTypeLink(scope, paramSym.parameter.typeLink, true); + } + if(len && funcDecl.variableArgList) { + if(!signature.parameters[len - 1].parameter.typeLink.type.elementType) { + this.errorReporter.simpleErrorFromSym(signature.parameters[len - 1].parameter.symbol, "... parameter must have array type"); + signature.parameters[len - 1].parameter.typeLink.type = this.makeArrayType(signature.parameters[len - 1].parameter.typeLink.type); + } + } + this.resolveTypeLink(scope, signature.returnType, funcDecl.isSignature()); + return functionGroupSymbol; + }; + TypeChecker.prototype.resolveVarDecl = function (varDecl, scope) { + var field = new TypeScript.ValueLocation(); + var fieldSymbol = new TypeScript.FieldSymbol(varDecl.id.text, varDecl.minChar, this.locationInfo.unitIndex, (varDecl.varFlags & TypeScript.VarFlags.Readonly) == TypeScript.VarFlags.None, field); + fieldSymbol.transferVarFlags(varDecl.varFlags); + field.symbol = fieldSymbol; + fieldSymbol.declAST = varDecl; + field.typeLink = TypeScript.getTypeLink(varDecl.typeExpr, this, varDecl.init == null); + this.resolveTypeLink(scope, field.typeLink, true); + varDecl.sym = fieldSymbol; + varDecl.type = field.typeLink.type; + return fieldSymbol; + }; + TypeChecker.prototype.resolveTypeLink = function (scope, typeLink, supplyVar) { + var arrayCount = 0; + if(typeLink.type == null) { + var ast = typeLink.ast; + if(ast) { + while(typeLink.type == null) { + switch(ast.nodeType) { + case TypeScript.NodeType.Name: + var identifier = ast; + var symbol = scope.find(identifier.text, false, true); + if(symbol == null) { + typeLink.type = this.anyType; + this.errorReporter.unresolvedSymbol(identifier, identifier.actualText); + } else if(symbol.isType()) { + if(!symbol.visible(scope, this)) { + this.errorReporter.simpleError(ast, "The symbol '" + identifier.actualText + "' is not visible at this point"); + } + identifier.sym = symbol; + typeLink.type = symbol.getType(); + if(typeLink.type) { + if(typeLink.type.isClass()) { + typeLink.type = typeLink.type.instanceType; + } + } else { + typeLink.type = this.anyType; + } + } else { + typeLink.type = this.anyType; + this.errorReporter.simpleError(ast, "Expected type"); + } + break; + case TypeScript.NodeType.Dot: + typeLink.type = this.resolveTypeMember(scope, ast); + break; + case TypeScript.NodeType.TypeRef: + var typeRef = ast; + arrayCount = typeRef.arrayCount; + ast = typeRef.term; + if(ast == null) { + typeLink.type = this.anyType; + } + break; + case TypeScript.NodeType.InterfaceDeclaration: + var interfaceDecl = ast; + var interfaceType = new TypeScript.Type(); + var interfaceSymbol = new TypeScript.TypeSymbol((interfaceDecl.name).text, ast.minChar, ast.limChar - ast.minChar, this.locationInfo.unitIndex, interfaceType); + interfaceType.symbol = interfaceSymbol; + interfaceType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + interfaceType.containedScope = new TypeScript.SymbolTableScope(interfaceType.members, null, null, null, interfaceSymbol); + interfaceType.containedScope.container = interfaceSymbol; + interfaceType.memberScope = interfaceType.containedScope; + var memberList = interfaceDecl.members; + var props = memberList.members; + var propsLen = props.length; + for(var j = 0; j < propsLen; j++) { + var propDecl = props[j]; + var propSym = null; + var addMember = true; + var id = null; + if(propDecl.nodeType == TypeScript.NodeType.FuncDecl) { + var funcDecl = propDecl; + id = funcDecl.name; + propSym = interfaceType.members.allMembers.lookup(funcDecl.getNameText()); + addMember = (propSym == null); + if(funcDecl.isSpecialFn()) { + addMember = false; + propSym = this.resolveFuncDecl(funcDecl, scope, interfaceSymbol); + } else { + propSym = this.resolveFuncDecl(funcDecl, scope, propSym); + } + funcDecl.type = (propSym).type; + } else { + id = (propDecl).id; + propSym = this.resolveVarDecl(propDecl, scope); + addMember = !id.isMissing(); + } + if(addMember) { + if(id && TypeScript.hasFlag(id.flags, TypeScript.ASTFlags.OptionalName)) { + propSym.flags |= TypeScript.SymbolFlags.Optional; + } + if(!interfaceType.members.allMembers.add(propSym.name, propSym)) { + this.errorReporter.duplicateIdentifier(ast, propSym.name); + } + } + } + ast.type = interfaceType; + typeLink.type = interfaceType; + break; + case TypeScript.NodeType.FuncDecl: + var tsym = this.resolveFuncDecl(ast, scope, null); + typeLink.type = tsym.type; + break; + default: + typeLink.type = this.anyType; + this.errorReporter.simpleError(ast, "Expected type"); + break; + } + } + } + for(var count = arrayCount; count > 0; count--) { + typeLink.type = this.makeArrayType(typeLink.type); + } + if(supplyVar && (typeLink.type == null)) { + typeLink.type = this.anyType; + } + if(typeLink.ast) { + typeLink.ast.type = typeLink.type; + } + } + }; + TypeChecker.prototype.resolveBaseTypeLink = function (typeLink, scope) { + this.resolvingBases = true; + this.resolveTypeLink(scope, typeLink, true); + this.resolvingBases = false; + var extendsType = null; + if(typeLink.type.isClass()) { + extendsType = typeLink.type.instanceType; + } else { + extendsType = typeLink.type; + } + return extendsType; + }; + TypeChecker.prototype.findMostApplicableSignature = function (signatures, args) { + if(signatures.length == 1) { + return { + sig: signatures[0].signature, + ambiguous: false + }; + } + var best = signatures[0]; + var Q = null; + var AType = null; + var PType = null; + var QType = null; + var ambiguous = false; + for(var qSig = 1; qSig < signatures.length; qSig++) { + Q = signatures[qSig]; + var i = 0; + for(i = 0; args && i < args.members.length; i++) { + AType = args.members[i].type; + PType = i < best.signature.parameters.length ? best.signature.parameters[i].getType() : best.signature.parameters[best.signature.parameters.length - 1].getType().elementType; + QType = i < Q.signature.parameters.length ? Q.signature.parameters[i].getType() : Q.signature.parameters[Q.signature.parameters.length - 1].getType().elementType; + if(this.typesAreIdentical(PType, QType)) { + continue; + } else if(this.typesAreIdentical(AType, PType)) { + break; + } else if(this.typesAreIdentical(AType, QType)) { + best = Q; + break; + } else if(this.sourceIsSubtypeOfTarget(PType, QType)) { + break; + } else if(this.sourceIsSubtypeOfTarget(QType, PType)) { + best = Q; + break; + } else if(Q.hadProvisionalErrors) { + break; + } else if(best.hadProvisionalErrors) { + best = Q; + break; + } + } + if(!args || i == args.members.length) { + var collection = { + getLength: function () { + return 2; + }, + setTypeAtIndex: function (index, type) { + }, + getTypeAtIndex: function (index) { + return index ? Q.signature.returnType.type : best.signature.returnType.type; + } + }; + var bct = this.findBestCommonType(best.signature.returnType.type, null, collection, true); + ambiguous = !bct; + } else { + ambiguous = false; + } + } + return { + sig: best.signature, + ambiguous: ambiguous + }; + }; + TypeChecker.prototype.getApplicableSignatures = function (signatures, args, comparisonInfo) { + var applicableSigs = []; + var memberType = null; + var miss = false; + var cxt = null; + var hadProvisionalErrors = false; + for(var i = 0; i < signatures.length; i++) { + miss = false; + for(var j = 0; j < args.members.length; j++) { + if(j >= signatures[i].parameters.length) { + continue; + } + memberType = signatures[i].parameters[j].getType(); + if(signatures[i].declAST.variableArgList && (j >= signatures[i].nonOptionalParameterCount - 1) && memberType.isArray()) { + memberType = memberType.elementType; + } + if(memberType == this.anyType) { + continue; + } else if(args.members[j].nodeType == TypeScript.NodeType.FuncDecl) { + if(this.typeFlow.functionInterfaceType && memberType == this.typeFlow.functionInterfaceType) { + continue; + } + if(!this.canContextuallyTypeFunction(memberType, args.members[j], true)) { + if(this.canContextuallyTypeFunction(memberType, args.members[j], false)) { + this.typeFlow.typeCheck(args.members[j]); + if(!this.sourceIsAssignableToTarget(args.members[j].type, memberType, comparisonInfo)) { + break; + } + } else { + break; + } + } else { + this.typeCheckWithContextualType(memberType, true, true, args.members[j]); + this.cleanStartedPTO(); + hadProvisionalErrors = this.hadProvisionalErrors(); + if(!this.sourceIsAssignableToTarget(args.members[j].type, memberType, comparisonInfo)) { + if(comparisonInfo) { + comparisonInfo.setMessage("Could not apply type '" + memberType.getTypeName() + "' to argument " + (j + 1) + ", which is of type '" + args.members[j].type.getTypeName() + "'"); + } + miss = true; + } + this.resetProvisionalErrors(); + if(miss) { + break; + } + } + } else if(args.members[j].nodeType == TypeScript.NodeType.ObjectLit) { + if(this.typeFlow.objectInterfaceType && memberType == this.typeFlow.objectInterfaceType) { + continue; + } + this.typeCheckWithContextualType(memberType, true, true, args.members[j]); + this.cleanStartedPTO(); + hadProvisionalErrors = this.hadProvisionalErrors(); + if(!this.sourceIsAssignableToTarget(args.members[j].type, memberType, comparisonInfo)) { + if(comparisonInfo) { + comparisonInfo.setMessage("Could not apply type '" + memberType.getTypeName() + "' to argument " + (j + 1) + ", which is of type '" + args.members[j].type.getTypeName() + "'"); + } + miss = true; + } + this.resetProvisionalErrors(); + if(miss) { + break; + } + } else if(args.members[j].nodeType == TypeScript.NodeType.ArrayLit) { + if(this.typeFlow.arrayInterfaceType && memberType == this.typeFlow.arrayInterfaceType) { + continue; + } + this.typeCheckWithContextualType(memberType, true, true, args.members[j]); + this.cleanStartedPTO(); + hadProvisionalErrors = this.hadProvisionalErrors(); + if(!this.sourceIsAssignableToTarget(args.members[j].type, memberType, comparisonInfo)) { + if(comparisonInfo) { + comparisonInfo.setMessage("Could not apply type '" + memberType.getTypeName() + "' to argument " + (j + 1) + ", which is of type '" + args.members[j].type.getTypeName() + "'"); + } + break; + } + this.resetProvisionalErrors(); + if(miss) { + break; + } + } + } + if(j == args.members.length) { + applicableSigs[applicableSigs.length] = { + signature: signatures[i], + hadProvisionalErrors: hadProvisionalErrors + }; + } + hadProvisionalErrors = false; + } + return applicableSigs; + }; + TypeChecker.prototype.canContextuallyTypeFunction = function (candidateType, funcDecl, beStringent) { + if(funcDecl.isParenthesized || funcDecl.isMethod() || beStringent && funcDecl.returnTypeAnnotation || funcDecl.isInlineCallLiteral) { + return false; + } + beStringent = beStringent || (this.typeFlow.functionInterfaceType == candidateType); + if(!beStringent) { + return true; + } + if(!funcDecl.signature) { + this.createFunctionSignature(funcDecl, this.typeFlow.scope.container, this.typeFlow.scope, null, null); + this.typeFlow.typeCheck(funcDecl); + } + var signature = funcDecl.signature; + var paramLen = signature.parameters.length; + for(var i = 0; i < paramLen; i++) { + var param = signature.parameters[i]; + var symbol = param; + var argDecl = symbol.declAST; + if(beStringent && argDecl.typeExpr) { + return false; + } + } + if(candidateType.construct && candidateType.call) { + return false; + } + var candidateSigs = candidateType.construct ? candidateType.construct : candidateType.call; + if(!candidateSigs || candidateSigs.signatures.length > 1) { + return false; + } + return true; + }; + TypeChecker.prototype.canContextuallyTypeObjectLiteral = function (targetType, objectLit) { + if(targetType == this.typeFlow.objectInterfaceType) { + return true; + } + var memberDecls = objectLit.operand; + if(!(memberDecls && targetType.memberScope)) { + return false; + } + var id = null; + var targetMember = null; + var text = ""; + var foundSyms = { + }; + for(var i = 0; i < memberDecls.members.length; i++) { + id = (memberDecls.members[i]).operand1; + if(id.nodeType == TypeScript.NodeType.Name) { + text = (id).text; + } else if(id.nodeType == TypeScript.NodeType.QString) { + var idText = (id).text; + text = idText.substring(1, idText.length - 1); + } else { + return false; + } + targetMember = targetType.memberScope.find(text, true, false); + if(!targetMember) { + return false; + } + foundSyms[text] = true; + } + var targetMembers = targetType.memberScope.getAllValueSymbolNames(true); + for(var i = 0; i < targetMembers.length; i++) { + var memberName = targetMembers[i]; + var memberSym = targetType.memberScope.find(memberName, true, false); + if(!foundSyms[targetMembers[i]] && !TypeScript.hasFlag(memberSym.flags, TypeScript.SymbolFlags.Optional)) { + return false; + } + } + return true; + }; + TypeChecker.prototype.widenType = function (t) { + if(t == this.undefinedType || t == this.nullType) { + return this.anyType; + } + return t; + }; + TypeChecker.prototype.isNullOrUndefinedType = function (t) { + return t == this.undefinedType || t == this.nullType; + }; + TypeChecker.prototype.findBestCommonType = function (initialType, targetType, collection, acceptVoid, comparisonInfo) { + var i = 0; + var len = collection.getLength(); + var nlastChecked = 0; + var bestCommonType = initialType; + if(targetType) { + bestCommonType = bestCommonType ? bestCommonType.mergeOrdered(targetType, this, acceptVoid) : targetType; + } + var convergenceType = bestCommonType; + while(nlastChecked < len) { + for(i = 0; i < len; i++) { + if(i == nlastChecked) { + continue; + } + if(convergenceType && (bestCommonType = convergenceType.mergeOrdered(collection.getTypeAtIndex(i), this, acceptVoid, comparisonInfo))) { + convergenceType = bestCommonType; + } + if(bestCommonType == this.anyType || bestCommonType == null) { + break; + } else if(targetType) { + collection.setTypeAtIndex(i, targetType); + } + } + if(convergenceType && bestCommonType) { + break; + } + nlastChecked++; + if(nlastChecked < len) { + convergenceType = collection.getTypeAtIndex(nlastChecked); + } + } + return acceptVoid ? bestCommonType : (bestCommonType == this.voidType ? null : bestCommonType); + }; + TypeChecker.prototype.typesAreIdentical = function (t1, t2) { + if(t1 == t2) { + return true; + } + if(!t1 || !t2) { + return false; + } + if(t1.isClass() || t1.isClassInstance()) { + return false; + } + var comboId = (t2.typeID << 16) | t1.typeID; + if(this.identicalCache[comboId]) { + return true; + } + if((t1.typeFlags & TypeScript.TypeFlags.IsEnum) || (t2.typeFlags & TypeScript.TypeFlags.IsEnum)) { + return false; + } + if(t1.isArray() || t2.isArray()) { + if(!(t1.isArray() && t2.isArray())) { + return false; + } + this.identicalCache[comboId] = false; + var ret = this.typesAreIdentical(t1.elementType, t2.elementType); + if(ret) { + this.subtypeCache[comboId] = true; + } else { + this.subtypeCache[comboId] = undefined; + } + return ret; + } + if(t1.primitiveTypeClass != t2.primitiveTypeClass) { + return false; + } + this.identicalCache[comboId] = false; + if(t1.memberScope && t2.memberScope) { + var t1MemberKeys = t1.memberScope.getAllValueSymbolNames(true).sort(); + var t2MemberKeys = t2.memberScope.getAllValueSymbolNames(true).sort(); + if(t1MemberKeys.length != t2MemberKeys.length) { + this.identicalCache[comboId] = undefined; + return false; + } + var t1MemberSymbol = null; + var t2MemberSymbol = null; + var t1MemberType = null; + var t2MemberType = null; + for(var iMember = 0; iMember < t1MemberKeys.length; iMember++) { + if(t1MemberKeys[iMember] != t2MemberKeys[iMember]) { + this.identicalCache[comboId] = undefined; + return false; + } + t1MemberSymbol = t1.memberScope.find(t1MemberKeys[iMember], false, false); + t2MemberSymbol = t2.memberScope.find(t2MemberKeys[iMember], false, false); + if((t1MemberSymbol.flags & TypeScript.SymbolFlags.Optional) != (t2MemberSymbol.flags & TypeScript.SymbolFlags.Optional)) { + this.identicalCache[comboId] = undefined; + return false; + } + t1MemberType = t1MemberSymbol.getType(); + t2MemberType = t2MemberSymbol.getType(); + if(t1MemberType && t2MemberType && (this.identicalCache[(t2MemberType.typeID << 16) | t1MemberType.typeID] != undefined)) { + continue; + } + if(!this.typesAreIdentical(t1MemberType, t2MemberType)) { + this.identicalCache[comboId] = undefined; + return false; + } + } + } else if(t1.memberScope || t2.memberScope) { + this.identicalCache[comboId] = undefined; + return false; + } + if(!this.signatureGroupsAreIdentical(t1.call, t2.call)) { + this.identicalCache[comboId] = undefined; + return false; + } + if(!this.signatureGroupsAreIdentical(t1.construct, t2.construct)) { + this.identicalCache[comboId] = undefined; + return false; + } + if(!this.signatureGroupsAreIdentical(t1.index, t2.index)) { + this.identicalCache[comboId] = undefined; + return false; + } + this.identicalCache[comboId] = true; + return true; + }; + TypeChecker.prototype.signatureGroupsAreIdentical = function (sg1, sg2) { + if(sg1 == sg2) { + return true; + } + if(!sg1 || !sg2) { + return false; + } + if(sg1.signatures.length != sg2.signatures.length) { + return false; + } + var sig1 = null; + var sig2 = null; + var sigsMatch = false; + for(var iSig1 = 0; iSig1 < sg1.signatures.length; iSig1++) { + sig1 = sg1.signatures[iSig1]; + for(var iSig2 = 0; iSig2 < sg2.signatures.length; iSig2++) { + sig2 = sg2.signatures[iSig2]; + if(this.signaturesAreIdentical(sig1, sig2)) { + sigsMatch = true; + break; + } + } + if(sigsMatch) { + sigsMatch = false; + continue; + } + return false; + } + return true; + }; + TypeChecker.prototype.signaturesAreIdentical = function (s1, s2) { + if(s1.hasVariableArgList != s2.hasVariableArgList) { + return false; + } + if(s1.nonOptionalParameterCount != s2.nonOptionalParameterCount) { + return false; + } + if(s1.parameters.length != s2.parameters.length) { + return false; + } + if(!this.typesAreIdentical(s1.returnType.type, s2.returnType.type)) { + return false; + } + for(var iParam = 0; iParam < s1.parameters.length; iParam++) { + if(!this.typesAreIdentical(s1.parameters[iParam].parameter.typeLink.type, s2.parameters[iParam].parameter.typeLink.type)) { + return false; + } + } + return true; + }; + TypeChecker.prototype.sourceIsSubtypeOfTarget = function (source, target, comparisonInfo) { + return this.sourceIsRelatableToTarget(source, target, false, this.subtypeCache, comparisonInfo); + }; + TypeChecker.prototype.signatureGroupIsSubtypeOfTarget = function (sg1, sg2, comparisonInfo) { + return this.signatureGroupIsRelatableToTarget(sg1, sg2, false, this.subtypeCache, comparisonInfo); + }; + TypeChecker.prototype.signatureIsSubtypeOfTarget = function (s1, s2, comparisonInfo) { + return this.signatureIsRelatableToTarget(s1, s2, false, this.subtypeCache, comparisonInfo); + }; + TypeChecker.prototype.sourceIsAssignableToTarget = function (source, target, comparisonInfo) { + return this.sourceIsRelatableToTarget(source, target, true, this.assignableCache, comparisonInfo); + }; + TypeChecker.prototype.signatureGroupIsAssignableToTarget = function (sg1, sg2, comparisonInfo) { + return this.signatureGroupIsRelatableToTarget(sg1, sg2, true, this.assignableCache, comparisonInfo); + }; + TypeChecker.prototype.signatureIsAssignableToTarget = function (s1, s2, comparisonInfo) { + return this.signatureIsRelatableToTarget(s1, s2, true, this.assignableCache, comparisonInfo); + }; + TypeChecker.prototype.sourceIsRelatableToTarget = function (source, target, assignableTo, comparisonCache, comparisonInfo) { + if(source == target) { + return true; + } + if(!(source && target)) { + return true; + } + var comboId = (source.typeID << 16) | target.typeID; + if(comparisonCache[comboId] != undefined) { + return true; + } + if(assignableTo) { + if(source == this.anyType || target == this.anyType) { + return true; + } + } else { + if(target == this.anyType) { + return true; + } + } + if(source == this.undefinedType) { + return true; + } + if((source == this.nullType) && (target != this.undefinedType && target != this.voidType)) { + return true; + } + if(target == this.numberType && (source.typeFlags & TypeScript.TypeFlags.IsEnum)) { + return true; + } + if(source == this.numberType && (target.typeFlags & TypeScript.TypeFlags.IsEnum)) { + return true; + } + if((source.typeFlags & TypeScript.TypeFlags.IsEnum) || (target.typeFlags & TypeScript.TypeFlags.IsEnum)) { + return false; + } + if(source.isArray() || target.isArray()) { + if(!(source.isArray() && target.isArray())) { + return false; + } + comparisonCache[comboId] = false; + var ret = this.sourceIsRelatableToTarget(source.elementType, target.elementType, assignableTo, comparisonCache, comparisonInfo); + if(ret) { + comparisonCache[comboId] = true; + } else { + comparisonCache[comboId] = undefined; + } + return ret; + } + if(source.primitiveTypeClass != target.primitiveTypeClass) { + if(target.primitiveTypeClass == TypeScript.Primitive.None) { + if(source == this.numberType && this.typeFlow.numberInterfaceType) { + source = this.typeFlow.numberInterfaceType; + } else if(source == this.stringType && this.typeFlow.stringInterfaceType) { + source = this.typeFlow.stringInterfaceType; + } else if(source == this.booleanType && this.typeFlow.booleanInterfaceType) { + source = this.typeFlow.booleanInterfaceType; + } else { + return false; + } + } else { + return false; + } + } + comparisonCache[comboId] = false; + if(source.hasBase(target)) { + comparisonCache[comboId] = true; + return true; + } + if(this.typeFlow.objectInterfaceType && target == this.typeFlow.objectInterfaceType) { + return true; + } + if(this.typeFlow.functionInterfaceType && (source.call || source.construct) && target == this.typeFlow.functionInterfaceType) { + return true; + } + if(target.isClass() || target.isClassInstance()) { + comparisonCache[comboId] = undefined; + return false; + } + if(target.memberScope && source.memberScope) { + var mPropKeys = target.memberScope.getAllValueSymbolNames(true); + var mProp = null; + var nProp = null; + var mPropType = null; + var nPropType = null; + var inferenceSymbol = null; + for(var iMProp = 0; iMProp < mPropKeys.length; iMProp++) { + mProp = target.memberScope.find(mPropKeys[iMProp], false, false); + nProp = source.memberScope.find(mPropKeys[iMProp], false, false); + if(mProp.name == "arguments" && this.typeFlow.iargumentsInterfaceType && (this.typeFlow.iargumentsInterfaceType.symbol.flags & TypeScript.SymbolFlags.CompilerGenerated) && mProp.kind() == TypeScript.SymbolKind.Variable && (mProp).variable.typeLink.type == this.typeFlow.iargumentsInterfaceType) { + continue; + } + if(mProp.isInferenceSymbol()) { + inferenceSymbol = mProp; + if(inferenceSymbol.typeCheckStatus == TypeScript.TypeCheckStatus.NotStarted) { + this.typeFlow.typeCheck(mProp.declAST); + } + } + mPropType = mProp.getType(); + if(!nProp) { + if(this.typeFlow.objectInterfaceType) { + nProp = this.typeFlow.objectInterfaceType.memberScope.find(mPropKeys[iMProp], false, false); + } + if(!nProp) { + if(this.typeFlow.functionInterfaceType && (mPropType.call || mPropType.construct)) { + nProp = this.typeFlow.functionInterfaceType.memberScope.find(mPropKeys[iMProp], false, false); + } + if(!nProp) { + if(!(mProp.flags & TypeScript.SymbolFlags.Optional)) { + comparisonCache[comboId] = undefined; + if(comparisonInfo) { + comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.RequiredPropertyIsMissing; + comparisonInfo.addMessageToFront("Type '" + source.getTypeName() + "' is missing property '" + mPropKeys[iMProp] + "' from type '" + target.getTypeName() + "'"); + } + return false; + } else { + continue; + } + } + } + } + if(nProp.isInferenceSymbol()) { + inferenceSymbol = nProp; + if(inferenceSymbol.typeCheckStatus == TypeScript.TypeCheckStatus.NotStarted) { + this.typeFlow.typeCheck(nProp.declAST); + } + } + nPropType = nProp.getType(); + if(mPropType && nPropType && (comparisonCache[(nPropType.typeID << 16) | mPropType.typeID] != undefined)) { + continue; + } + if(!this.sourceIsRelatableToTarget(nPropType, mPropType, assignableTo, comparisonCache, comparisonInfo)) { + comparisonCache[comboId] = undefined; + if(comparisonInfo) { + comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatiblePropertyTypes; + comparisonInfo.addMessageToFront("Types of property '" + mProp.name + "' of types '" + source.getTypeName() + "' and '" + target.getTypeName() + "' are incompatible"); + } + return false; + } + } + } + if(source.call || target.call) { + if(!this.signatureGroupIsRelatableToTarget(source.call, target.call, assignableTo, comparisonCache, comparisonInfo)) { + if(comparisonInfo) { + if(source.call && target.call) { + comparisonInfo.addMessageToFront("Call signatures of types '" + source.getTypeName() + "' and '" + target.getTypeName() + "' are incompatible"); + } else { + var hasSig = target.call ? target.getTypeName() : source.getTypeName(); + var lacksSig = !target.call ? target.getTypeName() : source.getTypeName(); + comparisonInfo.setMessage("Type '" + hasSig + "' requires a call signature, but Type '" + lacksSig + "' lacks one"); + } + comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleSignatures; + } + comparisonCache[comboId] = undefined; + return false; + } + } + if(source.construct || target.construct) { + if(!this.signatureGroupIsRelatableToTarget(source.construct, target.construct, assignableTo, comparisonCache, comparisonInfo)) { + if(comparisonInfo) { + if(source.construct && target.construct) { + comparisonInfo.addMessageToFront("Construct signatures of types '" + source.getTypeName() + "' and '" + target.getTypeName() + "' are incompatible"); + } else { + var hasSig = target.construct ? target.getTypeName() : source.getTypeName(); + var lacksSig = !target.construct ? target.getTypeName() : source.getTypeName(); + comparisonInfo.setMessage("Type '" + hasSig + "' requires a construct signature, but Type '" + lacksSig + "' lacks one"); + } + comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleSignatures; + } + comparisonCache[comboId] = undefined; + return false; + } + } + if(target.index) { + var targetIndex = !target.index && this.typeFlow.objectInterfaceType ? this.typeFlow.objectInterfaceType.index : target.index; + var sourceIndex = !source.index && this.typeFlow.objectInterfaceType ? this.typeFlow.objectInterfaceType.index : source.index; + if(!this.signatureGroupIsRelatableToTarget(sourceIndex, targetIndex, assignableTo, comparisonCache, comparisonInfo)) { + if(comparisonInfo) { + comparisonInfo.addMessageToFront("Index signatures of types '" + source.getTypeName() + "' and '" + target.getTypeName() + "' are incompatible"); + comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleSignatures; + } + comparisonCache[comboId] = undefined; + return false; + } + } + comparisonCache[comboId] = true; + return true; + }; + TypeChecker.prototype.signatureGroupIsRelatableToTarget = function (sourceSG, targetSG, assignableTo, comparisonCache, comparisonInfo) { + if(sourceSG == targetSG) { + return true; + } + if(!(sourceSG && targetSG)) { + return false; + } + var mSig = null; + var nSig = null; + var foundMatch = false; + for(var iMSig = 0; iMSig < targetSG.signatures.length; iMSig++) { + mSig = targetSG.signatures[iMSig]; + for(var iNSig = 0; iNSig < sourceSG.signatures.length; iNSig++) { + nSig = sourceSG.signatures[iNSig]; + if(this.signatureIsRelatableToTarget(nSig, mSig, assignableTo, comparisonCache, comparisonInfo)) { + foundMatch = true; + break; + } + } + if(foundMatch) { + foundMatch = false; + continue; + } + return false; + } + return true; + }; + TypeChecker.prototype.signatureIsRelatableToTarget = function (sourceSig, targetSig, assignableTo, comparisonCache, comparisonInfo) { + if(!sourceSig.parameters || !targetSig.parameters) { + return false; + } + var targetVarArgCount = targetSig.hasVariableArgList ? targetSig.nonOptionalParameterCount - 1 : targetSig.nonOptionalParameterCount; + var sourceVarArgCount = sourceSig.hasVariableArgList ? sourceSig.nonOptionalParameterCount - 1 : sourceSig.nonOptionalParameterCount; + if(sourceVarArgCount > targetVarArgCount && !targetSig.hasVariableArgList) { + if(comparisonInfo) { + comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.SourceSignatureHasTooManyParameters; + comparisonInfo.addMessageToFront("Call signature expects " + targetVarArgCount + " or fewer parameters"); + } + return false; + } + var sourceReturnType = sourceSig.returnType.type; + var targetReturnType = targetSig.returnType.type; + if(targetReturnType != this.voidType) { + if(!this.sourceIsRelatableToTarget(sourceReturnType, targetReturnType, assignableTo, comparisonCache, comparisonInfo)) { + if(comparisonInfo) { + comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleReturnTypes; + } + return false; + } + } + var len = (sourceVarArgCount < targetVarArgCount && sourceSig.hasVariableArgList) ? targetVarArgCount : sourceVarArgCount; + var sourceParamType = null; + var targetParamType = null; + var sourceParamName = ""; + var targetParamName = ""; + for(var iSource = 0, iTarget = 0; iSource < len; iSource++ , iTarget++) { + if(!sourceSig.hasVariableArgList || iSource < sourceVarArgCount) { + sourceParamType = (sourceSig.parameters[iSource]).parameter.typeLink.type; + sourceParamName = (sourceSig.parameters[iSource]).parameter.symbol.name; + } else if(iSource == sourceVarArgCount) { + sourceParamType = (sourceSig.parameters[iSource]).parameter.typeLink.type; + if(sourceParamType.elementType) { + sourceParamType = sourceParamType.elementType; + } + sourceParamName = (sourceSig.parameters[iSource]).parameter.symbol.name; + } + if(iTarget < targetSig.parameters.length && iTarget < targetVarArgCount) { + targetParamType = (targetSig.parameters[iTarget]).parameter.typeLink.type; + targetParamName = (targetSig.parameters[iTarget]).parameter.symbol.name; + } else if(targetSig.hasVariableArgList && iTarget == targetVarArgCount) { + targetParamType = (targetSig.parameters[iTarget]).parameter.typeLink.type; + if(targetParamType.elementType) { + targetParamType = targetParamType.elementType; + } + targetParamName = (targetSig.parameters[iTarget]).parameter.symbol.name; + } + if(!(this.sourceIsRelatableToTarget(sourceParamType, targetParamType, assignableTo, comparisonCache, comparisonInfo) || this.sourceIsRelatableToTarget(targetParamType, sourceParamType, assignableTo, comparisonCache, comparisonInfo))) { + if(comparisonInfo) { + comparisonInfo.flags |= TypeScript.TypeRelationshipFlags.IncompatibleParameterTypes; + } + return false; + } + } + return true; + }; + return TypeChecker; + })(); + TypeScript.TypeChecker = TypeChecker; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var Continuation = (function () { + function Continuation(normalBlock) { + this.normalBlock = normalBlock; + this.exceptionBlock = -1; + } + return Continuation; + })(); + TypeScript.Continuation = Continuation; + function getBaseTypeLinks(bases, baseTypeLinks) { + if(bases) { + var len = bases.members.length; + if(baseTypeLinks == null) { + baseTypeLinks = new Array(); + } + for(var i = 0; i < len; i++) { + var baseExpr = bases.members[i]; + var name = baseExpr; + var typeLink = new TypeScript.TypeLink(); + typeLink.ast = name; + baseTypeLinks[baseTypeLinks.length] = typeLink; + } + } + return baseTypeLinks; + } + function getBases(type, typeDecl) { + type.extendsTypeLinks = getBaseTypeLinks(typeDecl.extendsList, type.extendsTypeLinks); + type.implementsTypeLinks = getBaseTypeLinks(typeDecl.implementsList, type.implementsTypeLinks); + } + function addPrototypeField(classType, ast, context) { + var field = new TypeScript.ValueLocation(); + field.typeLink = new TypeScript.TypeLink(); + field.typeLink.ast = ast; + field.typeLink.type = classType.instanceType; + var fieldSymbol = new TypeScript.FieldSymbol("prototype", ast.minChar, context.checker.locationInfo.unitIndex, true, field); + fieldSymbol.flags |= (TypeScript.SymbolFlags.Property | TypeScript.SymbolFlags.BuiltIn); + field.symbol = fieldSymbol; + fieldSymbol.declAST = ast; + classType.members.addPublicMember("prototype", fieldSymbol); + } + function createNewConstructGroupForType(type) { + var signature = new TypeScript.Signature(); + signature.returnType = new TypeScript.TypeLink(); + signature.returnType.type = type.instanceType; + signature.parameters = []; + type.construct = new TypeScript.SignatureGroup(); + type.construct.addSignature(signature); + } + TypeScript.createNewConstructGroupForType = createNewConstructGroupForType; + function cloneParentConstructGroupForChildType(child, parent) { + child.construct = new TypeScript.SignatureGroup(); + var sig = null; + if(!parent.construct) { + createNewConstructGroupForType(parent); + } + for(var i = 0; i < parent.construct.signatures.length; i++) { + sig = new TypeScript.Signature(); + sig.parameters = parent.construct.signatures[i].parameters; + sig.nonOptionalParameterCount = parent.construct.signatures[i].nonOptionalParameterCount; + sig.typeCheckStatus = parent.construct.signatures[i].typeCheckStatus; + sig.declAST = parent.construct.signatures[i].declAST; + sig.returnType = new TypeScript.TypeLink(); + sig.returnType.type = child.instanceType; + child.construct.addSignature(sig); + } + } + TypeScript.cloneParentConstructGroupForChildType = cloneParentConstructGroupForChildType; + TypeScript.globalId = "__GLO"; + function findTypeSymbolInScopeChain(name, scopeChain) { + var symbol = scopeChain.scope.find(name, false, true); + if(symbol == null && scopeChain.previous) { + symbol = findTypeSymbolInScopeChain(name, scopeChain.previous); + } + return symbol; + } + function findSymbolFromAlias(alias, context) { + var symbol = null; + switch(alias.nodeType) { + case TypeScript.NodeType.Name: + var name = (alias).text; + var isDynamic = TypeScript.isQuoted(name); + var findSym = function (id) { + if(context.members) { + return context.members.lookup(name); + } else { + return findTypeSymbolInScopeChain(name, context.topLevelScope); + } + }; + if(isDynamic) { + symbol = context.tcContext.checker.findSymbolForDynamicModule(name, context.tcContext.script.locationInfo.filename, findSym); + } else { + symbol = findSym(name); + } + break; + case TypeScript.NodeType.Dot: + var dottedExpr = alias; + var op1Sym = findSymbolFromAlias(dottedExpr.operand1, context); + if(op1Sym && op1Sym.getType()) { + symbol = findSymbolFromAlias(dottedExpr.operand2, context); + } + break; + default: + break; + } + if(symbol) { + var symType = symbol.getType(); + if(symType) { + var members = symType.members; + if(members) { + context.members = members.publicMembers; + } + } + } + return symbol; + } + function preCollectImportTypes(ast, parent, context) { + var scopeChain = context.scopeChain; + var typeSymbol = null; + var modType = null; + var importDecl = ast; + var aliasedModSymbol = findSymbolFromAlias(importDecl.alias, { + topLevelScope: scopeChain, + members: null, + tcContext: context + }); + var isGlobal = context.scopeChain.container == context.checker.gloMod; + if(aliasedModSymbol) { + var aliasedModType = aliasedModSymbol.getType(); + if(aliasedModType) { + modType = aliasedModType; + } + } + typeSymbol = new TypeScript.TypeSymbol(importDecl.id.text, importDecl.id.minChar, importDecl.limChar - importDecl.minChar, context.checker.locationInfo.unitIndex, modType); + typeSymbol.aliasLink = importDecl; + if(context.scopeChain.moduleDecl) { + typeSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; + typeSymbol.declModule = context.scopeChain.moduleDecl; + } + typeSymbol.declAST = importDecl; + importDecl.id.sym = typeSymbol; + scopeChain.scope.enter(scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isGlobal, true, false); + scopeChain.scope.enter(scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isGlobal, false, false); + return true; + } + TypeScript.preCollectImportTypes = preCollectImportTypes; + function preCollectModuleTypes(ast, parent, context) { + var scopeChain = context.scopeChain; + var moduleDecl = ast; + var isAmbient = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.Ambient); + var isEnum = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsEnum); + var isGlobal = context.scopeChain.container == context.checker.gloMod; + var isExported = TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.Exported); + var modName = (moduleDecl.name).text; + var isDynamic = TypeScript.isQuoted(modName); + var symbol = scopeChain.scope.findLocal(modName, false, false); + var typeSymbol = null; + var modType = null; + if(symbol && symbol.declAST && symbol.declAST.nodeType != TypeScript.NodeType.ModuleDeclaration) { + context.checker.errorReporter.simpleError(moduleDecl, "Conflicting symbol name for module '" + modName + "'"); + symbol = null; + modName = ""; + } + if(symbol) { + var modDeclAST = symbol.declAST; + var modDeclASTIsExported = TypeScript.hasFlag(modDeclAST.modFlags, TypeScript.ModuleFlags.Exported); + if((modDeclASTIsExported && !isExported) || (!modDeclASTIsExported && isExported)) { + context.checker.errorReporter.simpleError(moduleDecl, 'All contributions to a module must be "export" or none'); + } + } + if((symbol == null) || (symbol.kind() != TypeScript.SymbolKind.Type)) { + if(modType == null) { + var enclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + var ambientEnclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + modType = new TypeScript.ModuleType(enclosedTypes, ambientEnclosedTypes); + if(isEnum) { + modType.typeFlags |= TypeScript.TypeFlags.IsEnum; + } + modType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + modType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + modType.setHasImplementation(); + } + typeSymbol = new TypeScript.TypeSymbol(modName, moduleDecl.name.minChar, modName.length, context.checker.locationInfo.unitIndex, modType); + typeSymbol.isDynamic = TypeScript.isQuoted(moduleDecl.prettyName); + if(context.scopeChain.moduleDecl) { + typeSymbol.declModule = context.scopeChain.moduleDecl; + } + typeSymbol.declAST = moduleDecl; + typeSymbol.prettyName = moduleDecl.prettyName; + scopeChain.scope.enter(scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, true, isAmbient); + scopeChain.scope.enter(scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, false, isAmbient); + modType.symbol = typeSymbol; + } else { + typeSymbol = symbol; + var publicEnclosedTypes = typeSymbol.type.getAllEnclosedTypes().publicMembers; + var publicEnclosedTypesTable = (publicEnclosedTypes == null) ? new TypeScript.StringHashTable() : publicEnclosedTypes; + var enclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(publicEnclosedTypesTable, new TypeScript.StringHashTable())); + var publicEnclosedAmbientTypes = typeSymbol.type.getAllAmbientEnclosedTypes().publicMembers; + var publicAmbientEnclosedTypesTable = (publicEnclosedAmbientTypes == null) ? new TypeScript.StringHashTable() : publicEnclosedAmbientTypes; + var ambientEnclosedTypes = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(publicAmbientEnclosedTypesTable, new TypeScript.StringHashTable())); + var publicMembers = typeSymbol.type.members.publicMembers; + var publicMembersTable = (publicMembers == null) ? new TypeScript.StringHashTable() : publicMembers; + var members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(publicMembersTable, new TypeScript.StringHashTable())); + var publicAmbientMembers = typeSymbol.type.ambientMembers.publicMembers; + var publicAmbientMembersTable = (publicAmbientMembers == null) ? new TypeScript.StringHashTable() : publicAmbientMembers; + var ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(publicAmbientMembersTable, new TypeScript.StringHashTable())); + modType = new TypeScript.ModuleType(enclosedTypes, ambientEnclosedTypes); + if(isEnum) { + modType.typeFlags |= TypeScript.TypeFlags.IsEnum; + } + modType.members = members; + modType.ambientMembers = ambientMembers; + modType.setHasImplementation(); + modType.symbol = typeSymbol; + typeSymbol.addLocation(moduleDecl.minChar); + typeSymbol.expansions.push(modType); + typeSymbol.expansionsDeclAST.push(moduleDecl); + } + if(context.scopeChain.moduleDecl) { + context.scopeChain.moduleDecl.recordNonInterface(); + } + if(isExported) { + typeSymbol.flags |= TypeScript.SymbolFlags.Exported; + } + if((context.scopeChain.moduleDecl) || (context.scopeChain.container == context.checker.gloMod)) { + typeSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; + } + moduleDecl.mod = modType; + TypeScript.pushTypeCollectionScope(typeSymbol, modType.members, modType.ambientMembers, modType.enclosedTypes, modType.ambientEnclosedTypes, context, null, null, moduleDecl); + return true; + } + TypeScript.preCollectModuleTypes = preCollectModuleTypes; + function preCollectClassTypes(ast, parent, context) { + var scopeChain = context.scopeChain; + var classDecl = ast; + var classType; + var instanceType; + var typeSymbol = null; + var className = (classDecl.name).text; + var alreadyInScope = false; + var isAmbient = TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Ambient); + var isExported = TypeScript.hasFlag(classDecl.varFlags, TypeScript.VarFlags.Exported); + var isGlobal = context.scopeChain.container == context.checker.gloMod; + var containerMod = scopeChain.container; + var foundValSymbol = false; + typeSymbol = scopeChain.scope.findLocal(className, false, true); + if(!typeSymbol) { + var valTypeSymbol = scopeChain.scope.findLocal(className, false, false); + if(valTypeSymbol && valTypeSymbol.isType() && valTypeSymbol.declAST && valTypeSymbol.declAST.nodeType == TypeScript.NodeType.FuncDecl && (valTypeSymbol.declAST).isSignature()) { + typeSymbol = valTypeSymbol; + foundValSymbol = true; + if(isExported) { + typeSymbol.flags |= TypeScript.SymbolFlags.Exported; + } + if(isAmbient) { + typeSymbol.flags |= TypeScript.SymbolFlags.Ambient; + } + context.scopeChain.scope.enter(context.scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, true, isAmbient); + } + } + if(typeSymbol && !foundValSymbol && (typeSymbol.declAST != classDecl)) { + typeSymbol = null; + } + if(typeSymbol == null) { + var valueSymbol = scopeChain.scope.findLocal(className, false, false); + classType = new TypeScript.Type(); + classType.setHasImplementation(); + instanceType = new TypeScript.Type(); + instanceType.setHasImplementation(); + classType.instanceType = instanceType; + classType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + classType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + addPrototypeField(classType, classDecl, context); + instanceType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + instanceType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + typeSymbol = new TypeScript.TypeSymbol(className, classDecl.name.minChar, className.length, context.checker.locationInfo.unitIndex, classType); + typeSymbol.declAST = classDecl; + typeSymbol.instanceType = instanceType; + classType.symbol = typeSymbol; + instanceType.symbol = typeSymbol; + if(context.scopeChain.moduleDecl) { + context.scopeChain.moduleDecl.recordNonInterface(); + typeSymbol.declModule = context.scopeChain.moduleDecl; + typeSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; + } + if(isExported) { + typeSymbol.flags |= TypeScript.SymbolFlags.Exported; + } + if(isAmbient) { + typeSymbol.flags |= TypeScript.SymbolFlags.Ambient; + } + ast.type = classType; + context.scopeChain.scope.enter(context.scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, true, isAmbient); + if(valueSymbol == null) { + context.scopeChain.scope.enter(context.scopeChain.container, ast, typeSymbol, context.checker.errorReporter, isExported || isGlobal, false, isAmbient); + } + } else { + classType = typeSymbol.type; + if(classType.instanceType == null) { + classType.instanceType = new TypeScript.Type(); + classType.instanceType.setHasImplementation(); + classType.instanceType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + classType.instanceType.symbol = classType.symbol; + classType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + classType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + } + instanceType = classType.instanceType; + ast.type = classType; + } + if(!classDecl.constructorDecl) { + if(typeSymbol && typeSymbol.declAST && typeSymbol.declAST.type && typeSymbol.declAST.type.call && !(typeSymbol.declAST).isOverload) { + context.checker.errorReporter.duplicateIdentifier(typeSymbol.declAST, typeSymbol.name); + } + createNewConstructGroupForType(classDecl.type); + } + classType.typeFlags |= TypeScript.TypeFlags.IsClass; + instanceType.typeFlags |= TypeScript.TypeFlags.IsClass; + getBases(instanceType, classDecl); + TypeScript.pushTypeCollectionScope(typeSymbol, instanceType.members, instanceType.ambientMembers, null, null, context, instanceType, classType, null); + return true; + } + TypeScript.preCollectClassTypes = preCollectClassTypes; + function preCollectInterfaceTypes(ast, parent, context) { + var scopeChain = context.scopeChain; + var interfaceDecl = ast; + var interfaceSymbol = null; + var interfaceType = null; + var isExported = TypeScript.hasFlag(interfaceDecl.varFlags, TypeScript.VarFlags.Exported); + var isGlobal = context.scopeChain.container == context.checker.gloMod; + var alreadyInScope = true; + alreadyInScope = false; + var interfaceName = (interfaceDecl.name).text; + interfaceSymbol = scopeChain.scope.findLocal(interfaceName, false, true); + if(interfaceSymbol == null) { + interfaceType = new TypeScript.Type(); + interfaceSymbol = new TypeScript.TypeSymbol(interfaceName, interfaceDecl.name.minChar, interfaceName.length, context.checker.locationInfo.unitIndex, interfaceType); + interfaceType.symbol = interfaceSymbol; + interfaceType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + interfaceType.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + interfaceSymbol.declAST = interfaceDecl; + interfaceSymbol.declModule = context.scopeChain.moduleDecl; + } else { + alreadyInScope = true; + interfaceType = interfaceSymbol.type; + } + if(!interfaceType) { + interfaceType = context.checker.anyType; + } + ast.type = interfaceType; + getBases(interfaceType, interfaceDecl); + if(isExported) { + interfaceSymbol.flags |= TypeScript.SymbolFlags.Exported; + } + if(context.scopeChain.moduleDecl) { + interfaceSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; + } + if(!alreadyInScope) { + context.scopeChain.scope.enter(context.scopeChain.container, ast, interfaceSymbol, context.checker.errorReporter, isGlobal || isExported, true, false); + } + TypeScript.pushTypeCollectionScope(interfaceSymbol, interfaceType.members, interfaceType.ambientMembers, null, null, context, interfaceType, null, null); + return true; + } + TypeScript.preCollectInterfaceTypes = preCollectInterfaceTypes; + function preCollectArgDeclTypes(ast, parent, context) { + var scopeChain = context.scopeChain; + var argDecl = ast; + if(TypeScript.hasFlag(argDecl.varFlags, TypeScript.VarFlags.Public | TypeScript.VarFlags.Private)) { + var field = new TypeScript.ValueLocation(); + var isPrivate = TypeScript.hasFlag(argDecl.varFlags, TypeScript.VarFlags.Private); + var fieldSymbol = new TypeScript.FieldSymbol(argDecl.id.text, argDecl.id.minChar, context.checker.locationInfo.unitIndex, !TypeScript.hasFlag(argDecl.varFlags, TypeScript.VarFlags.Readonly), field); + fieldSymbol.transferVarFlags(argDecl.varFlags); + field.symbol = fieldSymbol; + fieldSymbol.declAST = ast; + argDecl.parameterPropertySym = fieldSymbol; + context.scopeChain.scope.enter(context.scopeChain.container, ast, fieldSymbol, context.checker.errorReporter, !isPrivate, false, false); + field.typeLink = TypeScript.getTypeLink(argDecl.typeExpr, context.checker, argDecl.init == null); + argDecl.sym = fieldSymbol; + } + return false; + } + TypeScript.preCollectArgDeclTypes = preCollectArgDeclTypes; + function preCollectVarDeclTypes(ast, parent, context) { + var scopeChain = context.scopeChain; + var varDecl = ast; + var isAmbient = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Ambient); + var isExported = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Exported); + var isGlobal = context.scopeChain.container == context.checker.gloMod; + var isProperty = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Property); + var isStatic = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Static); + var isPrivate = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Private); + var isOptional = TypeScript.hasFlag(varDecl.id.flags, TypeScript.ASTFlags.OptionalName); + if(context.scopeChain.moduleDecl) { + context.scopeChain.moduleDecl.recordNonInterface(); + } + if(isProperty || isExported || (context.scopeChain.container == context.checker.gloMod) || context.scopeChain.moduleDecl) { + if(isAmbient) { + var existingSym = scopeChain.scope.findLocal(varDecl.id.text, false, false); + if(existingSym) { + varDecl.sym = existingSym; + return false; + } + } + if(varDecl.id == null) { + context.checker.errorReporter.simpleError(varDecl, "Expected variable identifier at this location"); + return false; + } + var field = new TypeScript.ValueLocation(); + var fieldSymbol = new TypeScript.FieldSymbol(varDecl.id.text, varDecl.id.minChar, context.checker.locationInfo.unitIndex, (varDecl.varFlags & TypeScript.VarFlags.Readonly) == TypeScript.VarFlags.None, field); + fieldSymbol.transferVarFlags(varDecl.varFlags); + if(isOptional) { + fieldSymbol.flags |= TypeScript.SymbolFlags.Optional; + } + field.symbol = fieldSymbol; + fieldSymbol.declAST = ast; + if((context.scopeChain.moduleDecl) || (context.scopeChain.container == context.checker.gloMod)) { + fieldSymbol.flags |= TypeScript.SymbolFlags.ModuleMember; + fieldSymbol.declModule = context.scopeChain.moduleDecl; + } + if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Property) && isStatic && context.scopeChain.classType) { + if(!context.scopeChain.classType.members.publicMembers.add(varDecl.id.text, fieldSymbol)) { + context.checker.errorReporter.duplicateIdentifier(ast, fieldSymbol.name); + } + fieldSymbol.container = context.scopeChain.classType.symbol; + } else { + context.scopeChain.scope.enter(context.scopeChain.container, ast, fieldSymbol, context.checker.errorReporter, !isPrivate && (isProperty || isExported || isGlobal || isStatic), false, isAmbient); + } + if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Exported)) { + fieldSymbol.flags |= TypeScript.SymbolFlags.Exported; + } + field.typeLink = TypeScript.getTypeLink(varDecl.typeExpr, context.checker, varDecl.init == null); + varDecl.sym = fieldSymbol; + } + return false; + } + TypeScript.preCollectVarDeclTypes = preCollectVarDeclTypes; + function preCollectFuncDeclTypes(ast, parent, context) { + var scopeChain = context.scopeChain; + if(context.scopeChain.moduleDecl) { + context.scopeChain.moduleDecl.recordNonInterface(); + } + var funcDecl = ast; + var fgSym = null; + var nameText = funcDecl.getNameText(); + var isExported = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Exported | TypeScript.FncFlags.ClassPropertyMethodExported); + var isStatic = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static); + var isPrivate = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Private); + var isConstructor = funcDecl.isConstructMember() || funcDecl.isConstructor; + var containerSym = (((funcDecl.isMethod() && isStatic) || funcDecl.isAccessor()) && context.scopeChain.classType ? context.scopeChain.classType.symbol : context.scopeChain.container); + var containerScope = context.scopeChain.scope; + var isGlobal = containerSym == context.checker.gloMod; + var isOptional = funcDecl.name && TypeScript.hasFlag(funcDecl.name.flags, TypeScript.ASTFlags.OptionalName); + var go = false; + var foundSymbol = false; + if(isConstructor && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { + containerSym = containerSym.container; + containerScope = scopeChain.previous.scope; + } + funcDecl.unitIndex = context.checker.locationInfo.unitIndex; + if(!funcDecl.isConstructor && containerSym && containerSym.declAST && containerSym.declAST.nodeType == TypeScript.NodeType.FuncDecl && (containerSym.declAST).isConstructor && !funcDecl.isMethod()) { + return go; + } + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Signature)) { + var instType = context.scopeChain.thisType; + if(nameText && nameText != "__missing") { + if(isStatic) { + fgSym = containerSym.type.members.allMembers.lookup(nameText); + } else { + fgSym = containerScope.findLocal(nameText, false, false); + if(fgSym == null) { + fgSym = containerScope.findLocal(nameText, false, true); + } + } + if(fgSym) { + foundSymbol = true; + if(!funcDecl.isSignature() && (TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Ambient) != TypeScript.hasFlag(fgSym.flags, TypeScript.SymbolFlags.Ambient))) { + fgSym = null; + } + } + } + if(fgSym == null) { + if(!(funcDecl.isSpecialFn())) { + fgSym = context.checker.createFunctionSignature(funcDecl, containerSym, containerScope, null, !foundSymbol).declAST.type.symbol; + } else { + fgSym = context.checker.createFunctionSignature(funcDecl, containerSym, containerScope, containerSym, false).declAST.type.symbol; + } + if(fgSym.declAST == null || !funcDecl.isSpecialFn()) { + fgSym.declAST = ast; + } + } else { + if((fgSym.kind() == TypeScript.SymbolKind.Type)) { + fgSym = context.checker.createFunctionSignature(funcDecl, containerSym, containerScope, fgSym, false).declAST.type.symbol; + } else { + context.checker.errorReporter.simpleError(funcDecl, "Function or method '" + funcDecl.name.actualText + "' already declared as a property"); + } + } + if(funcDecl.isSpecialFn() && !isStatic) { + funcDecl.type = instType ? instType : fgSym.type; + } else { + funcDecl.type = fgSym.type; + } + } else { + if(nameText) { + if(isStatic) { + fgSym = containerSym.type.members.allMembers.lookup(nameText); + } else { + if(funcDecl.isConstructor && context.scopeChain.previous) { + fgSym = context.scopeChain.previous.scope.findLocal(nameText, false, false); + } + if(fgSym == null) { + fgSym = containerScope.findLocal(nameText, false, false); + } + } + if(fgSym) { + foundSymbol = true; + if(!isConstructor && fgSym.declAST.nodeType == TypeScript.NodeType.FuncDecl && !(fgSym.declAST).isAccessor() && !(fgSym.declAST).isSignature()) { + fgSym = null; + foundSymbol = false; + } + } + } + if(fgSym && !fgSym.isAccessor() && fgSym.type && fgSym.type.construct && fgSym.type.construct.signatures != [] && (fgSym.type.construct.signatures[0].declAST == null || !TypeScript.hasFlag(fgSym.type.construct.signatures[0].declAST.fncFlags, TypeScript.FncFlags.Ambient)) && !funcDecl.isConstructor) { + context.checker.errorReporter.simpleError(funcDecl, "Functions may not have class overloads"); + } + if(fgSym && !(fgSym.kind() == TypeScript.SymbolKind.Type) && funcDecl.isMethod() && !funcDecl.isAccessor() && !funcDecl.isConstructor) { + context.checker.errorReporter.simpleError(funcDecl, "Function or method '" + funcDecl.name.actualText + "' already declared as a property"); + fgSym.type = context.checker.anyType; + } + if(fgSym && !fgSym.isAccessor() && funcDecl.isAccessor()) { + fgSym = null; + } + var sig = context.checker.createFunctionSignature(funcDecl, containerSym, containerScope, fgSym, !foundSymbol); + if(((!fgSym || fgSym.declAST.nodeType != TypeScript.NodeType.FuncDecl) && funcDecl.isAccessor()) || (fgSym && fgSym.isAccessor())) { + funcDecl.accessorSymbol = context.checker.createAccessorSymbol(funcDecl, fgSym, containerSym.type, (funcDecl.isMethod() && isStatic), true, containerScope, containerSym); + } + funcDecl.type.symbol.declAST = ast; + if(funcDecl.isConstructor) { + go = true; + } + ; + } + if(isExported) { + if(funcDecl.type.call) { + funcDecl.type.symbol.flags |= TypeScript.SymbolFlags.Exported; + } + if(fgSym && !fgSym.isAccessor() && fgSym.kind() == TypeScript.SymbolKind.Type && fgSym.type.call) { + fgSym.flags |= TypeScript.SymbolFlags.Exported; + } + } + if(context.scopeChain.moduleDecl && !funcDecl.isSpecialFn()) { + funcDecl.type.symbol.flags |= TypeScript.SymbolFlags.ModuleMember; + funcDecl.type.symbol.declModule = context.scopeChain.moduleDecl; + } + if(fgSym && isOptional) { + fgSym.flags |= TypeScript.SymbolFlags.Optional; + } + return go; + } + TypeScript.preCollectFuncDeclTypes = preCollectFuncDeclTypes; + function preCollectTypes(ast, parent, walker) { + var context = walker.state; + var go = false; + var scopeChain = context.scopeChain; + if(ast.nodeType == TypeScript.NodeType.Script) { + var script = ast; + context.script = script; + go = true; + } else if(ast.nodeType == TypeScript.NodeType.List) { + go = true; + } else if(ast.nodeType == TypeScript.NodeType.ImportDeclaration) { + go = preCollectImportTypes(ast, parent, context); + } else if(ast.nodeType == TypeScript.NodeType.With) { + go = false; + } else if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { + go = preCollectModuleTypes(ast, parent, context); + } else if(ast.nodeType == TypeScript.NodeType.ClassDeclaration) { + go = preCollectClassTypes(ast, parent, context); + } else if(ast.nodeType == TypeScript.NodeType.Block) { + go = true; + } else if(ast.nodeType == TypeScript.NodeType.InterfaceDeclaration) { + go = preCollectInterfaceTypes(ast, parent, context); + } else if(ast.nodeType == TypeScript.NodeType.ArgDecl) { + go = preCollectArgDeclTypes(ast, parent, context); + } else if(ast.nodeType == TypeScript.NodeType.VarDecl) { + go = preCollectVarDeclTypes(ast, parent, context); + } else if(ast.nodeType == TypeScript.NodeType.FuncDecl) { + go = preCollectFuncDeclTypes(ast, parent, context); + } else { + if(ast.isStatementOrExpression() && context.scopeChain.moduleDecl) { + context.scopeChain.moduleDecl.recordNonInterface(); + } + } + walker.options.goChildren = go; + return ast; + } + TypeScript.preCollectTypes = preCollectTypes; + function postCollectTypes(ast, parent, walker) { + var context = walker.state; + if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { + TypeScript.popTypeCollectionScope(context); + } else if(ast.nodeType == TypeScript.NodeType.ClassDeclaration) { + TypeScript.popTypeCollectionScope(context); + } else if(ast.nodeType == TypeScript.NodeType.InterfaceDeclaration) { + TypeScript.popTypeCollectionScope(context); + } + return ast; + } + TypeScript.postCollectTypes = postCollectTypes; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var ScopeChain = (function () { + function ScopeChain(container, previous, scope) { + this.container = container; + this.previous = previous; + this.scope = scope; + } + return ScopeChain; + })(); + TypeScript.ScopeChain = ScopeChain; + var BBUseDefInfo = (function () { + function BBUseDefInfo(bb) { + this.bb = bb; + this.defsBySymbol = new Array(); + this.useIndexBySymbol = new Array(); + } + BBUseDefInfo.prototype.updateTop = function () { + var temp = new BitVector(this.top.bitCount); + for(var i = 0, succLen = this.bb.successors.length; i < succLen; i++) { + var succ = this.bb.successors[i]; + if(succ.useDef) { + temp.union(succ.useDef.top); + } + } + temp.difference(this.kill); + temp.union(this.gen); + var changed = temp.notEq(this.top); + this.top = temp; + return changed; + }; + BBUseDefInfo.prototype.initialize = function (useDefContext) { + var _this = this; + var defSym = function (sym, context) { + if(context.isLocalSym(sym)) { + var index = context.getSymbolIndex(sym); + _this.useIndexBySymbol[index] = new Array(); + _this.defsBySymbol[index] = true; + } + }; + var useSym = function (sym, context, ast) { + if(context.isLocalSym(sym)) { + var symIndex = context.getSymbolIndex(sym); + if(_this.useIndexBySymbol[symIndex] == undefined) { + _this.useIndexBySymbol[symIndex] = new Array(); + } + var symUses = _this.useIndexBySymbol[symIndex]; + var astIndex = context.getUseIndex(ast); + context.addUse(symIndex, astIndex); + symUses.push(astIndex); + } + }; + function initUseDefPre(cur, parent, walker) { + var context = walker.state; + if(cur == null) { + cur = null; + } + if(cur.nodeType == TypeScript.NodeType.VarDecl) { + var varDecl = cur; + if(varDecl.init || TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.AutoInit)) { + defSym(varDecl.sym, context); + } + } else if(cur.nodeType == TypeScript.NodeType.Name) { + if(parent) { + if(parent.nodeType == TypeScript.NodeType.Asg) { + var asg = parent; + if(asg.operand1 == cur) { + return cur; + } + } else if(parent.nodeType == TypeScript.NodeType.VarDecl) { + var parentDecl = parent; + if(parentDecl.id == cur) { + return cur; + } + } + } + var id = cur; + useSym(id.sym, context, cur); + } else if((cur.nodeType >= TypeScript.NodeType.Asg) && (cur.nodeType <= TypeScript.NodeType.LastAsg)) { + var asg = cur; + if(asg.operand1 && (asg.operand1.nodeType == TypeScript.NodeType.Name)) { + var id = asg.operand1; + defSym(id.sym, context); + } + } else if(cur.nodeType == TypeScript.NodeType.FuncDecl) { + walker.options.goChildren = false; + } + return cur; + } + var options = new TypeScript.AstWalkOptions(); + options.reverseSiblings = true; + TypeScript.getAstWalkerFactory().walk(this.bb.content, initUseDefPre, null, options, useDefContext); + }; + BBUseDefInfo.prototype.initializeGen = function (useDefContext) { + var symbolLen = this.useIndexBySymbol.length; + var bitCount = useDefContext.uses.length; + this.gen = new BitVector(bitCount); + for(var s = 0; s < symbolLen; s++) { + var symUses = this.useIndexBySymbol[s]; + if((symUses != undefined) && (symUses.length > 0)) { + for(var u = 0, uLen = symUses.length; u < uLen; u++) { + this.gen.set(symUses[u], true); + } + } + } + this.top = this.gen; + }; + BBUseDefInfo.prototype.initializeKill = function (useDefContext) { + this.kill = new BitVector(this.gen.bitCount); + for(var s = 0, symbolLen = this.defsBySymbol.length; s < symbolLen; s++) { + if(this.defsBySymbol[s]) { + var globalSymUses = useDefContext.useIndexBySymbol[s]; + if(globalSymUses) { + for(var u = 0, useLen = globalSymUses.length; u < useLen; u++) { + this.kill.set(globalSymUses[u], true); + } + } + } + } + }; + return BBUseDefInfo; + })(); + TypeScript.BBUseDefInfo = BBUseDefInfo; + var UseDefContext = (function () { + function UseDefContext() { + this.useIndexBySymbol = new Array(); + this.uses = new Array(); + this.symbols = new Array(); + this.symbolMap = new TypeScript.StringHashTable(); + this.symbolCount = 0; + } + UseDefContext.prototype.getSymbolIndex = function (sym) { + var name = sym.name; + var index = (this.symbolMap.lookup(name)); + if(index == null) { + index = this.symbolCount++; + this.symbols[index] = sym; + this.symbolMap.add(name, index); + } + return index; + }; + UseDefContext.prototype.addUse = function (symIndex, astIndex) { + var useBySym = this.useIndexBySymbol[symIndex]; + if(useBySym == undefined) { + useBySym = new Array(); + this.useIndexBySymbol[symIndex] = useBySym; + } + useBySym[useBySym.length] = astIndex; + }; + UseDefContext.prototype.getUseIndex = function (ast) { + this.uses[this.uses.length] = ast; + return this.uses.length - 1; + }; + UseDefContext.prototype.isLocalSym = function (sym) { + return (sym && (sym.container == this.func) && (sym.kind() == TypeScript.SymbolKind.Variable)); + }; + UseDefContext.prototype.killSymbol = function (sym, bbUses) { + var index = this.symbolMap.lookup(sym.name); + var usesOfSym = this.useIndexBySymbol[index]; + for(var k = 0, len = usesOfSym.length; k < len; k++) { + bbUses.set(usesOfSym[k], true); + } + }; + return UseDefContext; + })(); + TypeScript.UseDefContext = UseDefContext; + var BitVector = (function () { + function BitVector(bitCount) { + this.bitCount = bitCount; + this.firstBits = 0; + this.restOfBits = null; + if(this.bitCount > BitVector.packBits) { + this.restOfBits = new Array(); + var len = Math.floor(this.bitCount / BitVector.packBits); + for(var i = 0; i < len; i++) { + this.restOfBits[i] = 0; + } + } + } + BitVector.packBits = 30; + BitVector.prototype.set = function (bitIndex, value) { + if(bitIndex < BitVector.packBits) { + if(value) { + this.firstBits |= (1 << bitIndex); + } else { + this.firstBits &= (~(1 << bitIndex)); + } + } else { + var offset = Math.floor(bitIndex / BitVector.packBits) - 1; + var localIndex = bitIndex % BitVector.packBits; + if(value) { + this.restOfBits[offset] |= (1 << localIndex); + } else { + this.restOfBits[offset] &= (~(1 << localIndex)); + } + } + }; + BitVector.prototype.map = function (fn) { + var k; + for(k = 0; k < BitVector.packBits; k++) { + if(k == this.bitCount) { + return; + } + if(((1 << k) & this.firstBits) != 0) { + fn(k); + } + } + if(this.restOfBits) { + var len; + var cumu = BitVector.packBits; + for(k = 0 , len = this.restOfBits.length; k < len; k++) { + var myBits = this.restOfBits[k]; + for(var j = 0; j < BitVector.packBits; j++) { + if(((1 << j) & myBits) != 0) { + fn(cumu); + } + cumu++; + if(cumu == this.bitCount) { + return; + } + } + } + } + }; + BitVector.prototype.union = function (b) { + this.firstBits |= b.firstBits; + if(this.restOfBits) { + for(var k = 0, len = this.restOfBits.length; k < len; k++) { + var myBits = this.restOfBits[k]; + var bBits = b.restOfBits[k]; + this.restOfBits[k] = myBits | bBits; + } + } + }; + BitVector.prototype.intersection = function (b) { + this.firstBits &= b.firstBits; + if(this.restOfBits) { + for(var k = 0, len = this.restOfBits.length; k < len; k++) { + var myBits = this.restOfBits[k]; + var bBits = b.restOfBits[k]; + this.restOfBits[k] = myBits & bBits; + } + } + }; + BitVector.prototype.notEq = function (b) { + if(this.firstBits != b.firstBits) { + return true; + } + if(this.restOfBits) { + for(var k = 0, len = this.restOfBits.length; k < len; k++) { + var myBits = this.restOfBits[k]; + var bBits = b.restOfBits[k]; + if(myBits != bBits) { + return true; + } + } + } + return false; + }; + BitVector.prototype.difference = function (b) { + var oldFirstBits = this.firstBits; + this.firstBits &= (~b.firstBits); + if(this.restOfBits) { + for(var k = 0, len = this.restOfBits.length; k < len; k++) { + var myBits = this.restOfBits[k]; + var bBits = b.restOfBits[k]; + this.restOfBits[k] &= (~bBits); + } + } + }; + return BitVector; + })(); + TypeScript.BitVector = BitVector; + var BasicBlock = (function () { + function BasicBlock() { + this.predecessors = new Array(); + this.index = -1; + this.markValue = 0; + this.successors = new Array(); + this.useDef = null; + this.content = new TypeScript.ASTList(); + } + BasicBlock.prototype.marked = function (markBase) { + return this.markValue > markBase; + }; + BasicBlock.prototype.mark = function () { + this.markValue++; + }; + BasicBlock.prototype.addSuccessor = function (successor) { + this.successors[this.successors.length] = successor; + successor.predecessors[successor.predecessors.length] = this; + }; + return BasicBlock; + })(); + TypeScript.BasicBlock = BasicBlock; + var ControlFlowContext = (function () { + function ControlFlowContext(current, exit) { + this.current = current; + this.exit = exit; + this.entry = null; + this.unreachable = null; + this.noContinuation = false; + this.statementStack = new Array(); + this.currentSwitch = new Array(); + this.markBase = 0; + this.linearBBs = new Array(); + this.entry = this.current; + } + ControlFlowContext.prototype.walk = function (ast, parent) { + return this.walker.walk(ast, parent); + }; + ControlFlowContext.prototype.pushSwitch = function (bb) { + this.currentSwitch.push(bb); + }; + ControlFlowContext.prototype.popSwitch = function () { + return this.currentSwitch.pop(); + }; + ControlFlowContext.prototype.reportUnreachable = function (er) { + if(this.unreachable && (this.unreachable.length > 0)) { + var len = this.unreachable.length; + for(var i = 0; i < len; i++) { + var unreachableAST = this.unreachable[i]; + if(unreachableAST.nodeType != TypeScript.NodeType.EndCode) { + er.simpleError(unreachableAST, "unreachable code"); + } + } + } + }; + ControlFlowContext.prototype.printAST = function (ast, outfile) { + var printContext = new TypeScript.PrintContext(outfile, null); + printContext.increaseIndent(); + TypeScript.getAstWalkerFactory().walk(ast, TypeScript.prePrintAST, TypeScript.postPrintAST, null, printContext); + printContext.decreaseIndent(); + }; + ControlFlowContext.prototype.printBlockContent = function (bb, outfile) { + var content = bb.content; + for(var i = 0, len = content.members.length; i < len; i++) { + var ast = content.members[i]; + this.printAST(ast, outfile); + } + }; + ControlFlowContext.prototype.bfs = function (nodeFunc, edgeFunc, preEdges, postEdges) { + var markValue = this.markBase++; + var q = new Array(); + q[q.length] = this.entry; + while(q.length > 0) { + var bb = q.pop(); + if(!(bb.marked(markValue))) { + bb.mark(); + if(nodeFunc) { + nodeFunc(bb); + } + var succLen = bb.successors.length; + if(succLen > 0) { + if(preEdges) { + preEdges(); + } + for(var j = succLen - 1; j >= 0; j--) { + var successor = bb.successors[j]; + if(!(successor.marked(this.markBase))) { + if(edgeFunc) { + edgeFunc(bb, successor); + } + q[q.length] = successor; + } + } + if(postEdges) { + postEdges(); + } + } + } + } + }; + ControlFlowContext.prototype.useDef = function (er, funcSym) { + var _this = this; + var useDefContext = new UseDefContext(); + useDefContext.func = funcSym; + var useDefInit = function (bb) { + bb.useDef = new BBUseDefInfo(bb); + bb.useDef.initialize(useDefContext); + _this.linearBBs[_this.linearBBs.length] = bb; + }; + this.bfs(useDefInit, null, null, null); + var i, bbLen; + for(i = 0 , bbLen = this.linearBBs.length; i < bbLen; i++) { + this.linearBBs[i].useDef.initializeGen(useDefContext); + this.linearBBs[i].useDef.initializeKill(useDefContext); + } + var changed = true; + while(changed) { + changed = false; + for(i = 0; i < bbLen; i++) { + changed = this.linearBBs[i].useDef.updateTop() || changed; + } + } + var top = this.entry.useDef.top; + top.map(function (index) { + var ast = useDefContext.uses[index]; + er.simpleError(ast, "use of variable '" + ast.actualText + "' that is not definitely assigned"); + }); + }; + ControlFlowContext.prototype.print = function (outfile) { + var _this = this; + var index = 0; + var node = function (bb) { + if(bb.index < 0) { + bb.index = index++; + } + if(bb == _this.exit) { + outfile.WriteLine("Exit block with index " + bb.index); + } else { + outfile.WriteLine("Basic block with index " + bb.index); + _this.printBlockContent(bb, outfile); + } + }; + function preEdges() { + outfile.Write(" Branches to "); + } + function postEdges() { + outfile.WriteLine(""); + } + function edge(node1, node2) { + if(node2.index < 0) { + node2.index = index++; + } + outfile.Write(node2.index + " "); + } + this.bfs(node, edge, preEdges, postEdges); + if(this.unreachable != null) { + for(var i = 0, len = this.unreachable.length; i < len; i++) { + outfile.WriteLine("Unreachable basic block ..."); + this.printAST(this.unreachable[i], outfile); + } + } + }; + ControlFlowContext.prototype.pushStatement = function (stmt, continueBB, breakBB) { + this.statementStack.push({ + stmt: stmt, + continueBB: continueBB, + breakBB: breakBB + }); + }; + ControlFlowContext.prototype.popStatement = function () { + return this.statementStack.pop(); + }; + ControlFlowContext.prototype.returnStmt = function () { + this.current.addSuccessor(this.exit); + this.setUnreachable(); + }; + ControlFlowContext.prototype.setUnreachable = function () { + this.current = null; + this.noContinuation = true; + }; + ControlFlowContext.prototype.addUnreachable = function (ast) { + if(this.unreachable === null) { + this.unreachable = new Array(); + } + this.unreachable[this.unreachable.length] = ast; + }; + ControlFlowContext.prototype.unconditionalBranch = function (target, isContinue) { + var targetBB = null; + for(var i = 0, len = this.statementStack.length; i < len; i++) { + var targetInfo = this.statementStack[i]; + if(targetInfo.stmt == target) { + if(isContinue) { + targetBB = targetInfo.continueBB; + } else { + targetBB = targetInfo.breakBB; + } + break; + } + } + if(targetBB) { + this.current.addSuccessor(targetBB); + } + this.setUnreachable(); + }; + ControlFlowContext.prototype.addContent = function (ast) { + if(this.current) { + this.current.content.append(ast); + } + }; + return ControlFlowContext; + })(); + TypeScript.ControlFlowContext = ControlFlowContext; + var ResolutionDataCache = (function () { + function ResolutionDataCache() { + this.cacheSize = 16; + this.rdCache = []; + this.nextUp = 0; + for(var i = 0; i < this.cacheSize; i++) { + this.rdCache[i] = { + actuals: new Array(), + exactCandidates: new Array(), + conversionCandidates: new Array(), + id: i + }; + } + } + ResolutionDataCache.prototype.getResolutionData = function () { + var rd = null; + if(this.nextUp < this.cacheSize) { + rd = this.rdCache[this.nextUp]; + } + if(rd == null) { + this.cacheSize++; + rd = { + actuals: new Array(), + exactCandidates: new Array(), + conversionCandidates: new Array(), + id: this.cacheSize + }; + this.rdCache[this.cacheSize] = rd; + } + this.nextUp++; + return rd; + }; + ResolutionDataCache.prototype.returnResolutionData = function (rd) { + rd.actuals.length = 0; + rd.exactCandidates.length = 0; + rd.conversionCandidates.length = 0; + this.nextUp = rd.id; + }; + return ResolutionDataCache; + })(); + TypeScript.ResolutionDataCache = ResolutionDataCache; + var TypeFlow = (function () { + function TypeFlow(logger, initScope, parser, checker) { + this.logger = logger; + this.initScope = initScope; + this.parser = parser; + this.checker = checker; + this.thisFnc = null; + this.thisClassNode = null; + this.enclosingFncIsMethod = false; + this.arrayInterfaceType = null; + this.stringInterfaceType = null; + this.objectInterfaceType = null; + this.functionInterfaceType = null; + this.numberInterfaceType = null; + this.booleanInterfaceType = null; + this.iargumentsInterfaceType = null; + this.currentScript = null; + this.inImportTypeCheck = false; + this.inTypeRefTypeCheck = false; + this.inArrayElementTypeCheck = false; + this.resolutionDataCache = new ResolutionDataCache(); + this.nestingLevel = 0; + this.inSuperCall = false; + this.checker.typeFlow = this; + this.scope = this.initScope; + this.globalScope = this.initScope; + this.doubleType = this.checker.numberType; + this.booleanType = this.checker.booleanType; + this.stringType = this.checker.stringType; + this.anyType = this.checker.anyType; + this.regexType = this.anyType; + this.nullType = this.checker.nullType; + this.voidType = this.checker.voidType; + this.arrayAnyType = this.checker.makeArrayType(this.anyType); + } + TypeFlow.prototype.initLibs = function () { + var arraySym = this.globalScope.find("Array", false, true); + if(arraySym && (arraySym.kind() == TypeScript.SymbolKind.Type)) { + this.arrayInterfaceType = (arraySym).type; + } + var stringSym = this.globalScope.find("String", false, true); + if(stringSym && (stringSym.kind() == TypeScript.SymbolKind.Type)) { + this.stringInterfaceType = (stringSym).type; + } + var objectSym = this.globalScope.find("Object", false, true); + if(objectSym && (objectSym.kind() == TypeScript.SymbolKind.Type)) { + this.objectInterfaceType = (objectSym).type; + } + var fnSym = this.globalScope.find("Function", false, true); + if(fnSym && (fnSym.kind() == TypeScript.SymbolKind.Type)) { + this.functionInterfaceType = (fnSym).type; + } + var numberSym = this.globalScope.find("Number", false, true); + if(numberSym && (numberSym.kind() == TypeScript.SymbolKind.Type)) { + this.numberInterfaceType = (numberSym).type; + } + var booleanSym = this.globalScope.find("Boolean", false, true); + if(booleanSym && (booleanSym.kind() == TypeScript.SymbolKind.Type)) { + this.booleanInterfaceType = (booleanSym).type; + } + var regexSym = this.globalScope.find("RegExp", false, true); + if(regexSym && (regexSym.kind() == TypeScript.SymbolKind.Type)) { + this.regexType = (regexSym).type; + } + }; + TypeFlow.prototype.cast = function (ast, type) { + return this.castWithCoercion(ast, type, true, false); + }; + TypeFlow.prototype.castWithCoercion = function (ast, type, applyCoercion, typeAssertion) { + var comparisonInfo = new TypeScript.TypeComparisonInfo(); + if(this.checker.sourceIsAssignableToTarget(ast.type, type, comparisonInfo) || (typeAssertion && this.checker.sourceIsAssignableToTarget(type, ast.type, comparisonInfo))) { + if(applyCoercion) { + if(type == null) { + ast.type = this.anyType; + } else if(type.isClass()) { + ast.type = type.instanceType; + } else { + ast.type = type; + } + } + return ast; + } else { + this.checker.errorReporter.incompatibleTypes(ast, ast.type, type, null, this.scope, comparisonInfo); + return ast; + } + }; + TypeFlow.prototype.inScopeTypeCheck = function (ast, enclosingScope) { + var prevScope = this.scope; + this.scope = enclosingScope; + var svThisFnc = this.thisFnc; + var svThisType = this.thisType; + var svThisClassNode = this.thisClassNode; + var svCurrentModDecl = this.checker.currentModDecl; + var prevMethodStatus = this.enclosingFncIsMethod; + var container = this.scope.container; + var fnc = null; + while(container) { + if(container.kind() == TypeScript.SymbolKind.Type) { + var typeSym = container; + var type = typeSym.type; + if(type.call) { + if(fnc == null) { + this.enclosingFncIsMethod = typeSym.isMethod; + fnc = container.declAST; + } + } + if(type.isClass()) { + this.thisType = type.instanceType; + if(typeSym.declAST && (typeSym.declAST.nodeType == TypeScript.NodeType.ClassDeclaration)) { + this.thisClassNode = typeSym.declAST; + } + break; + } + if(type.isModuleType()) { + this.checker.currentModDecl = typeSym.declAST; + break; + } + } + container = container.container; + } + this.thisFnc = fnc; + var updated = this.typeCheck(ast); + this.thisFnc = svThisFnc; + this.thisType = svThisType; + this.thisClassNode = svThisClassNode; + this.checker.currentModDecl = svCurrentModDecl; + this.enclosingFncIsMethod = prevMethodStatus; + this.scope = prevScope; + return updated; + }; + TypeFlow.prototype.typeCheck = function (ast) { + if(ast) { + return ast.typeCheck(this); + } else { + return null; + } + }; + TypeFlow.prototype.inScopeTypeCheckDecl = function (ast) { + if(ast.nodeType == TypeScript.NodeType.VarDecl || ast.nodeType == TypeScript.NodeType.ArgDecl) { + this.inScopeTypeCheckBoundDecl(ast); + } else if(ast.nodeType == TypeScript.NodeType.FuncDecl) { + var funcDecl = ast; + if(funcDecl.isAccessor()) { + this.typeCheckFunction(funcDecl); + } + } + }; + TypeFlow.prototype.inScopeTypeCheckBoundDecl = function (varDecl) { + var sym = varDecl.sym; + var svThisFnc = this.thisFnc; + var svThisType = this.thisType; + var prevMethodStatus = this.enclosingFncIsMethod; + var prevLocationInfo = this.checker.locationInfo; + if(sym && sym.container) { + var instanceScope = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.ClassConstructorProperty) ? sym.container.getType().constructorScope : sym.container.instanceScope(); + if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Property) && sym.container.declAST.nodeType == TypeScript.NodeType.FuncDecl) { + this.thisFnc = sym.container.declAST; + } + if(instanceScope) { + var prevScope = this.scope; + this.scope = instanceScope; + var container = sym.container; + var svCurrentModDecl = this.checker.currentModDecl; + if(this.checker.units && (sym.unitIndex >= 0) && (sym.unitIndex < this.checker.units.length)) { + this.checker.locationInfo = this.checker.units[sym.unitIndex]; + } else { + this.checker.locationInfo = TypeScript.unknownLocationInfo; + } + while(container) { + if(container.kind() == TypeScript.SymbolKind.Type) { + var typeSym = container; + var type = typeSym.type; + if(type.call) { + this.enclosingFncIsMethod = typeSym.isMethod; + } + if(type.isClass()) { + this.thisType = type.instanceType; + } + if(type.isModuleType()) { + this.checker.currentModDecl = container.declAST; + break; + } + } + container = container.container; + } + this.typeCheckBoundDecl(varDecl); + this.checker.currentModDecl = svCurrentModDecl; + this.scope = prevScope; + } + } + this.thisFnc = svThisFnc; + this.thisType = svThisType; + this.checker.locationInfo = prevLocationInfo; + this.enclosingFncIsMethod = prevMethodStatus; + }; + TypeFlow.prototype.resolveBoundDecl = function (varDecl) { + if(varDecl.typeExpr) { + if(varDecl.typeExpr.type == null || (varDecl.typeExpr.type && varDecl.typeExpr.type == this.anyType && this.scope) || varDecl.typeExpr.type.symbol == null || !this.checker.typeStatusIsFinished(varDecl.typeExpr.type.symbol.typeCheckStatus)) { + this.typeCheck(varDecl.typeExpr); + } + varDecl.type = varDecl.typeExpr.type; + if(varDecl.sym) { + varDecl.sym.setType(varDecl.type); + } + } else if(varDecl.init == null) { + if(this.checker.styleSettings.implicitAny) { + this.checker.errorReporter.styleError(varDecl, "type implicitly set to 'any'"); + } + varDecl.type = this.anyType; + if(varDecl.sym) { + if(varDecl.sym.isType()) { + var tsym = varDecl.sym; + if(tsym.isMethod) { + this.checker.errorReporter.simpleError(varDecl, "Cannot bind method group to variable. (Did you mean to use 'declare function' instead of 'declare var'?)"); + return; + } else { + this.checker.errorReporter.simpleError(varDecl, "Cannot bind type to variable"); + return; + } + } + varDecl.sym.setType(varDecl.type); + } + } + }; + TypeFlow.prototype.typeCheckBoundDecl = function (varDecl) { + var _this = this; + var infSym = varDecl.sym; + if(infSym == null) { + if(varDecl.init) { + varDecl.init = this.typeCheck(varDecl.init); + varDecl.type = this.checker.widenType(varDecl.init.type); + } else { + if(this.checker.styleSettings.implicitAny) { + this.checker.errorReporter.styleError(varDecl, "type implicitly set to 'any'"); + } + varDecl.type = this.anyType; + } + } else { + if(infSym.typeCheckStatus == TypeScript.TypeCheckStatus.Started) { + if(this.checker.styleSettings.implicitAny) { + this.checker.errorReporter.styleError(varDecl, "type implicitly set to 'any'"); + } + varDecl.type = this.anyType; + infSym.setType(this.anyType); + } else if(infSym.typeCheckStatus == TypeScript.TypeCheckStatus.NotStarted) { + infSym.typeCheckStatus = TypeScript.TypeCheckStatus.Started; + this.checker.addStartedPTO(infSym); + var resolved = false; + if(varDecl.type == null) { + if(varDecl.typeExpr) { + this.resolveBoundDecl(varDecl); + resolved = true; + varDecl.type = varDecl.typeExpr.type; + infSym.typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); + } + } + if(varDecl.init) { + var isLocalStatic = TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.LocalStatic); + var prevScope = this.scope; + var applyTargetType = !varDecl.init.isParenthesized; + if(isLocalStatic) { + this.scope = varDecl.sym.container.getType().memberScope; + } + if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Property) && this.thisClassNode) { + TypeScript.getAstWalkerFactory().walk(varDecl.init, function (ast, parent, walker) { + if(ast && ast.nodeType == TypeScript.NodeType.FuncDecl) { + if(TypeScript.hasFlag((ast).fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { + (ast).fncFlags |= TypeScript.FncFlags.IsPropertyBound; + } + walker.options.goChildren = false; + } + return ast; + }); + } + this.checker.typeCheckWithContextualType(varDecl.type, this.checker.inProvisionalTypecheckMode(), applyTargetType, varDecl.init); + this.scope = prevScope; + if(varDecl.type) { + var preserveScope = false; + var preservedContainedScope = null; + if(varDecl.init.type) { + preservedContainedScope = varDecl.init.type.containedScope; + preserveScope = true; + if(varDecl.init.type == this.voidType) { + this.checker.errorReporter.simpleError(varDecl, "Cannot assign type 'void' to variable '" + varDecl.id.actualText + "'"); + } + } + varDecl.init = this.castWithCoercion(varDecl.init, varDecl.type, applyTargetType && !this.checker.inProvisionalTypecheckMode(), false); + if(preserveScope && varDecl.init.type.containedScope == null) { + varDecl.init.type.containedScope = preservedContainedScope; + } + } else { + varDecl.type = this.checker.widenType(varDecl.init.type); + if(varDecl.type == this.voidType) { + this.checker.errorReporter.simpleError(varDecl, "Cannot assign type 'void' to variable '" + varDecl.id.actualText + "'"); + varDecl.type = this.anyType; + } + } + infSym.setType(varDecl.type); + } else { + if(!resolved) { + this.resolveBoundDecl(varDecl); + } + } + infSym.typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); + } else if(this.checker.typeStatusIsFinished(infSym.typeCheckStatus) && (infSym.declAST != varDecl)) { + if(varDecl.init) { + varDecl.init = this.typeCheck(varDecl.init); + varDecl.type = infSym.getType(); + varDecl.init = this.cast(varDecl.init, varDecl.type); + } + } + } + if(varDecl.id && varDecl.sym) { + varDecl.id.sym = varDecl.sym; + } + if(varDecl.sym && varDecl.sym.container) { + this.checkTypePrivacy(varDecl.sym.getType(), varDecl.sym, function (typeName, isModuleName) { + return _this.varPrivacyErrorReporter(varDecl, typeName, isModuleName); + }); + } + return varDecl; + }; + TypeFlow.prototype.varPrivacyErrorReporter = function (varDecl, typeName, isModuleName) { + var typestring = ""; + if(isModuleName) { + var quotestring = ""; + if(!TypeScript.isQuoted(typeName)) { + quotestring = "'"; + } + typestring = " is using inaccessible module " + quotestring + typeName + quotestring; + } else { + typestring = " has or is using private type '" + typeName + "'"; + } + if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Public)) { + if(varDecl.sym.container.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) { + this.checker.errorReporter.simpleError(varDecl, "property '" + varDecl.sym.name + "' of exported interface" + typestring); + } else { + this.checker.errorReporter.simpleError(varDecl, "public member '" + varDecl.sym.name + "' of exported class" + typestring); + } + } else { + this.checker.errorReporter.simpleError(varDecl, "exported variable '" + varDecl.sym.name + "'" + typestring); + } + }; + TypeFlow.prototype.typeCheckSuper = function (ast) { + if(this.thisType && (this.enclosingFncIsMethod && !this.thisFnc.isStatic()) && this.thisType.baseClass()) { + ast.type = this.thisType.baseClass(); + } else { + if(!this.enclosingFncIsMethod && this.thisType && this.thisType.baseClass() && this.thisFnc && TypeScript.hasFlag(this.thisFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { + var enclosingFnc = this.thisFnc.enclosingFnc; + while(TypeScript.hasFlag(enclosingFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { + enclosingFnc = enclosingFnc.enclosingFnc; + } + if(enclosingFnc && (enclosingFnc.isMethod() || enclosingFnc.isConstructor) && !enclosingFnc.isStatic()) { + ast.type = this.thisType.baseClass(); + enclosingFnc.setHasSuperReferenceInFatArrowFunction(); + return ast; + } + } + ast.type = this.anyType; + this.checker.errorReporter.invalidSuperReference(ast); + } + return ast; + }; + TypeFlow.prototype.typeCheckThis = function (ast) { + ast.type = this.anyType; + var illegalThisRef = false; + if(this.thisFnc == null) { + if(this.thisType) { + if(this.thisClassNode && this.thisClassNode.nodeType == TypeScript.NodeType.ClassDeclaration) { + illegalThisRef = true; + } else { + ast.type = this.thisType; + } + } else if(this.checker.currentModDecl) { + this.checker.errorReporter.simpleError(ast, "'this' may not be referenced within module bodies"); + } + } else { + if(this.thisClassNode && (TypeScript.hasFlag(this.thisFnc.fncFlags, TypeScript.FncFlags.IsPropertyBound) || (this.inSuperCall && TypeScript.hasFlag((this.thisClassNode).varFlags, TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor)))) { + illegalThisRef = true; + } + if(this.thisFnc.isMethod() || this.thisFnc.isConstructor) { + if(this.thisType && !(this.thisFnc.fncFlags & TypeScript.FncFlags.Static)) { + ast.type = this.thisType; + } + } + } + if(!this.enclosingFncIsMethod && this.thisFnc && TypeScript.hasFlag(this.thisFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { + if(this.thisFnc.boundToProperty) { + var container = this.thisFnc.boundToProperty.sym.container; + if(container.declAST.nodeType == TypeScript.NodeType.FuncDecl) { + (container.declAST).setHasSelfReference(); + } + } else { + var encFnc = this.thisFnc.enclosingFnc; + var firstEncFnc = encFnc; + while(encFnc) { + if(this.thisClassNode && TypeScript.hasFlag(encFnc.fncFlags, TypeScript.FncFlags.IsPropertyBound)) { + illegalThisRef = true; + } + if(!TypeScript.hasFlag(encFnc.fncFlags, TypeScript.FncFlags.IsFatArrowFunction) || encFnc.hasSelfReference()) { + encFnc.setHasSelfReference(); + break; + } + encFnc = encFnc.enclosingFnc; + } + if(!encFnc && firstEncFnc) { + encFnc = firstEncFnc; + encFnc.setHasSelfReference(); + } else if(!encFnc) { + if(this.thisClassNode) { + (this.thisClassNode).varFlags |= TypeScript.VarFlags.MustCaptureThis; + } else if(this.checker.currentModDecl) { + this.checker.currentModDecl.modFlags |= TypeScript.ModuleFlags.MustCaptureThis; + } else { + this.checker.mustCaptureGlobalThis = true; + } + } + if(encFnc && (encFnc.isMethod() || encFnc.isConstructor) && this.thisType && !TypeScript.hasFlag(encFnc.fncFlags, TypeScript.FncFlags.Static)) { + ast.type = this.thisType; + } + } + } + if(illegalThisRef) { + this.checker.errorReporter.simpleError(ast, "Keyword 'this' cannot be referenced in initializers in a class body, or in super constructor calls"); + } + return ast; + }; + TypeFlow.prototype.setTypeFromSymbol = function (ast, symbol) { + if(symbol.isVariable()) { + if(symbol.isInferenceSymbol()) { + var infSym = symbol; + if(infSym.declAST && !this.checker.typeStatusIsFinished(infSym.typeCheckStatus)) { + if(infSym.typeCheckStatus == TypeScript.TypeCheckStatus.Started) { + infSym.declAST.type = this.anyType; + infSym.setType(this.anyType); + } else { + this.inScopeTypeCheckDecl(infSym.declAST); + } + } + if(!this.checker.styleSettings.innerScopeDeclEscape) { + if(infSym.declAST && (infSym.declAST.nodeType == TypeScript.NodeType.VarDecl)) { + if(this.nestingLevel < (infSym.declAST).nestingLevel) { + this.checker.errorReporter.styleError(ast, "Illegal reference to a variable defined in more nested scope"); + } + } + } + } + ast.type = symbol.getType(); + if(!symbol.writeable()) { + ast.flags = ast.flags & (~(TypeScript.ASTFlags.Writeable)); + } + } else if(symbol.isType()) { + ast.type = symbol.getType(); + ast.flags = ast.flags & (~(TypeScript.ASTFlags.Writeable)); + } else { + ast.type = this.anyType; + this.checker.errorReporter.symbolDoesNotReferToAValue(ast, symbol.name); + } + }; + TypeFlow.prototype.typeCheckName = function (ast) { + var _this = this; + var identifier = ast; + if(this.checker.inWith) { + identifier.type = this.anyType; + } else { + var typespace = this.inTypeRefTypeCheck; + var idText = identifier.text; + var originalIdText = idText; + var isDynamicModuleName = TypeScript.isQuoted(identifier.text); + var symbol = this.scope.find(idText, false, typespace); + if(symbol == null && isDynamicModuleName) { + symbol = this.checker.findSymbolForDynamicModule(idText, this.currentScript.locationInfo.filename, function (id) { + return _this.scope.find(id, false, typespace); + }); + } + if(!symbol) { + if(!identifier.isMissing()) { + this.checker.errorReporter.unresolvedSymbol(identifier, identifier.text); + } + identifier.type = this.anyType; + } else { + if(TypeScript.optimizeModuleCodeGen && symbol && symbol.isType()) { + var symType = symbol.getType(); + if(symType && (symbol).aliasLink && (symbol).onlyReferencedAsTypeRef) { + var modDecl = symType.symbol.declAST; + if(modDecl && TypeScript.hasFlag(modDecl.modFlags, TypeScript.ModuleFlags.IsDynamic)) { + (symbol).onlyReferencedAsTypeRef = this.inTypeRefTypeCheck; + } + } + } + if(symbol.declAST && symbol.declAST.nodeType == TypeScript.NodeType.FuncDecl && !(symbol.declAST).returnTypeAnnotation && (symbol.declAST).signature.typeCheckStatus == TypeScript.TypeCheckStatus.Started) { + (symbol.declAST).type.symbol.flags |= TypeScript.SymbolFlags.RecursivelyReferenced; + (symbol.declAST).signature.returnType.type = this.anyType; + } + this.setTypeFromSymbol(ast, symbol); + identifier.sym = symbol; + if(this.thisFnc) { + if(this.thisFnc.type && symbol.container != this.thisFnc.type.symbol) { + this.thisFnc.freeVariables[this.thisFnc.freeVariables.length] = symbol; + } + } + } + } + return ast; + }; + TypeFlow.prototype.typeCheckScript = function (script) { + this.checker.locationInfo = script.locationInfo; + this.scope = this.checker.globalScope; + if(!script.topLevelMod) { + this.addLocalsFromScope(this.scope, this.checker.gloMod, script.vars, this.checker.globals, true); + } + this.currentScript = script; + script.bod = this.typeCheck(script.bod); + this.currentScript = null; + return script; + }; + TypeFlow.prototype.typeCheckBitNot = function (ast) { + var unex = ast; + unex.operand = this.typeCheck(unex.operand); + unex.type = this.doubleType; + return unex; + }; + TypeFlow.prototype.typeCheckUnaryNumberOperator = function (ast) { + var unex = ast; + unex.operand = this.typeCheck(unex.operand); + unex.type = this.doubleType; + return ast; + }; + TypeFlow.prototype.typeCheckLogNot = function (ast) { + var unex = ast; + unex.operand = this.typeCheck(unex.operand); + unex.type = this.booleanType; + return unex; + }; + TypeFlow.prototype.astIsWriteable = function (ast) { + return TypeScript.hasFlag(ast.flags, TypeScript.ASTFlags.Writeable); + }; + TypeFlow.prototype.typeCheckIncOrDec = function (ast) { + var unex = ast; + var lval = unex.operand; + if(!this.astIsWriteable(unex)) { + this.checker.errorReporter.valueCannotBeModified(unex); + unex.type = this.doubleType; + } else { + unex = this.typeCheckUnaryNumberOperator(ast); + if(unex.operand.type != this.checker.numberType && unex.operand.type != this.checker.anyType && !(unex.operand.type.typeFlags & TypeScript.TypeFlags.IsEnum)) { + this.checker.errorReporter.simpleError(ast, "'++' and '--' may only be applied to operands of type 'number' or 'any'"); + } + } + return unex; + }; + TypeFlow.prototype.typeCheckBitwiseOperator = function (ast, assignment) { + var binex = ast; + var resultType = null; + binex.operand1 = this.typeCheck(binex.operand1); + binex.operand2 = this.typeCheck(binex.operand2); + var leftType = binex.operand1.type; + var rightType = binex.operand2.type; + if(assignment && (!this.astIsWriteable(binex))) { + this.checker.errorReporter.valueCannotBeModified(binex); + } + if(this.checker.styleSettings.bitwise) { + this.checker.errorReporter.styleError(ast, "use of " + TypeScript.nodeTypeTable[binex.nodeType]); + } + if(this.checker.sourceIsSubtypeOfTarget(leftType, this.doubleType) && (this.checker.sourceIsSubtypeOfTarget(rightType, this.doubleType))) { + resultType = this.doubleType; + } else if((leftType == this.booleanType) && (rightType == this.booleanType)) { + resultType = this.booleanType; + } else if(leftType == this.anyType) { + if((rightType == this.anyType) || (rightType == this.doubleType) || (rightType == this.booleanType)) { + resultType = this.anyType; + } + } else if(rightType == this.anyType) { + if((leftType == this.anyType) || (leftType == this.doubleType) || (leftType == this.booleanType)) { + resultType = this.anyType; + } + } + if(resultType == null) { + resultType = this.anyType; + this.checker.errorReporter.incompatibleTypes(binex, leftType, rightType, binex.printLabel(), this.scope); + } + binex.type = resultType; + return binex; + }; + TypeFlow.prototype.typeCheckArithmeticOperator = function (ast, assignment) { + var binex = ast; + binex.operand1 = this.typeCheck(binex.operand1); + binex.operand2 = this.typeCheck(binex.operand2); + var leftType = binex.operand1.type; + var rightType = binex.operand2.type; + if(assignment && (!this.astIsWriteable(binex.operand1))) { + this.checker.errorReporter.valueCannotBeModified(binex); + } + if(this.checker.styleSettings.bitwise && ((binex.nodeType == TypeScript.NodeType.And) || (binex.nodeType == TypeScript.NodeType.Or) || (binex.nodeType == TypeScript.NodeType.AsgAnd) || (binex.nodeType == TypeScript.NodeType.AsgOr))) { + this.checker.errorReporter.styleError(ast, "use of " + TypeScript.nodeTypeTable[binex.nodeType]); + } + var nodeType = binex.nodeType; + if(this.checker.isNullOrUndefinedType(leftType)) { + leftType = rightType; + } + if(this.checker.isNullOrUndefinedType(rightType)) { + rightType = leftType; + } + leftType = this.checker.widenType(leftType); + rightType = this.checker.widenType(rightType); + if(nodeType == TypeScript.NodeType.Add || nodeType == TypeScript.NodeType.AsgAdd) { + if(leftType == this.checker.stringType || rightType == this.checker.stringType) { + binex.type = this.checker.stringType; + } else if(leftType == this.checker.numberType && rightType == this.checker.numberType) { + binex.type = this.checker.numberType; + } else if(this.checker.sourceIsSubtypeOfTarget(leftType, this.checker.numberType) && this.checker.sourceIsSubtypeOfTarget(rightType, this.checker.numberType)) { + binex.type = this.checker.numberType; + } else if(leftType == this.checker.anyType || rightType == this.checker.anyType) { + binex.type = this.checker.anyType; + } else { + binex.type = this.anyType; + this.checker.errorReporter.incompatibleTypes(binex, leftType, rightType, binex.printLabel(), this.scope); + } + } else { + if(leftType == this.checker.numberType && rightType == this.checker.numberType) { + binex.type = this.checker.numberType; + } else if(this.checker.sourceIsSubtypeOfTarget(leftType, this.checker.numberType) && this.checker.sourceIsSubtypeOfTarget(rightType, this.checker.numberType)) { + binex.type = this.checker.numberType; + } else if(leftType == this.checker.anyType || rightType == this.checker.anyType) { + binex.type = this.checker.numberType; + } else { + binex.type = this.anyType; + this.checker.errorReporter.incompatibleTypes(binex, leftType, rightType, binex.printLabel(), this.scope); + } + } + return binex; + }; + TypeFlow.prototype.typeCheckDotOperator = function (ast) { + var binex = ast; + var leftIsFnc = false; + binex.operand1 = this.typeCheck(binex.operand1); + var leftType = binex.operand1.type; + var leftScope = null; + if(leftType) { + if(leftType == this.anyType) { + binex.type = this.anyType; + return binex; + } else if(leftType == this.stringType) { + if(this.stringInterfaceType) { + leftScope = this.stringInterfaceType.memberScope; + } else { + binex.type = this.anyType; + return binex; + } + } else if(leftType == this.doubleType) { + if(this.numberInterfaceType) { + leftScope = this.numberInterfaceType.memberScope; + } else { + binex.type = this.anyType; + return binex; + } + } else if(leftType == this.booleanType) { + if(this.booleanInterfaceType) { + leftScope = this.booleanInterfaceType.memberScope; + } else { + binex.type = this.anyType; + return binex; + } + } else if((leftType.call || leftType.construct) && leftType.members == null) { + if(this.functionInterfaceType) { + leftScope = this.functionInterfaceType.memberScope; + } else { + binex.type = this.anyType; + return binex; + } + } else if(leftType.elementType) { + if(this.arrayInterfaceType) { + var arrInstType = leftType.elementType.getArrayBase(this.arrayInterfaceType, this.checker); + leftScope = arrInstType.memberScope; + } else { + binex.type = this.anyType; + return binex; + } + } else { + leftScope = leftType.memberScope; + } + } + if(leftScope == null) { + this.checker.errorReporter.expectedClassOrInterface(binex); + binex.type = this.anyType; + } else { + var propertyName = binex.operand2; + var lhsIsEnclosingType = (this.thisClassNode && binex.operand1.type == this.thisClassNode.type.instanceType) || this.inTypeRefTypeCheck; + var symbol = leftScope.find(propertyName.text, !lhsIsEnclosingType, this.inTypeRefTypeCheck); + if(!symbol) { + if(this.objectInterfaceType && leftType) { + if(leftType.isReferenceType()) { + symbol = this.objectInterfaceType.memberScope.find(propertyName.text, false, this.inTypeRefTypeCheck); + } + if(!symbol) { + if(this.functionInterfaceType && (leftType.call || leftType.construct)) { + symbol = this.functionInterfaceType.memberScope.find(propertyName.text, false, this.inTypeRefTypeCheck); + } + } + } + } + if(!symbol || (!symbol.visible(leftScope, this.checker))) { + binex.type = this.anyType; + if(symbol == null) { + this.checker.errorReporter.simpleError(propertyName, "The property '" + propertyName.actualText + "' does not exist on value of type '" + leftType.getScopedTypeName(this.scope) + "'"); + } else if(!this.inTypeRefTypeCheck) { + this.checker.errorReporter.simpleError(binex, "The property '" + propertyName.actualText + " on type '" + leftType.getScopedTypeName(this.scope) + "' is not visible"); + } + } else { + if(symbol.isVariable()) { + if(symbol.isInferenceSymbol()) { + var infSym = symbol; + if(infSym.declAST && !this.checker.typeStatusIsFinished(infSym.typeCheckStatus)) { + this.inScopeTypeCheckDecl(infSym.declAST); + } + } + } + propertyName.sym = symbol; + binex.type = symbol.getType(); + } + } + if(binex.type == null) { + binex.type = this.anyType; + } + return binex; + }; + TypeFlow.prototype.typeCheckBooleanOperator = function (ast) { + var binex = ast; + binex.operand1 = this.typeCheck(binex.operand1); + binex.operand2 = this.typeCheck(binex.operand2); + var leftType = binex.operand1.type; + var rightType = binex.operand2.type; + if((!(this.checker.sourceIsAssignableToTarget(leftType, rightType))) && (!(this.checker.sourceIsAssignableToTarget(rightType, leftType)))) { + this.checker.errorReporter.incompatibleTypes(binex, leftType, rightType, binex.printLabel(), this.scope); + } + binex.type = this.booleanType; + return binex; + }; + TypeFlow.prototype.typeCheckAsgOperator = function (ast) { + var binex = ast; + var applyTargetType = !binex.operand2.isParenthesized; + binex.operand1 = this.typeCheck(binex.operand1); + this.checker.typeCheckWithContextualType(binex.operand1.type, this.checker.inProvisionalTypecheckMode(), applyTargetType, binex.operand2); + var leftType = binex.operand1.type; + var rightType = binex.operand2.type; + if(!(this.astIsWriteable(binex.operand1))) { + this.checker.errorReporter.valueCannotBeModified(binex); + } + if(binex.operand1.nodeType == TypeScript.NodeType.Call) { + var callEx = binex.operand1; + } + var preserveScope = false; + var preservedContainedScope = null; + if(binex.operand2.type) { + preservedContainedScope = binex.operand2.type.containedScope; + preserveScope = true; + } + binex.operand2 = this.castWithCoercion(binex.operand2, leftType, applyTargetType && !this.checker.inProvisionalTypecheckMode(), false); + if(preserveScope && binex.operand2.type.containedScope == null) { + binex.operand2.type.containedScope = preservedContainedScope; + } + binex.type = rightType; + return binex; + }; + TypeFlow.prototype.typeCheckIndex = function (ast) { + var binex = ast; + binex.operand1 = this.typeCheck(binex.operand1); + binex.operand2 = this.typeCheck(binex.operand2); + if(!this.checker.styleSettings.literalSubscript) { + if(binex.operand2.nodeType == TypeScript.NodeType.QString) { + this.checker.errorReporter.styleError(ast, "use literal subscript ('.') notation instead)"); + } + } + var objExprType = binex.operand1.type; + var indexExprType = binex.operand2.type; + if(objExprType.elementType) { + if(indexExprType == this.checker.anyType || indexExprType == this.checker.numberType || TypeScript.hasFlag(indexExprType.typeFlags, TypeScript.TypeFlags.IsEnum)) { + binex.type = objExprType.elementType; + } else if(indexExprType == this.checker.stringType) { + binex.type = this.checker.anyType; + } else { + this.checker.errorReporter.simpleError(binex, "Illegal property access"); + binex.type = this.checker.anyType; + } + } else if(objExprType.index) { + if(indexExprType == this.checker.anyType || !((objExprType.index.flags & TypeScript.SignatureFlags.IsStringIndexer) || (objExprType.index.flags & TypeScript.SignatureFlags.IsNumberIndexer)) || ((objExprType.index.flags & TypeScript.SignatureFlags.IsStringIndexer) && indexExprType == this.checker.stringType) || ((objExprType.index.flags & TypeScript.SignatureFlags.IsNumberIndexer) && (indexExprType == this.checker.numberType || TypeScript.hasFlag(indexExprType.typeFlags, TypeScript.TypeFlags.IsEnum)))) { + var sig = this.resolveOverload(ast, objExprType.index); + if(sig) { + binex.type = sig.returnType.type; + } else { + binex.type = this.checker.anyType; + } + } else if(indexExprType == this.checker.stringType) { + binex.type = this.checker.anyType; + } else { + this.checker.errorReporter.simpleError(binex, "Illegal property access"); + binex.type = this.checker.anyType; + } + } else if((objExprType == this.checker.anyType || objExprType == this.checker.stringType || objExprType == this.checker.numberType || objExprType == this.checker.booleanType || objExprType.isReferenceType()) && (indexExprType == this.checker.anyType || indexExprType == this.checker.stringType || (indexExprType == this.checker.numberType || TypeScript.hasFlag(indexExprType.typeFlags, TypeScript.TypeFlags.IsEnum)))) { + binex.type = this.checker.anyType; + } else { + this.checker.errorReporter.simpleError(binex, "Illegal property access"); + binex.type = this.checker.anyType; + } + return binex; + }; + TypeFlow.prototype.typeCheckInOperator = function (binex) { + binex.operand1 = this.cast(this.typeCheck(binex.operand1), this.stringType); + binex.operand2 = this.typeCheck(binex.operand2); + if(!((binex.operand1.type == this.checker.anyType || binex.operand1.type == this.checker.stringType) && (binex.operand2.type == this.anyType || this.checker.sourceIsSubtypeOfTarget(binex.operand2.type, this.objectInterfaceType)))) { + this.checker.errorReporter.simpleError(binex, "The in operator requires the left operand to be of type Any or the String primitive type, and the right operand to be of type Any or an object type"); + } + binex.type = this.booleanType; + return binex; + }; + TypeFlow.prototype.typeCheckShift = function (binex, assignment) { + binex.operand1 = this.cast(this.typeCheck(binex.operand1), this.doubleType); + binex.operand2 = this.cast(this.typeCheck(binex.operand2), this.doubleType); + if(assignment && (!(this.astIsWriteable(binex.operand1)))) { + this.checker.errorReporter.valueCannotBeModified(binex); + } + binex.type = this.doubleType; + return binex; + }; + TypeFlow.prototype.typeCheckQMark = function (trinex) { + trinex.operand1 = this.typeCheck(trinex.operand1); + trinex.operand2 = this.typeCheck(trinex.operand2); + trinex.operand3 = this.typeCheck(trinex.operand3); + var leftType = trinex.operand2.type; + var rightType = trinex.operand3.type; + if(leftType == rightType) { + trinex.type = leftType; + } else { + if(this.checker.sourceIsSubtypeOfTarget(leftType, rightType)) { + trinex.type = rightType; + } else if(this.checker.sourceIsSubtypeOfTarget(rightType, leftType)) { + trinex.type = leftType; + } else { + trinex.type = this.anyType; + this.checker.errorReporter.incompatibleTypes(trinex, leftType, rightType, trinex.printLabel(), this.scope); + } + } + return trinex; + }; + TypeFlow.prototype.addFormals = function (container, signature, table) { + var len = signature.parameters.length; + for(var i = 0; i < len; i++) { + var symbol = signature.parameters[i]; + symbol.container = container; + table.add(symbol.name, symbol); + } + }; + TypeFlow.prototype.addLocalsFromScope = function (scope, container, vars, table, isModContainer) { + var len = vars.members.length; + var hasArgsDef = false; + for(var i = 0; i < len; i++) { + var local = vars.members[i]; + if(((local.sym == null) || (local.sym.kind() != TypeScript.SymbolKind.Field))) { + var result = null; + if((result = table.lookup(local.id.text)) == null) { + var localVar = new TypeScript.ValueLocation(); + localVar.typeLink = new TypeScript.TypeLink(); + var varSym = null; + if(TypeScript.hasFlag(local.varFlags, TypeScript.VarFlags.Static)) { + local.varFlags |= TypeScript.VarFlags.LocalStatic; + varSym = new TypeScript.FieldSymbol(local.id.text, local.minChar, this.checker.locationInfo.unitIndex, true, localVar); + } else { + varSym = new TypeScript.VariableSymbol(local.id.text, local.minChar, this.checker.locationInfo.unitIndex, localVar); + } + varSym.transferVarFlags(local.varFlags); + localVar.symbol = varSym; + varSym.declAST = local; + localVar.typeLink.ast = local.typeExpr; + this.checker.resolveTypeLink(scope, localVar.typeLink, false); + if((local.type == null) && (local.init == null)) { + local.type = this.anyType; + } + localVar.typeLink.type = local.type; + localVar.symbol.container = container; + local.sym = localVar.symbol; + table.add(local.id.text, varSym); + if(local.id.text == "arguments") { + hasArgsDef = true; + } + } else { + local.type = result.getType(); + local.sym = result; + } + } + } + if(!isModContainer) { + if(!hasArgsDef) { + var argLoc = new TypeScript.ValueLocation(); + argLoc.typeLink = new TypeScript.TypeLink(); + var theArgSym = new TypeScript.VariableSymbol("arguments", vars.minChar, this.checker.locationInfo.unitIndex, argLoc); + if(!this.iargumentsInterfaceType) { + var argumentsSym = scope.find("IArguments", false, true); + if(argumentsSym) { + argumentsSym.flags |= TypeScript.SymbolFlags.CompilerGenerated; + this.iargumentsInterfaceType = argumentsSym.getType(); + } else { + this.iargumentsInterfaceType = this.anyType; + } + } + argLoc.typeLink.type = this.iargumentsInterfaceType; + table.add("arguments", theArgSym); + } + } + }; + TypeFlow.prototype.addConstructorLocalArgs = function (constructorDecl, table, isClass) { + var container = constructorDecl.type.symbol; + var args = constructorDecl.arguments; + if(args) { + var len = args.members.length; + for(var i = 0; i < len; i++) { + var local = args.members[i]; + if((local.sym == null) || (isClass || (local.sym.kind() != TypeScript.SymbolKind.Field))) { + var result = null; + if((result = table.lookup(local.id.text)) == null) { + this.resolveBoundDecl(local); + var localVar = new TypeScript.ValueLocation(); + localVar.typeLink = new TypeScript.TypeLink(); + var varSym = new TypeScript.ParameterSymbol(local.id.text, local.minChar, this.checker.locationInfo.unitIndex, localVar); + varSym.funcDecl = constructorDecl; + varSym.declAST = local; + localVar.symbol = varSym; + localVar.typeLink.type = local.type; + localVar.symbol.container = container; + local.sym = localVar.symbol; + table.add(local.id.text, varSym); + } else { + local.type = result.getType(); + local.sym = result; + } + } + } + } + }; + TypeFlow.prototype.checkInitSelf = function (funcDecl) { + if(!funcDecl.isMethod()) { + var freeVars = funcDecl.freeVariables; + for(var k = 0, len = freeVars.length; k < len; k++) { + var sym = freeVars[k]; + if(sym.isInstanceProperty()) { + return true; + } + } + } + var fns = funcDecl.scopes; + var fnsLen = fns.members.length; + for(var j = 0; j < fnsLen; j++) { + var fn = fns.members[j]; + if(this.checkInitSelf(fn)) { + return true; + } + } + return false; + }; + TypeFlow.prototype.checkPromoteFreeVars = function (funcDecl, constructorSym) { + var freeVars = funcDecl.freeVariables; + for(var k = 0, len = freeVars.length; k < len; k++) { + var sym = freeVars[k]; + if((!sym.isInstanceProperty()) && (sym.container == constructorSym)) { + TypeScript.instanceFilter.reset(); + if(this.scope.search(TypeScript.instanceFilter, sym.name, false, false)) { + this.checker.errorReporter.simpleError(funcDecl, "Constructor-local variable shadows class property '" + sym.name + "'. To access the class property, use 'self." + sym.name + "'"); + } + this.checker.errorReporter.simpleError(funcDecl, "Constructor-local variables may not be accessed from instance method bodies. Consider changing local variable '" + sym.name + "' to a class property"); + } + } + }; + TypeFlow.prototype.allReturnsAreVoid = function (funcDecl) { + var allReturnsAreVoid = true; + if(funcDecl.signature.returnType.type == null) { + var preFindReturnExpressionTypes = function (ast, parent, walker) { + var go = true; + switch(ast.nodeType) { + case TypeScript.NodeType.FuncDecl: + go = false; + break; + case TypeScript.NodeType.Return: + var returnStmt = ast; + if(returnStmt.returnExpression) { + allReturnsAreVoid = false; + go = false; + } + default: + break; + } + walker.options.goChildren = go; + walker.options.goNextSibling = go; + return ast; + }; + TypeScript.getAstWalkerFactory().walk(funcDecl.bod, preFindReturnExpressionTypes); + } + return allReturnsAreVoid; + }; + TypeFlow.prototype.classConstructorHasSuperCall = function (funcDecl) { + var foundSuper = false; + var preFindSuperCall = function (ast, parent, walker) { + var go = true; + switch(ast.nodeType) { + case TypeScript.NodeType.FuncDecl: + go = false; + break; + case TypeScript.NodeType.Call: + var call = ast; + if(call.target.nodeType == TypeScript.NodeType.Super) { + go = false; + foundSuper = true; + break; + } + break; + default: + break; + } + walker.options.goChildren = go; + return ast; + }; + TypeScript.getAstWalkerFactory().walk(funcDecl.bod, preFindSuperCall); + return foundSuper; + }; + TypeFlow.prototype.baseListPrivacyErrorReporter = function (bases, i, declSymbol, extendsList, typeName, isModuleName) { + var baseSymbol = bases.members[i].type.symbol; + var declTypeString = (declSymbol.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) ? "interface" : "class"; + var baseListTypeString = extendsList ? "extends" : "implements"; + var baseTypeString = (baseSymbol.declAST.nodeType == TypeScript.NodeType.InterfaceDeclaration) ? "interface" : "class"; + var typestring = ""; + if(isModuleName) { + var quotestring = ""; + if(!TypeScript.isQuoted(typeName)) { + quotestring = "'"; + } + typestring = " is using inaccessible module "; + baseTypeString = " " + baseTypeString + " from private module " + quotestring + typeName + quotestring; + } else { + baseTypeString = " private " + baseTypeString + " '" + typeName + "'"; + } + this.checker.errorReporter.simpleError(bases.members[i], "exported " + declTypeString + " '" + declSymbol.name + "' " + baseListTypeString + baseTypeString); + }; + TypeFlow.prototype.typeCheckBaseListPrivacy = function (bases, declSymbol, extendsList) { + var _this = this; + if(bases) { + var basesLen = bases.members.length; + for(var i = 0; i < basesLen; i++) { + if(!bases.members[i].type || bases.members[i].type == this.checker.anyType) { + continue; + } + this.checkSymbolPrivacy(bases.members[i].type.symbol, declSymbol, function (typeName, isModuleName) { + return _this.baseListPrivacyErrorReporter(bases, i, declSymbol, extendsList, typeName, isModuleName); + }); + } + } + }; + TypeFlow.prototype.checkSymbolPrivacy = function (typeSymbol, declSymbol, errorCallback) { + var externalModuleSymbol = null; + var declSymbolPath = null; + if(typeSymbol.isExternallyVisible(this.checker)) { + var typeSymbolPath = typeSymbol.pathToRoot(); + declSymbolPath = declSymbol.pathToRoot(); + var typeSymbolLength = typeSymbolPath.length; + var declSymbolPathLength = declSymbolPath.length; + if(typeSymbolLength > 0) { + if(typeSymbolPath[typeSymbolLength - 1].getType().isModuleType() && (typeSymbolPath[typeSymbolLength - 1]).isDynamic && typeSymbolPath[typeSymbolLength - 1] != declSymbolPath[declSymbolPathLength - 1]) { + externalModuleSymbol = typeSymbolPath[typeSymbolLength - 1]; + } else if(typeSymbolLength > 1) { + if(typeSymbolPath[typeSymbolLength - 2].getType().isModuleType() && (typeSymbolPath[typeSymbolLength - 2]).isDynamic && (declSymbolPathLength == 1 || typeSymbolPath[typeSymbolLength - 2] != declSymbolPath[declSymbolPathLength - 2])) { + externalModuleSymbol = typeSymbolPath[typeSymbolLength - 2]; + } + } + } + if(externalModuleSymbol == null) { + return; + } + } + var interfaceDecl = declSymbol.getInterfaceDeclFromSymbol(this.checker); + if(interfaceDecl && !TypeScript.hasFlag(interfaceDecl.varFlags, TypeScript.VarFlags.Exported)) { + return; + } + var checkVisibilitySymbol = declSymbol; + var varDecl = declSymbol.getVarDeclFromSymbol(); + if(varDecl) { + if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Private)) { + return; + } else if(TypeScript.hasFlag(varDecl.varFlags, TypeScript.VarFlags.Public)) { + checkVisibilitySymbol = declSymbol.container; + } + } + if(checkVisibilitySymbol.isExternallyVisible(this.checker)) { + var privateSymbolName = typeSymbol.name; + if(externalModuleSymbol != null) { + var prettyName = externalModuleSymbol.getPrettyNameOfDynamicModule(declSymbolPath); + if(prettyName != null) { + this.currentScript.AddExternallyVisibleImportedSymbol(prettyName.symbol, this.checker); + return; + } else { + privateSymbolName = externalModuleSymbol.prettyName; + } + } + errorCallback(privateSymbolName, typeSymbol.name != privateSymbolName); + } + }; + TypeFlow.prototype.checkTypePrivacy = function (type, declSymbol, errorCallback) { + var _this = this; + if(!(type && type.primitiveTypeClass == TypeScript.Primitive.None)) { + return; + } + if(type.isArray()) { + return this.checkTypePrivacy(type.elementType, declSymbol, errorCallback); + } + if(type.symbol && type.symbol.name && type.symbol.name != "_anonymous" && (((type.call == null) && (type.construct == null) && (type.index == null)) || (type.members && (!type.isClass())))) { + return this.checkSymbolPrivacy(type.symbol, declSymbol, errorCallback); + } + if(type.members) { + type.members.allMembers.map(function (key, s, unused) { + var sym = s; + if(!TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.BuiltIn)) { + _this.checkTypePrivacy(sym.getType(), declSymbol, errorCallback); + } + }, null); + } + this.checkSignatureGroupPrivacy(type.call, declSymbol, errorCallback); + this.checkSignatureGroupPrivacy(type.construct, declSymbol, errorCallback); + this.checkSignatureGroupPrivacy(type.index, declSymbol, errorCallback); + }; + TypeFlow.prototype.checkSignatureGroupPrivacy = function (sgroup, declSymbol, errorCallback) { + if(sgroup) { + var len = sgroup.signatures.length; + for(var i = 0; i < sgroup.signatures.length; i++) { + var signature = sgroup.signatures[i]; + if(len > 1 && signature == sgroup.definitionSignature) { + continue; + } + if(signature.returnType) { + this.checkTypePrivacy(signature.returnType.type, declSymbol, errorCallback); + } + var paramLen = signature.parameters.length; + for(var j = 0; j < paramLen; j++) { + var param = signature.parameters[j]; + this.checkTypePrivacy(param.getType(), declSymbol, errorCallback); + } + } + } + }; + TypeFlow.prototype.functionArgumentPrivacyErrorReporter = function (funcDecl, p, paramSymbol, typeName, isModuleName) { + var isGetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor); + var isSetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.SetAccessor); + var isPublicFunc = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Public); + var isContainerInterface = funcDecl.type.symbol.getInterfaceDeclFromSymbol(this.checker) != null; + var typestring = ""; + if(isModuleName) { + var quotestring = ""; + if(!TypeScript.isQuoted(typeName)) { + quotestring = "'"; + } + typestring = " is using inaccessible module " + quotestring + typeName + quotestring; + } else { + typestring = " has or is using private type '" + typeName + "'"; + } + if(!isContainerInterface) { + if(funcDecl.isConstructor) { + this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], "exported class's constructor parameter '" + paramSymbol.name + "'" + typestring); + } else if(isSetter) { + this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], (isPublicFunc ? "public" : "exported") + " setter parameter '" + paramSymbol.name + "'" + typestring); + } else if(!isGetter) { + this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], (isPublicFunc ? "public" : "exported") + " function parameter '" + paramSymbol.name + "'" + typestring); + } + } else { + if(funcDecl.isConstructMember()) { + this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], "exported interface's constructor parameter '" + paramSymbol.name + "'" + typestring); + } else if(funcDecl.isCallMember()) { + this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], "exported interface's call parameter '" + paramSymbol.name + "'" + typestring); + } else if(!funcDecl.isIndexerMember()) { + this.checker.errorReporter.simpleError(funcDecl.arguments.members[p], "exported interface's function parameter '" + paramSymbol.name + "'" + typestring); + } + } + }; + TypeFlow.prototype.returnTypePrivacyError = function (astError, funcDecl, typeName, isModuleName) { + var isGetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor); + var isSetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.SetAccessor); + var isPublicFunc = TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Public); + var isContainerInterface = funcDecl.type.symbol.getInterfaceDeclFromSymbol(this.checker) != null; + var typestring = ""; + if(isModuleName) { + var quotestring = ""; + if(!TypeScript.isQuoted(typeName)) { + quotestring = "'"; + } + typestring = " is using inaccessible module " + quotestring + typeName + quotestring; + } else { + typestring = " has or is using private type '" + typeName + "'"; + } + if(!isContainerInterface) { + if(isGetter) { + this.checker.errorReporter.simpleError(astError, (isPublicFunc ? "public" : "exported") + " getter return type" + typestring); + } else if(!isSetter) { + this.checker.errorReporter.simpleError(astError, (isPublicFunc ? "public" : "exported") + " function return type" + typestring); + } + } else { + if(funcDecl.isConstructMember()) { + this.checker.errorReporter.simpleError(astError, "exported interface's constructor return type" + typestring); + } else if(funcDecl.isCallMember()) { + this.checker.errorReporter.simpleError(astError, "exported interface's call return type" + typestring); + } else if(funcDecl.isIndexerMember()) { + this.checker.errorReporter.simpleError(astError, "exported interface's indexer return type" + typestring); + } else { + this.checker.errorReporter.simpleError(astError, "exported interface's function return type" + typestring); + } + } + }; + TypeFlow.prototype.functionReturnTypePrivacyErrorReporter = function (funcDecl, signature, typeName, isModuleName) { + var reportOnFuncDecl = false; + if(funcDecl.returnTypeAnnotation != null && funcDecl.returnTypeAnnotation.type == signature.returnType.type) { + this.returnTypePrivacyError(funcDecl.returnTypeAnnotation, funcDecl, typeName, isModuleName); + } + for(var i = 0; i < funcDecl.returnStatementsWithExpressions.length; i++) { + if(funcDecl.returnStatementsWithExpressions[i].type == signature.returnType.type) { + this.returnTypePrivacyError(funcDecl.returnStatementsWithExpressions[i], funcDecl, typeName, isModuleName); + } else { + reportOnFuncDecl = true; + } + } + if(reportOnFuncDecl) { + this.returnTypePrivacyError(funcDecl, funcDecl, typeName, isModuleName); + } + }; + TypeFlow.prototype.typeCheckFunction = function (funcDecl) { + var _this = this; + this.nestingLevel = 0; + var fnType = funcDecl.type; + var fgSym = fnType.symbol; + var signature = funcDecl.signature; + if(this.checker.typeStatusIsFinished(signature.typeCheckStatus)) { + return funcDecl; + } else if(signature.typeCheckStatus == TypeScript.TypeCheckStatus.Started) { + if(!funcDecl.returnTypeAnnotation && funcDecl.bod && !funcDecl.isSignature() && !(funcDecl.isConstructor) && this.allReturnsAreVoid(funcDecl)) { + signature.returnType.type = this.voidType; + return funcDecl; + } else { + if(funcDecl.returnTypeAnnotation == null) { + if(this.checker.styleSettings.implicitAny) { + this.checker.errorReporter.styleError(funcDecl, "type implicitly set to 'any'"); + } + signature.returnType.type = this.anyType; + fgSym.flags |= TypeScript.SymbolFlags.RecursivelyReferenced; + } + return funcDecl; + } + } + signature.typeCheckStatus = TypeScript.TypeCheckStatus.Started; + this.checker.addStartedPTO(signature); + var prevScope = this.scope; + var prevFnc = this.thisFnc; + var prevMethodStatus = this.enclosingFncIsMethod; + var prevClassNode = this.thisClassNode; + this.enclosingFncIsMethod = funcDecl.isMethod() || funcDecl.isConstructor; + this.thisFnc = funcDecl; + var container = funcDecl.type.symbol; + var prevThisType = this.thisType; + var prevLocationInfo = this.checker.locationInfo; + var funcTable = null; + var acceptedContextualType = false; + var targetParams = null; + var targetReturnType = null; + var isGetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor); + var isSetter = funcDecl.isAccessor() && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.SetAccessor); + var accessorType = (isGetter || isSetter) && funcDecl.accessorSymbol ? funcDecl.accessorSymbol.getType() : null; + var prevModDecl = this.checker.currentModDecl; + if(funcDecl.isConstructor && !funcDecl.isOverload) { + if(fnType.instanceType == null) { + this.checker.errorReporter.simpleError(funcDecl, "Malformed function body (is this a class named the same as an existing interface?)"); + return funcDecl; + } + if(funcDecl.classDecl.type.construct == null) { + this.checker.errorReporter.simpleError(funcDecl, "Malformed constructor (is this a class named the same as an existing class?)"); + return funcDecl; + } + this.scope = fnType.instanceType.constructorScope; + var ssb = this.scope; + funcTable = ssb.valueMembers.allMembers; + } else if((funcDecl.isSpecialFn() && !(funcDecl.fncFlags & TypeScript.FncFlags.Signature)) || funcDecl.isOverload) { + funcTable = funcDecl.symbols; + if(!TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Static) && fnType.containedScope) { + this.scope = fnType.containedScope; + } + } else { + if(funcDecl.bod) { + this.scope = fnType.containedScope; + } + var ssb = this.scope; + if(ssb && ssb.valueMembers) { + funcTable = ssb.valueMembers.allMembers; + } + } + if(funcDecl.isConstructor && funcDecl.bod && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)) { + var hasBaseType = TypeScript.hasFlag(funcDecl.classDecl.type.instanceType.typeFlags, TypeScript.TypeFlags.HasBaseType); + var noSuperCallAllowed = !hasBaseType || TypeScript.hasFlag(funcDecl.classDecl.type.instanceType.typeFlags, TypeScript.TypeFlags.HasBaseTypeOfObject); + var superCallMustBeFirst = TypeScript.hasFlag((funcDecl.classDecl).varFlags, TypeScript.VarFlags.ClassSuperMustBeFirstCallInConstructor); + if(noSuperCallAllowed && this.classConstructorHasSuperCall(funcDecl)) { + this.checker.errorReporter.simpleError(funcDecl, "Calls to 'super' constructor are not allowed in classes that either inherit directly from 'Object' or have no base class"); + } else if(hasBaseType) { + if(superCallMustBeFirst) { + if(!funcDecl.bod || !funcDecl.bod.members.length || !((funcDecl.bod.members[0].nodeType == TypeScript.NodeType.Call && (funcDecl.bod.members[0]).target.nodeType == TypeScript.NodeType.Super) || (TypeScript.hasFlag(funcDecl.bod.flags, TypeScript.ASTFlags.StrictMode) && funcDecl.bod.members.length > 1 && funcDecl.bod.members[1].nodeType == TypeScript.NodeType.Call && (funcDecl.bod.members[1]).target.nodeType == TypeScript.NodeType.Super))) { + this.checker.errorReporter.simpleError(funcDecl, "If a derived class contains initialized properties or constructor parameter properties, the first statement in the constructor body must be a call to the super constructor"); + } + } else if(!this.classConstructorHasSuperCall(funcDecl)) { + this.checker.errorReporter.simpleError(funcDecl, "Constructors for derived classes must contain a call to the class's 'super' constructor"); + } + } + } + if(funcDecl.isMethod() && funcDecl.type.enclosingType) { + var enclosingClassNode = null; + if(funcDecl.type.enclosingType.symbol.declAST.nodeType == TypeScript.NodeType.FuncDecl) { + enclosingClassNode = (funcDecl.type.enclosingType.symbol.declAST).classDecl; + } else if(funcDecl.type.enclosingType.symbol.declAST.nodeType == TypeScript.NodeType.ClassDeclaration) { + enclosingClassNode = funcDecl.type.enclosingType.symbol.declAST; + } + if(enclosingClassNode) { + this.thisClassNode = enclosingClassNode; + } + } + if(fnType.enclosingType) { + ; + var enclosingSym = fnType.symbol.container; + if(enclosingSym && enclosingSym.isType() && enclosingSym.getType().isClass()) { + enclosingSym = enclosingSym.container; + } + if(enclosingSym && enclosingSym.declAST && enclosingSym.declAST.nodeType == TypeScript.NodeType.ModuleDeclaration) { + this.checker.currentModDecl = enclosingSym.declAST; + } + } + if(funcDecl.unitIndex > 0) { + if(this.checker.units && (funcDecl.unitIndex < this.checker.units.length)) { + this.checker.locationInfo = this.checker.units[funcDecl.unitIndex]; + } else { + this.checker.locationInfo = TypeScript.unknownLocationInfo; + } + } + if(fnType.enclosingType) { + this.thisType = fnType.enclosingType; + } else { + this.thisType = prevThisType; + } + var paramLen = signature.parameters.length; + if(!funcDecl.isConstructor && funcDecl.bod && !funcDecl.isSignature()) { + var tmpParamScope = this.scope; + var ssb = this.scope; + if(!funcDecl.isMethod() && funcDecl.returnTypeAnnotation == null) { + if(prevScope && funcDecl.name && !funcDecl.name.isMissing()) { + var considerSym = prevScope.findAmbient(funcDecl.name.text, false, false); + if(considerSym && considerSym.declAST && considerSym.declAST.type) { + this.checker.setContextualType(considerSym.declAST.type, false); + } + } + if(this.checker.hasTargetType()) { + var candidateTypeContext = this.checker.getTargetTypeContext(); + var candidateType = candidateTypeContext.contextualType; + if(this.checker.canContextuallyTypeFunction(candidateType, funcDecl, true)) { + var candidateSigs = candidateType.construct ? candidateType.construct : candidateType.call; + candidateTypeContext.targetSig = candidateSigs.signatures[0]; + var candidateParams = candidateTypeContext.targetSig.parameters; + targetParams = candidateParams; + targetReturnType = candidateTypeContext.targetSig.returnType.type; + fgSym.type = candidateTypeContext.contextualType; + acceptedContextualType = true; + } else if(candidateType && funcDecl.isAccessor()) { + accessorType = candidateType; + candidateTypeContext.targetAccessorType = accessorType; + } else { + this.checker.killCurrentContextualType(); + } + } + } + var paramTable = ssb.valueMembers; + this.scope = new TypeScript.SymbolScopeBuilder(paramTable, null, null, null, prevScope, container); + for(var p = 0; p < paramLen; p++) { + var symbol = signature.parameters[p]; + var ast = symbol.declAST; + if(this.checker.hasTargetType() && (targetParams && (this.checker.getTargetTypeContext().targetSig.hasVariableArgList || p < targetParams.length))) { + var candidateTypeContext = this.checker.getTargetTypeContext(); + var hasVarArgList = candidateTypeContext.targetSig.hasVariableArgList; + ast.type = hasVarArgList && p >= targetParams.length - 1 ? targetParams[targetParams.length - 1].getType().elementType : targetParams[p].getType(); + ast.sym.setType(ast.type); + (ast.sym).typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); + } else { + this.typeCheck(ast); + } + if(isSetter && accessorType) { + ast = this.cast(ast, accessorType); + } + symbol.container = container; + this.checkTypePrivacy(symbol.getType(), container, function (typeName, isModuleName) { + return _this.functionArgumentPrivacyErrorReporter(funcDecl, p, symbol, typeName, isModuleName); + }); + paramTable.publicMembers.add(symbol.name, symbol); + } + this.scope = tmpParamScope; + } else { + this.typeCheck(funcDecl.arguments); + for(var p = 0; p < paramLen; p++) { + signature.parameters[p].parameter.typeLink.type = funcDecl.arguments.members[p].type; + this.checkTypePrivacy(signature.parameters[p].getType(), container, function (typeName, isModuleName) { + return _this.functionArgumentPrivacyErrorReporter(funcDecl, p, signature.parameters[p], typeName, isModuleName); + }); + if((funcDecl.arguments.members[p]).parameterPropertySym) { + (funcDecl.arguments.members[p]).parameterPropertySym.setType(funcDecl.arguments.members[p].type); + } + } + if((funcDecl.fncFlags & TypeScript.FncFlags.IndexerMember)) { + if(!paramLen || paramLen > 1) { + this.checker.errorReporter.simpleError(funcDecl, "Index signatures may take one and only one parameter"); + } else if(funcDecl.arguments.members[0].type == this.checker.numberType) { + fnType.index.flags |= TypeScript.SignatureFlags.IsNumberIndexer; + } else if(funcDecl.arguments.members[0].type == this.checker.stringType) { + fnType.index.flags |= TypeScript.SignatureFlags.IsStringIndexer; + } else { + this.checker.errorReporter.simpleError(funcDecl.arguments.members[0], "Index signatures may only take 'string' or 'number' as their parameter"); + } + } + } + if(funcDecl.bod && (!funcDecl.isSignature())) { + if(!(funcDecl.isConstructor)) { + this.addFormals(container, signature, funcTable); + } else { + this.addConstructorLocalArgs(funcDecl, funcTable, TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.ClassMethod)); + if(this.thisClassNode && this.thisClassNode.extendsList) { + var tmpScope = this.scope; + var funcMembers = new TypeScript.ScopedMembers(funcTable); + this.scope = new TypeScript.FilteredSymbolScopeBuilder(funcMembers, prevScope, funcDecl.type.symbol, function (sym) { + return sym.kind() == TypeScript.SymbolKind.Parameter; + }); + this.typeCheckBaseCalls(this.thisClassNode.extendsList); + this.scope = tmpScope; + } + } + var prevMod = this.checker.currentModDecl; + if(funcDecl.type && funcDecl.type.symbol && !funcDecl.isMethod() && funcDecl.type.symbol.declModule) { + this.checker.currentModDecl = funcDecl.type.symbol.declModule; + } + if(acceptedContextualType) { + this.checker.setContextualType(null, this.checker.inProvisionalTypecheckMode()); + } + this.typeCheck(funcDecl.bod); + if(acceptedContextualType) { + this.checker.unsetContextualType(); + } + this.checker.currentModDecl = prevMod; + if(this.checker.checkControlFlow) { + var cfg = funcDecl.buildControlFlow(); + if(this.checker.printControlFlowGraph) { + cfg.print(this.checker.errorReporter.outfile); + } + cfg.reportUnreachable(this.checker.errorReporter); + if(this.checker.checkControlFlowUseDef) { + cfg.useDef(this.checker.errorReporter, funcDecl.type.symbol); + } + } + if(funcDecl.isConstructor) { + var fns = funcDecl.scopes; + var fnsLen = fns.members.length; + var freeVars; + var sym; + var j = 0; + for(; j < fnsLen; j++) { + var fn = fns.members[j]; + if(!fn.isSignature()) { + if(TypeScript.hasFlag(fn.fncFlags, TypeScript.FncFlags.Method) && (!TypeScript.hasFlag(fn.fncFlags, TypeScript.FncFlags.Static))) { + this.checkPromoteFreeVars(fn, funcDecl.type.symbol); + } + } + } + } + } + this.scope = prevScope; + this.thisFnc = prevFnc; + this.thisClassNode = prevClassNode; + this.enclosingFncIsMethod = prevMethodStatus; + this.thisType = prevThisType; + this.checker.locationInfo = prevLocationInfo; + this.checker.currentModDecl = prevModDecl; + signature.typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); + if(funcDecl.returnTypeAnnotation) { + this.checkForVoidConstructor(funcDecl.returnTypeAnnotation.type, funcDecl.returnTypeAnnotation); + if(signature.returnType.type == null) { + this.checker.resolveTypeLink(this.scope, signature.returnType, false); + } + } else if(targetReturnType) { + signature.returnType.type = targetReturnType; + } + if(!(fgSym.flags & TypeScript.SymbolFlags.RecursivelyReferenced) && funcDecl.returnStatementsWithExpressions.length > 0) { + var collection = { + getLength: function () { + return funcDecl.returnStatementsWithExpressions.length; + }, + setTypeAtIndex: function (index, type) { + funcDecl.returnStatementsWithExpressions[index].type = type; + }, + getTypeAtIndex: function (index) { + return funcDecl.returnStatementsWithExpressions[index].type; + } + }; + var bestCommonReturnType = funcDecl.returnStatementsWithExpressions[0].type; + bestCommonReturnType = this.checker.findBestCommonType(bestCommonReturnType, null, collection, true); + if(bestCommonReturnType) { + signature.returnType.type = this.checker.widenType(bestCommonReturnType); + } else { + for(var i = 0; i < funcDecl.returnStatementsWithExpressions.length; i++) { + this.checker.errorReporter.simpleError(funcDecl.returnStatementsWithExpressions[i], "Incompatible return type"); + } + signature.returnType.type = this.anyType; + } + } + var onlyHasThrow = false; + if(signature.returnType.type == null) { + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.HasReturnExpression)) { + if(this.checker.styleSettings.implicitAny) { + this.checker.errorReporter.styleError(funcDecl, "type implicitly set to 'any'"); + } + signature.returnType.type = this.anyType; + } else { + signature.returnType.type = this.voidType; + } + } else if(signature.returnType.type == this.nullType || signature.returnType.type == this.checker.undefinedType) { + signature.returnType.type = this.anyType; + } else if((signature.returnType.type != this.voidType && signature.returnType.type != this.checker.undefinedType && signature.returnType.type != this.anyType)) { + if(!funcDecl.isSignature() && !funcDecl.isConstructor && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.HasReturnExpression) && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.IsFatArrowFunction)) { + onlyHasThrow = (funcDecl.bod.members.length > 0) && (funcDecl.bod.members[0].nodeType == TypeScript.NodeType.Throw); + if(!onlyHasThrow) { + this.checker.errorReporter.simpleError(funcDecl.returnTypeAnnotation || funcDecl, "Function declared a non-void return type, but has no return expression"); + } + } + this.checkTypePrivacy(signature.returnType.type, container, function (typeName, isModuleName) { + return _this.functionReturnTypePrivacyErrorReporter(funcDecl, signature, typeName, isModuleName); + }); + } + if(funcDecl.accessorSymbol) { + var accessorType = funcDecl.accessorSymbol.getType(); + if(!onlyHasThrow && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor) && !TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.HasReturnExpression)) { + this.checker.errorReporter.simpleError(funcDecl, "Getters must return a value"); + } + if(accessorType) { + if((TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor) && accessorType != signature.returnType.type) || (funcDecl.arguments.members.length > 0 && accessorType != funcDecl.arguments.members[0].type)) { + this.checker.errorReporter.simpleError(funcDecl, "Getter and setter types do not agree"); + } + } else { + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { + funcDecl.accessorSymbol.setType(signature.returnType.type); + } else { + if(funcDecl.arguments.members.length != 1) { + this.checker.errorReporter.simpleError(funcDecl, "Setters may have one and only one argument"); + } else { + funcDecl.accessorSymbol.setType(funcDecl.arguments.members[0].type); + } + } + } + } + this.typeCheckOverloadSignatures(fnType, funcDecl); + return funcDecl; + }; + TypeFlow.prototype.typeCheckBases = function (type) { + var seenInterface = false; + var bases = type.extendsList; + var baseLinks = type.extendsTypeLinks; + if(bases) { + var len = bases.length; + if(len > 0) { + type.typeFlags |= TypeScript.TypeFlags.HasBaseType; + } + for(var i = 0; i < len; i++) { + if(bases[i] == this.checker.anyType) { + baseLinks[i].type = null; + var oldErrors = this.checker.errorReporter.getCapturedErrors(); + TypeScript.CompilerDiagnostics.assert(oldErrors.length == 0, "There shouldnt be any contextual errors when typechecking base type names"); + this.checker.errorReporter.pushToErrorSink = true; + bases[i] = this.checker.resolveBaseTypeLink(baseLinks[i], type.containedScope); + this.checker.errorReporter.pushToErrorSink = false; + this.checker.errorReporter.freeCapturedErrors(); + } + var base = bases[i]; + var baseRef = baseLinks[i].ast; + var baseTypeOfObject = base.symbol && base.symbol.name == "Object" && base.symbol.container == this.checker.gloMod; + if(baseTypeOfObject) { + type.typeFlags |= TypeScript.TypeFlags.HasBaseTypeOfObject; + } + if(base.isClassInstance()) { + if(!(type.isClassInstance())) { + this.checker.errorReporter.simpleError(baseRef, "Interface base type must be interface"); + } else { + if(seenInterface) { + this.checker.errorReporter.simpleError(baseRef, "Class may not follow interface as base type"); + } + } + } else if(base.isModuleType()) { + this.checker.errorReporter.simpleError(baseRef, "Types may not be derived from module types"); + } else if(base.members) { + if(!seenInterface) { + seenInterface = true; + } + } else { + if(!(type.isClassInstance())) { + this.checker.errorReporter.simpleError(baseRef, "Interface base type must be interface"); + } else { + this.checker.errorReporter.simpleError(baseRef, "Base type must be interface or class"); + } + break; + } + } + } + }; + TypeFlow.prototype.checkMembersImplementInterfaces = function (implementingType) { + var instanceType = implementingType.getInstanceType(); + if(instanceType.implementsList) { + var len = instanceType.implementsList.length; + for(var i = 0; i < len; i++) { + var interfaceType = instanceType.implementsList[i]; + var comparisonInfo = new TypeScript.TypeComparisonInfo(); + if(!this.checker.sourceIsSubtypeOfTarget(instanceType, interfaceType, comparisonInfo)) { + var emsg = "Class '" + instanceType.getTypeName() + "' declares interface '" + interfaceType.getTypeName() + "' but does not implement it"; + if(!comparisonInfo.message) { + this.checker.errorReporter.simpleErrorFromSym(instanceType.symbol, emsg); + } else { + this.checker.errorReporter.simpleErrorFromSym(instanceType.symbol, emsg + ": " + comparisonInfo.message); + } + } + } + } + }; + TypeFlow.prototype.typeCheckBaseCalls = function (bases) { + if(bases == null) { + return; + } + var basesLen = bases.members.length; + for(var i = 0; i < basesLen; i++) { + var baseExpr = bases.members[i]; + var baseSymbol = null; + if(baseExpr.nodeType == TypeScript.NodeType.Call) { + this.typeCheckNew(baseExpr); + } + } + }; + TypeFlow.prototype.assertUniqueNamesInBaseTypes = function (names, type, classDecl, checkUnique) { + var _this = this; + if(type) { + if(type.members) { + type.members.publicMembers.map(function (key, s, c) { + var sym = s; + var dup = names.lookup(sym.name); + if(dup) { + if(checkUnique) { + _this.checker.errorReporter.simpleError(classDecl, "duplicate member name in bases for " + classDecl.name.actualText + ": " + type.symbol.name + " and " + dup.container.name + " both contain member with name " + sym.name); + } + } else { + names.add(sym.name, sym); + } + }, null); + } + if(type.extendsList) { + var len = type.extendsList.length; + for(var i = 0; i < len; i++) { + if(!(type.extendsList[i].symbol.flags & TypeScript.SymbolFlags.RecursivelyReferenced)) { + this.assertUniqueNamesInBaseTypes(names, type.extendsList[i], classDecl, checkUnique); + } + } + } + } + }; + TypeFlow.prototype.checkBaseTypeMemberInheritance = function (derivedType, derivedTypeDecl) { + var _this = this; + var instanceType = derivedType.getInstanceType(); + if(instanceType.extendsList == null) { + return; + } + var len = instanceType.extendsList.length; + if(len > 0) { + var names = new TypeScript.StringHashTable(); + if(instanceType.isClassInstance()) { + for(var i = 0; i < len; i++) { + this.assertUniqueNamesInBaseTypes(names, instanceType.extendsList[i], derivedTypeDecl, i > 0); + } + } + if(instanceType.members) { + instanceType.members.publicMembers.map(function (key, s, c) { + var sym = s; + for(var j = 0; j < len; j++) { + var base = instanceType.extendsList[j]; + if(base.memberScope == null) { + _this.checker.errorReporter.simpleError(derivedTypeDecl, "Base type '" + base.symbol.name + "' lacks an implementation."); + } else { + var bSym = base.memberScope.find(sym.name, false, false); + if(bSym) { + var aType = sym.getType(); + var bType = bSym.getType(); + if(!(_this.checker.sourceIsSubtypeOfTarget(aType, bType))) { + _this.checker.errorReporter.simpleErrorFromSym(sym, "Type of overridden member '" + sym.name + "' is not subtype of original member defined by type '" + bSym.container.name + "'"); + } else if((sym.kind() == TypeScript.SymbolKind.Type) && (bSym.kind() == TypeScript.SymbolKind.Field)) { + _this.checker.errorReporter.simpleErrorFromSym(sym, "Cannot override field '" + sym.name + "' with method"); + } + } + } + } + }, null); + } + } + }; + TypeFlow.prototype.typeCheckClass = function (classDecl) { + var typeSymbol = classDecl.type.symbol; + if(typeSymbol.typeCheckStatus == TypeScript.TypeCheckStatus.Finished) { + return classDecl; + } else if(typeSymbol.typeCheckStatus == TypeScript.TypeCheckStatus.Started) { + return classDecl; + } else { + typeSymbol.typeCheckStatus = TypeScript.TypeCheckStatus.Started; + this.checker.addStartedPTO(typeSymbol); + } + var prevScope = this.scope; + var svClassNode = this.thisClassNode; + this.thisClassNode = classDecl; + var classType = classDecl.type; + this.typeCheckBases(classType.instanceType); + this.typeCheckBaseListPrivacy(classDecl.extendsList, typeSymbol, true); + this.typeCheckBaseListPrivacy(classDecl.implementsList, typeSymbol, false); + var prevThisType = this.thisType; + this.thisType = classType.instanceType; + this.scope = classType.instanceType.containedScope; + if(classDecl.constructorDecl) { + this.scope = classType.instanceType.constructorScope; + var ssb = this.scope; + var funcTable = ssb.valueMembers.allMembers; + this.addConstructorLocalArgs(classDecl.constructorDecl, funcTable, true); + } + this.typeCheck(classDecl.members); + typeSymbol.typeCheckStatus = TypeScript.TypeCheckStatus.Finished; + this.checkBaseTypeMemberInheritance(classType, classDecl); + this.checkMembersImplementInterfaces(classType); + this.typeCheckOverloadSignatures(classType, classDecl); + this.typeCheckOverloadSignatures(classType.instanceType, classDecl); + if(!classDecl.constructorDecl) { + if(classDecl.extendsList && classDecl.extendsList.members.length && classDecl.extendsList.members[0].type && classDecl.extendsList.members[0].type.symbol.type.isClass()) { + TypeScript.cloneParentConstructGroupForChildType(classDecl.type, classDecl.extendsList.members[0].type.symbol.type); + } + } + this.thisType = prevThisType; + this.thisClassNode = svClassNode; + this.scope = prevScope; + return classDecl; + }; + TypeFlow.prototype.typeCheckOverloadSignatures = function (type, ast) { + if(type.call) { + type.call.typeCheck(this.checker, ast, type.construct != null); + } + if(type.construct) { + type.construct.typeCheck(this.checker, ast, false); + } + if(type.index) { + type.index.typeCheck(this.checker, ast, false); + } + }; + TypeFlow.prototype.typeCheckInterface = function (interfaceDecl) { + this.typeCheckBases(interfaceDecl.type); + this.typeCheckBaseListPrivacy(interfaceDecl.extendsList, interfaceDecl.type.symbol, true); + this.typeCheck(interfaceDecl.members); + this.checkBaseTypeMemberInheritance(interfaceDecl.type, interfaceDecl); + if(interfaceDecl.extendsList) { + for(var i = 0; i < interfaceDecl.extendsList.members.length; i++) { + if(interfaceDecl.extendsList.members[i].type.call) { + if(interfaceDecl.type.call) { + interfaceDecl.type.call.signatures = interfaceDecl.type.call.signatures.concat(interfaceDecl.extendsList.members[i].type.call.signatures); + } else { + interfaceDecl.type.call = interfaceDecl.extendsList.members[i].type.call; + } + } + if(interfaceDecl.extendsList.members[i].type.construct) { + if(interfaceDecl.type.construct) { + interfaceDecl.type.construct.signatures = interfaceDecl.type.construct.signatures.concat(interfaceDecl.extendsList.members[i].type.construct.signatures); + } else { + interfaceDecl.type.construct = interfaceDecl.extendsList.members[i].type.construct; + } + } + if(interfaceDecl.extendsList.members[i].type.index) { + if(interfaceDecl.type.index) { + interfaceDecl.type.index.signatures = interfaceDecl.type.index.signatures.concat(interfaceDecl.extendsList.members[i].type.index.signatures); + } else { + interfaceDecl.type.index = interfaceDecl.extendsList.members[i].type.index; + } + } + } + } + return interfaceDecl; + }; + TypeFlow.prototype.typeCheckImportDecl = function (importDecl) { + var mod = importDecl.alias.type; + var sym = null; + var prevInImportTC = this.inImportTypeCheck; + this.inImportTypeCheck = true; + this.typeCheck(importDecl.alias); + mod = importDecl.alias.type; + if(mod == null) { + this.checker.errorReporter.simpleError(importDecl.alias, "Could not resolve module alias '" + importDecl.id.actualText + "'"); + mod = this.checker.anyType; + (importDecl.id.sym).type = mod; + } + importDecl.id.type = mod; + sym = mod.symbol; + if(!mod.isModuleType()) { + this.checker.errorReporter.simpleError(importDecl.alias, "A module cannot be aliased to a non-module type"); + } else { + sym.type = mod; + if(this.checker.typeFlow.currentScript && this.checker.typeFlow.currentScript.topLevelMod && this.checker.typeFlow.currentScript.topLevelMod.mod) { + this.checker.typeFlow.currentScript.topLevelMod.mod.importedModules.push(importDecl); + } + (importDecl.id.sym).type = mod; + if(mod.symbol && mod.symbol.declAST) { + (mod.symbol.declAST).modFlags &= ~TypeScript.ModuleFlags.ShouldEmitModuleDecl; + } + } + this.inImportTypeCheck = prevInImportTC; + return importDecl; + }; + TypeFlow.prototype.typeCheckModule = function (moduleDecl) { + if(!moduleDecl.mod) { + return moduleDecl; + } + if(this.currentScript) { + this.currentScript.requiresGlobal = true; + } + var mod = moduleDecl.mod; + var sym = null; + var prevScope = this.scope; + var prevThisType = this.thisType; + var prevCurrentModDecl = this.checker.currentModDecl; + this.checker.currentModDecl = moduleDecl; + this.thisType = null; + this.scope = mod.containedScope; + this.typeCheck(moduleDecl.members); + sym = mod.symbol; + this.checker.currentModDecl = prevCurrentModDecl; + this.thisType = prevThisType; + this.scope = prevScope; + moduleDecl.type = mod; + if(sym) { + sym.typeCheckStatus = TypeScript.TypeCheckStatus.Finished; + } + return moduleDecl; + }; + TypeFlow.prototype.typeCheckFor = function (forStmt) { + forStmt.init = this.typeCheck(forStmt.init); + this.nestingLevel++; + forStmt.cond = this.typeCheck(forStmt.cond); + this.typeCheckCondExpr(forStmt.cond); + forStmt.incr = this.typeCheck(forStmt.incr); + this.nestingLevel--; + forStmt.body = this.typeCheck(forStmt.body); + this.typeCheckCompoundStmtBlock(forStmt.body, "for statement"); + forStmt.type = this.voidType; + return forStmt; + }; + TypeFlow.prototype.typeCheckWith = function (withStmt) { + if(this.checker.errorsOnWith) { + this.checker.errorReporter.simpleError(withStmt.expr, "All symbols within a 'with' block will be typed as 'any'"); + } + withStmt.expr = this.typeCheck(withStmt.expr); + this.checker.inWith = true; + withStmt.body = this.typeCheck(withStmt.body); + this.typeCheckCompoundStmtBlock(withStmt.body, "with statement"); + this.checker.inWith = false; + return withStmt; + }; + TypeFlow.prototype.typeCheckForIn = function (forInStmt) { + forInStmt.obj = this.typeCheck(forInStmt.obj); + forInStmt.lval = this.cast(this.typeCheck(forInStmt.lval), this.checker.stringType); + if(forInStmt.lval.nodeType == TypeScript.NodeType.VarDecl) { + var varDecl = forInStmt.lval; + if(varDecl.typeExpr) { + this.checker.errorReporter.simpleError(varDecl, "Variable declarations for for/in expressions may not contain a type annotation"); + } + if(varDecl.sym) { + varDecl.sym.setType(this.checker.stringType); + } + } + forInStmt.body = this.typeCheck(forInStmt.body); + this.typeCheckCompoundStmtBlock(forInStmt.body, "for in statement"); + return forInStmt; + }; + TypeFlow.prototype.typeCheckWhile = function (whileStmt) { + whileStmt.cond = this.typeCheck(whileStmt.cond); + this.typeCheckCondExpr(whileStmt.cond); + whileStmt.body = this.typeCheck(whileStmt.body); + this.typeCheckCompoundStmtBlock(whileStmt.body, "while statement"); + whileStmt.type = this.voidType; + return whileStmt; + }; + TypeFlow.prototype.typeCheckDoWhile = function (doWhileStmt) { + doWhileStmt.cond = this.typeCheck(doWhileStmt.cond); + this.typeCheckCondExpr(doWhileStmt.cond); + doWhileStmt.body = this.typeCheck(doWhileStmt.body); + this.typeCheckCompoundStmtBlock(doWhileStmt.body, "do while statement"); + doWhileStmt.type = this.voidType; + return doWhileStmt; + }; + TypeFlow.prototype.typeCheckCondExpr = function (cond) { + if(this.checker.styleSettings.assignmentInCond) { + if((cond !== null) && (cond.nodeType >= TypeScript.NodeType.Asg) && (cond.nodeType <= TypeScript.NodeType.LastAsg)) { + this.checker.errorReporter.simpleError(cond, "top-level assignment statement in conditional expression"); + } + } + }; + TypeFlow.prototype.typeCheckCompoundStmtBlock = function (stmts, stmtType) { + if(this.checker.styleSettings.blockInCompoundStmt && stmts) { + if(stmts.nodeType != TypeScript.NodeType.Block) { + this.checker.errorReporter.styleError(stmts, stmtType + " requires a block"); + } + } + }; + TypeFlow.prototype.typeCheckIf = function (ifStmt) { + ifStmt.cond = this.typeCheck(ifStmt.cond); + this.typeCheckCondExpr(ifStmt.cond); + ifStmt.thenBod = this.typeCheck(ifStmt.thenBod); + ifStmt.elseBod = this.typeCheck(ifStmt.elseBod); + this.typeCheckCompoundStmtBlock(ifStmt.thenBod, "if statement"); + this.typeCheckCompoundStmtBlock(ifStmt.elseBod, "if statement"); + ifStmt.type = this.voidType; + return ifStmt; + }; + TypeFlow.prototype.typeFromAccessorFuncDecl = function (funcDecl) { + if(!funcDecl.isAccessor()) { + return null; + } + if(TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.GetAccessor)) { + return funcDecl.type.call.signatures[0].returnType.type; + } else { + return funcDecl.type.call.signatures[0].parameters[0].getType(); + } + }; + TypeFlow.prototype.typeCheckObjectLit = function (objectLit) { + var resultType = new TypeScript.Type(); + resultType.symbol = new TypeScript.TypeSymbol(this.checker.anon, objectLit.minChar, objectLit.limChar - objectLit.minChar, this.checker.locationInfo.unitIndex, resultType); + resultType.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + resultType.memberScope = new TypeScript.SymbolTableScope(resultType.members, null, null, null, null); + var aggScope = new TypeScript.SymbolAggregateScope(resultType.symbol); + aggScope.addParentScope(resultType.memberScope); + aggScope.addParentScope(this.scope); + resultType.containedScope = aggScope; + var memberDecls = objectLit.operand; + var prevThisType = this.thisType; + var acceptTargetType = false; + var targetType = null; + if(this.checker.hasTargetType()) { + targetType = this.checker.getTargetTypeContext().contextualType; + if(targetType && targetType.symbol && !this.checker.typeStatusIsFinished(targetType.symbol.typeCheckStatus)) { + if(targetType.symbol.declAST) { + this.typeCheck(targetType.symbol.declAST); + } + } + acceptTargetType = true; + } + if(memberDecls) { + for(var i = 0, len = memberDecls.members.length; i < len; i++) { + var binex = memberDecls.members[i]; + var id = binex.operand1; + var text; + var targetMember = null; + var fieldSymbol = null; + if(id.nodeType == TypeScript.NodeType.Name) { + text = (id).text; + } else if(id.nodeType == TypeScript.NodeType.QString) { + var idText = (id).text; + text = idText.substring(1, idText.length - 1); + } else { + this.checker.errorReporter.simpleError(objectLit, "malformed object literal"); + resultType = this.anyType; + break; + } + if(acceptTargetType && targetType.memberScope) { + targetMember = targetType.memberScope.find(text, false, false); + } + if(binex.operand2.nodeType == TypeScript.NodeType.FuncDecl && (binex.operand2).isAccessor()) { + var funcDecl = binex.operand2; + var accessorSym = resultType.members.publicMembers.lookup(text); + accessorSym = this.checker.createAccessorSymbol(funcDecl, accessorSym, resultType, true, false, resultType.memberScope, null); + funcDecl.accessorSymbol = accessorSym; + fieldSymbol = accessorSym; + if(id.nodeType == TypeScript.NodeType.Name) { + (id).sym = accessorSym; + } + } + this.checker.typeCheckWithContextualType(acceptTargetType && targetMember ? targetMember.getType() : null, false, acceptTargetType, binex.operand2); + if(acceptTargetType && targetMember) { + if((binex.operand2.type == this.anyType || this.checker.sourceIsAssignableToTarget(binex.operand2.type, targetMember.getType())) || (binex.operand2.nodeType == TypeScript.NodeType.FuncDecl && (binex.operand2).isAccessor() && this.typeFromAccessorFuncDecl(binex.operand2) == targetMember.getType())) { + binex.operand1.type = targetMember.getType(); + } + } else { + binex.operand2.type = binex.operand2.type == this.checker.undefinedType ? this.anyType : binex.operand2.type; + } + if(fieldSymbol == null) { + var memberType = binex.operand2.type; + var field = new TypeScript.ValueLocation(); + fieldSymbol = new TypeScript.FieldSymbol(text, id.minChar, this.checker.locationInfo.unitIndex, true, field); + fieldSymbol.flags |= TypeScript.SymbolFlags.Property; + field.symbol = fieldSymbol; + fieldSymbol.typeCheckStatus = this.checker.getTypeCheckFinishedStatus(); + field.typeLink = new TypeScript.TypeLink(); + field.typeLink.type = memberType; + resultType.members.publicMembers.add(text, fieldSymbol); + } + fieldSymbol.isObjectLitField = true; + } + } + this.thisType = prevThisType; + objectLit.type = resultType; + if(targetType) { + objectLit.targetType = targetType; + } + }; + TypeFlow.prototype.typeCheckArrayLit = function (arrayLit) { + var elements = arrayLit.operand; + var elementType = this.anyType; + var targetElementType = null; + var comparisonInfo = new TypeScript.TypeComparisonInfo(); + comparisonInfo.onlyCaptureFirstError = true; + if(this.checker.hasTargetType()) { + var targetType = this.checker.getTargetTypeContext().contextualType; + if(targetType.elementType) { + targetElementType = targetType.elementType; + } + } + if(elements) { + var prevInArrayElemTypeCheck = this.inArrayElementTypeCheck; + this.inArrayElementTypeCheck = true; + this.checker.typeCheckWithContextualType(targetElementType, this.checker.inProvisionalTypecheckMode(), targetElementType != null, elements); + this.inArrayElementTypeCheck = prevInArrayElemTypeCheck; + elementType = elements.members[0].type; + var collection = { + getLength: function () { + return elements.members.length; + }, + setTypeAtIndex: function (index, type) { + elements.members[index].type = type; + }, + getTypeAtIndex: function (index) { + return elements.members[index].type; + } + }; + elementType = this.checker.findBestCommonType(elementType, targetElementType, collection, false, comparisonInfo); + if(elementType == this.checker.undefinedType || (!prevInArrayElemTypeCheck && elementType == this.nullType)) { + elementType = this.anyType; + } + } + if(!elementType) { + var emsg = "Incompatible types in array literal expression"; + if(!comparisonInfo.message) { + this.checker.errorReporter.simpleError(arrayLit, emsg); + } else { + this.checker.errorReporter.simpleError(arrayLit, emsg + ": " + comparisonInfo.message); + } + elementType = this.anyType; + } else if(targetElementType) { + if(this.checker.sourceIsAssignableToTarget(elementType, targetElementType)) { + elementType = targetElementType; + } + } + arrayLit.type = this.checker.makeArrayType(elementType); + }; + TypeFlow.prototype.checkForVoidConstructor = function (type, ast) { + if(type && type.construct && type.construct.signatures.length > 0) { + for(var i = 0; i < type.construct.signatures.length; i++) { + if(type.construct.signatures[i].returnType.type == this.checker.voidType) { + this.checker.errorReporter.simpleError(ast, "Constructors may not have a return type of 'void'"); + break; + } + } + } + }; + TypeFlow.prototype.typeCheckReturn = function (returnStmt) { + if(this.thisFnc) { + var targetType = null; + if(this.checker.hasTargetType()) { + var tcContext = this.checker.getTargetTypeContext(); + var accessorType = tcContext.targetAccessorType; + if(accessorType) { + targetType = accessorType; + } else { + var targetSig = this.checker.getTargetTypeContext().targetSig; + if(targetSig && targetSig.returnType.type != this.voidType) { + targetType = targetSig.returnType.type; + } + } + } + if(returnStmt.returnExpression) { + this.thisFnc.fncFlags |= TypeScript.FncFlags.HasReturnExpression; + if(targetType == null && this.thisFnc.returnTypeAnnotation && this.thisFnc.returnTypeAnnotation.type && this.thisFnc.returnTypeAnnotation.type != this.voidType) { + targetType = this.thisFnc.returnTypeAnnotation.type; + } + this.checker.typeCheckWithContextualType(targetType, this.checker.inProvisionalTypecheckMode(), targetType != null, returnStmt.returnExpression); + var expectedReturnType = (this.thisFnc.returnTypeAnnotation && this.thisFnc.returnTypeAnnotation.type) ? this.thisFnc.returnTypeAnnotation.type : targetType; + if(expectedReturnType) { + if(expectedReturnType == this.voidType && returnStmt.returnExpression.type != this.voidType) { + this.checker.errorReporter.simpleError(returnStmt, "Return with value expression in void function"); + returnStmt.type = returnStmt.returnExpression.type; + } else { + returnStmt.returnExpression = this.cast(returnStmt.returnExpression, expectedReturnType); + returnStmt.type = expectedReturnType; + } + } else { + if(targetType) { + if(returnStmt.returnExpression.type != this.voidType) { + returnStmt.returnExpression = this.cast(returnStmt.returnExpression, targetType); + } else { + returnStmt.returnExpression.type = targetType; + } + } + returnStmt.type = returnStmt.returnExpression.type; + } + this.thisFnc.returnStatementsWithExpressions[this.thisFnc.returnStatementsWithExpressions.length] = returnStmt; + } else { + returnStmt.type = targetType == null ? this.checker.voidType : targetType; + } + } + return returnStmt; + }; + TypeFlow.prototype.typeCheckInstOf = function (ast) { + var binex = ast; + binex.operand1 = this.typeCheck(binex.operand1); + binex.operand2 = this.typeCheck(binex.operand2); + if(!((binex.operand1.type == this.checker.anyType || this.checker.sourceIsSubtypeOfTarget(binex.operand1.type, this.objectInterfaceType)) && (binex.operand2.type == this.anyType || this.checker.sourceIsSubtypeOfTarget(binex.operand2.type, this.functionInterfaceType)))) { + this.checker.errorReporter.simpleError(ast, "The instanceof operator requires the left operand to be of type Any or an object type, and the right operand to be of type Any or a subtype of the Function interface type"); + } + binex.type = this.booleanType; + return binex; + }; + TypeFlow.prototype.typeCheckCommaOperator = function (ast) { + var binex = ast; + binex.operand1 = this.typeCheck(binex.operand1); + binex.operand2 = this.typeCheck(binex.operand2); + binex.type = binex.operand2.type; + return binex; + }; + TypeFlow.prototype.typeCheckLogOr = function (binex) { + binex.operand1 = this.typeCheck(binex.operand1); + binex.operand2 = this.typeCheck(binex.operand2); + var leftType = binex.operand1.type; + var rightType = binex.operand2.type; + if(leftType == this.checker.anyType || rightType == this.checker.anyType) { + binex.type = this.checker.anyType; + } else if(leftType == this.checker.booleanType) { + if(rightType == this.checker.booleanType) { + binex.type = this.checker.booleanType; + } else { + binex.type = this.checker.anyType; + } + } else if(leftType == this.checker.numberType) { + if(rightType == this.checker.numberType) { + binex.type = this.checker.numberType; + } else { + binex.type = this.checker.anyType; + } + } else if(leftType == this.checker.stringType) { + if(rightType == this.checker.stringType) { + binex.type = this.checker.stringType; + } else { + binex.type = this.checker.anyType; + } + } else { + if(this.checker.sourceIsSubtypeOfTarget(leftType, rightType)) { + binex.type = rightType; + } else if(this.checker.sourceIsSubtypeOfTarget(rightType, leftType)) { + binex.type = leftType; + } else { + binex.type = this.checker.anyType; + } + } + return binex; + }; + TypeFlow.prototype.typeCheckLogAnd = function (binex) { + binex.operand1 = this.typeCheck(binex.operand1); + binex.operand2 = this.typeCheck(binex.operand2); + binex.type = binex.operand2.type; + return binex; + }; + TypeFlow.prototype.tryAddCandidates = function (signature, actuals, exactCandidates, conversionCandidates, comparisonInfo) { + var lowerBound = signature.nonOptionalParameterCount; + var upperBound = signature.parameters.length; + var formalLen = lowerBound; + var acceptable = false; + if((actuals.length >= lowerBound) && (signature.hasVariableArgList || actuals.length <= upperBound)) { + formalLen = (signature.hasVariableArgList ? signature.parameters.length : actuals.length); + acceptable = true; + } + var repeatType = null; + if(acceptable || signature.hasVariableArgList) { + if(signature.hasVariableArgList) { + formalLen -= 1; + repeatType = (signature.parameters[formalLen]).parameter.typeLink.type; + repeatType = repeatType.elementType; + acceptable = actuals.length >= formalLen; + } + var len = actuals.length; + var exact = acceptable; + var convert = acceptable; + for(var i = 0; i < len; i++) { + var typeA; + if(i < formalLen) { + typeA = (signature.parameters[i]).parameter.typeLink.type; + } else { + typeA = repeatType; + } + var typeB = actuals[i]; + if(!typeA || !typeB || !(this.checker.typesAreIdentical(typeA, typeB))) { + exact = false; + } + if(!this.checker.sourceIsAssignableToTarget(typeB, typeA, comparisonInfo)) { + convert = false; + } + if(!(exact || convert)) { + break; + } + } + if(exact) { + exactCandidates[exactCandidates.length] = signature; + } else if(convert && (exactCandidates.length == 0)) { + conversionCandidates[conversionCandidates.length] = signature; + } + } + }; + TypeFlow.prototype.resolveOverload = function (application, group) { + var rd = this.resolutionDataCache.getResolutionData(); + var actuals = rd.actuals; + var exactCandidates = rd.exactCandidates; + var conversionCandidates = rd.conversionCandidates; + var candidate = null; + var hasOverloads = group.signatures.length > 1; + var comparisonInfo = new TypeScript.TypeComparisonInfo(); + var args = null; + var target = null; + if(application.nodeType == TypeScript.NodeType.Call || application.nodeType == TypeScript.NodeType.New) { + var callEx = application; + args = callEx.arguments; + target = callEx.target; + if(callEx.arguments) { + var len = callEx.arguments.members.length; + for(var i = 0; i < len; i++) { + actuals[i] = callEx.arguments.members[i].type; + } + } + } else if(application.nodeType == TypeScript.NodeType.Index) { + var binExp = application; + target = binExp.operand1; + args = new TypeScript.ASTList(); + args.members[0] = binExp.operand2; + actuals[0] = binExp.operand2.type; + } + for(var j = 0, groupLen = group.signatures.length; j < groupLen; j++) { + var signature = group.signatures[j]; + if(hasOverloads && signature == group.definitionSignature && !this.checker.canCallDefinitionSignature) { + continue; + } + if(!signature.returnType.type && signature.declAST && (signature.typeCheckStatus != TypeScript.TypeCheckStatus.Finished)) { + this.typeCheckFunction(signature.declAST); + } + this.tryAddCandidates(signature, actuals, exactCandidates, conversionCandidates, comparisonInfo); + } + var apparentTarget = target.nodeType == TypeScript.NodeType.Dot ? (target).operand2 : target; + if(exactCandidates.length == 0) { + var applicableCandidates = this.checker.getApplicableSignatures(conversionCandidates, args, comparisonInfo); + if(applicableCandidates.length > 0) { + var candidateInfo = this.checker.findMostApplicableSignature(applicableCandidates, args); + if(candidateInfo.ambiguous) { + this.checker.errorReporter.simpleError(apparentTarget, "Ambiguous call expression - could not choose overload"); + } + candidate = candidateInfo.sig; + } else { + var emsg = "Supplied parameters do not match any signature of call target"; + if(comparisonInfo.message) { + this.checker.errorReporter.simpleError(apparentTarget, emsg + ":\n\t" + comparisonInfo.message); + } else { + this.checker.errorReporter.simpleError(apparentTarget, emsg); + } + } + } else { + if(exactCandidates.length > 1) { + var applicableSigs = []; + for(var i = 0; i < exactCandidates.length; i++) { + applicableSigs[i] = { + signature: exactCandidates[i], + hadProvisionalErrors: false + }; + } + var candidateInfo = this.checker.findMostApplicableSignature(applicableSigs, args); + if(candidateInfo.ambiguous) { + this.checker.errorReporter.simpleError(apparentTarget, "Ambiguous call expression - could not choose overload"); + } + candidate = candidateInfo.sig; + } else { + candidate = exactCandidates[0]; + } + } + this.resolutionDataCache.returnResolutionData(rd); + return candidate; + }; + TypeFlow.prototype.typeCheckNew = function (ast) { + var callEx = ast; + callEx.target = this.typeCheck(callEx.target); + var target = callEx.target; + if(target.type.construct || target.type.call) { + this.preTypeCheckCallArgs(callEx.arguments); + } else { + callEx.arguments = this.typeCheck(callEx.arguments); + } + if(target.type == this.anyType) { + callEx.type = this.anyType; + callEx.arguments = this.typeCheck(callEx.arguments); + } else { + if(target.type.construct) { + var signature = this.resolveOverload(callEx, target.type.construct); + if(signature == null) { + callEx.type = this.anyType; + } else if(signature.returnType.type == this.voidType) { + callEx.type = this.anyType; + callEx.signature = signature; + } else { + callEx.type = signature.returnType.type; + callEx.signature = signature; + } + } else if(target.type.call) { + var signature = this.resolveOverload(callEx, target.type.call); + if(signature == null) { + callEx.type = this.anyType; + } else if((signature.returnType.type == this.voidType) || (signature.returnType.type == this.anyType)) { + callEx.type = this.anyType; + callEx.signature = signature; + } else { + this.checker.errorReporter.simpleError(callEx.target, "new expression only valid on constructors"); + } + } else if(target.type.elementType) { + callEx.type = target.type; + } else { + this.checker.errorReporter.invalidCall(callEx, callEx.nodeType, this.scope); + callEx.type = this.anyType; + } + } + this.postTypeCheckCallArgs(callEx); + return callEx; + }; + TypeFlow.prototype.preTypeCheckCallArgs = function (args) { + if(!args) { + return; + } + for(var i = 0; i < args.members.length; i++) { + switch(args.members[i].nodeType) { + case TypeScript.NodeType.FuncDecl: + case TypeScript.NodeType.ObjectLit: + case TypeScript.NodeType.ArrayLit: + continue; + default: + this.typeCheck(args.members[i]); + break; + } + } + }; + TypeFlow.prototype.postTypeCheckCallArgs = function (callEx) { + var acceptedTargetType = false; + var i = 0; + if(callEx.target && callEx.target.type && callEx.signature && callEx.arguments) { + var sig = callEx.signature; + if(sig && callEx.arguments.members.length >= sig.nonOptionalParameterCount) { + acceptedTargetType = true; + var targetType = null; + var nonVarArgFormalParamLength = sig.hasVariableArgList ? sig.parameters.length - 1 : sig.parameters.length; + var nonVarArgActualParamLength = callEx.arguments.members.length < nonVarArgFormalParamLength ? callEx.arguments.members.length : nonVarArgFormalParamLength; + for(i = 0; i < nonVarArgActualParamLength; i++) { + targetType = sig.parameters[i].getType(); + switch(callEx.arguments.members[i].nodeType) { + case TypeScript.NodeType.FuncDecl: + case TypeScript.NodeType.ObjectLit: + case TypeScript.NodeType.ArrayLit: + this.checker.typeCheckWithContextualType(targetType, this.checker.inProvisionalTypecheckMode(), !sig.parameters[i].declAST.isParenthesized, callEx.arguments.members[i]); + break; + } + } + if(sig.hasVariableArgList) { + var varArgParamIndex = sig.nonOptionalParameterCount - 1; + targetType = sig.parameters[varArgParamIndex].getType(); + if(targetType) { + targetType = targetType.elementType; + } + var isParenthesized = !sig.parameters[varArgParamIndex].declAST.isParenthesized; + for(i = nonVarArgActualParamLength; i < callEx.arguments.members.length; i++) { + switch(callEx.arguments.members[i].nodeType) { + case TypeScript.NodeType.FuncDecl: + case TypeScript.NodeType.ObjectLit: + case TypeScript.NodeType.ArrayLit: + this.checker.typeCheckWithContextualType(targetType, this.checker.inProvisionalTypecheckMode(), isParenthesized, callEx.arguments.members[i]); + break; + } + } + } + } + } + if(!acceptedTargetType && callEx.arguments) { + this.checker.killCurrentContextualType(); + for(i = 0; i < callEx.arguments.members.length; i++) { + switch(callEx.arguments.members[i].nodeType) { + case TypeScript.NodeType.FuncDecl: + case TypeScript.NodeType.ObjectLit: + case TypeScript.NodeType.ArrayLit: + this.typeCheck(callEx.arguments.members[i]); + break; + default: + continue; + } + } + } + }; + TypeFlow.prototype.typeCheckCall = function (ast) { + var callEx = ast; + if(this.checker.styleSettings.newMustBeUsed && (ast.nodeType == TypeScript.NodeType.New)) { + if(TypeScript.hasFlag(ast.flags, TypeScript.ASTFlags.IsStatement)) { + this.checker.errorReporter.styleError(ast, "use of new expression as a statement"); + } + } else if((!this.checker.styleSettings.evalOK) && (ast.nodeType == TypeScript.NodeType.Call)) { + if((callEx.target.nodeType == TypeScript.NodeType.Name) && ((callEx.target).text == "eval")) { + this.checker.errorReporter.styleError(callEx, "eval not permitted"); + } + } + if(callEx.target.nodeType == TypeScript.NodeType.FuncDecl) { + (callEx.target).isInlineCallLiteral = true; + } + var prevInSuperCall = this.inSuperCall; + if(callEx.target.nodeType == TypeScript.NodeType.Super) { + this.inSuperCall = true; + } + callEx.target = this.typeCheck(callEx.target); + this.preTypeCheckCallArgs(callEx.arguments); + var target = callEx.target; + if((target.type == null) || (target.type == this.anyType) || (this.functionInterfaceType && target.type == this.functionInterfaceType)) { + callEx.type = this.anyType; + } else { + var fnType = target.type; + if(fnType.call) { + var signature = this.resolveOverload(callEx, fnType.call); + if(signature == null) { + callEx.type = this.anyType; + } else { + callEx.type = signature.returnType.type; + callEx.signature = signature; + } + } else { + if(callEx.target.nodeType == TypeScript.NodeType.Super && this.thisFnc && this.thisFnc.isConstructor && TypeScript.hasFlag(this.thisFnc.fncFlags, TypeScript.FncFlags.ClassMethod)) { + var signature = fnType.symbol.type.construct ? this.resolveOverload(callEx, fnType.symbol.type.construct) : null; + if(signature == null) { + callEx.type = this.anyType; + } else { + callEx.flags |= TypeScript.ASTFlags.ClassBaseConstructorCall; + callEx.type = signature.returnType.type; + callEx.signature = signature; + } + } else { + callEx.type = this.anyType; + this.checker.errorReporter.invalidCall(callEx, callEx.nodeType, this.scope); + } + } + } + this.postTypeCheckCallArgs(callEx); + this.inSuperCall = prevInSuperCall; + return callEx; + }; + TypeFlow.prototype.assignScopes = function (ast) { + var script = ast; + this.checker.locationInfo = script.locationInfo; + var globalChain = new ScopeChain(this.checker.gloMod, null, this.globalScope); + var context = new TypeScript.AssignScopeContext(globalChain, this, [ + this.checker.currentModDecl + ]); + TypeScript.getAstWalkerFactory().walk(ast, TypeScript.preAssignScopes, TypeScript.postAssignScopes, null, context); + }; + TypeFlow.prototype.findMemberScope = function (enclosingScopeContext, matchFlag) { + var enclosingScope = enclosingScopeContext.getScope(); + var pos = enclosingScopeContext.pos - enclosingScopeContext.getScriptFragmentPosition(); + var scriptFragment = enclosingScopeContext.getScriptFragment(); + var memContext = new TypeScript.MemberScopeContext(this, pos, matchFlag); + memContext.scope = enclosingScope; + if(scriptFragment.nodeType == TypeScript.NodeType.Name) { + return scriptFragment.type.getMemberScope(this); + } else { + TypeScript.getAstWalkerFactory().walk(scriptFragment, TypeScript.preFindMemberScope, null, null, memContext); + if(memContext.ast && enclosingScopeContext.enclosingClassDecl && memContext.ast.type == enclosingScopeContext.enclosingClassDecl.type.instanceType) { + enclosingScopeContext.publicsOnly = false; + } + if(memContext.type) { + return memContext.type.getMemberScope(this); + } else { + return null; + } + } + }; + TypeFlow.prototype.findMemberScopeAt = function (enclosingScopeContext) { + return this.findMemberScope(enclosingScopeContext, TypeScript.ASTFlags.DotLHS); + }; + TypeFlow.prototype.findMemberScopeAtFullAst = function (enclosingScopeContext) { + var matchFlag = TypeScript.ASTFlags.DotLHS; + var pos = enclosingScopeContext.pos; + var astResult = null; + var preFindMemberScopeFullAst = function (ast, parent, walker) { + if(TypeScript.isValidAstNode(ast)) { + if(TypeScript.hasFlag(ast.flags, matchFlag) && (pos == ast.limChar || (pos - 1) == ast.limChar)) { + astResult = ast; + walker.options.stopWalk(); + } + walker.options.goChildren = (ast.minChar <= pos) && (pos <= ast.limChar); + } + return ast; + }; + var preFindMemberScopeFullAstFuzy = function (ast, parent, walker) { + if(TypeScript.isValidAstNode(ast)) { + if(TypeScript.hasFlag(ast.flags, matchFlag) && ((ast.minChar < pos) && (pos <= ast.limChar))) { + astResult = ast; + } + walker.options.goChildren = (ast.minChar <= pos) && (pos <= ast.limChar); + } + return ast; + }; + TypeScript.getAstWalkerFactory().walk(enclosingScopeContext.script, preFindMemberScopeFullAst); + if(astResult == null) { + TypeScript.getAstWalkerFactory().walk(enclosingScopeContext.script, preFindMemberScopeFullAstFuzy); + } + if(astResult && enclosingScopeContext.enclosingClassDecl && astResult.type == enclosingScopeContext.enclosingClassDecl.type.instanceType) { + enclosingScopeContext.publicsOnly = false; + } + if(astResult && astResult.type) { + return astResult.type.getMemberScope(this); + } else { + return null; + } + }; + return TypeFlow; + })(); + TypeScript.TypeFlow = TypeFlow; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (Primitive) { + Primitive._map = []; + Primitive.None = 0; + Primitive.Void = 1; + Primitive.Double = 2; + Primitive.String = 4; + Primitive.Boolean = 8; + Primitive.Any = 16; + Primitive.Null = 32; + Primitive.Undefined = 64; + })(TypeScript.Primitive || (TypeScript.Primitive = {})); + var Primitive = TypeScript.Primitive; + var MemberName = (function () { + function MemberName() { + this.prefix = ""; + this.suffix = ""; + } + MemberName.prototype.isString = function () { + return false; + }; + MemberName.prototype.isArray = function () { + return false; + }; + MemberName.prototype.toString = function () { + return MemberName.memberNameToString(this); + }; + MemberName.memberNameToString = function memberNameToString(memberName) { + var result = memberName.prefix; + if(memberName.isString()) { + result += (memberName).text; + } else { + var ar = memberName; + for(var index = 0; index < ar.entries.length; index++) { + result += MemberName.memberNameToString(ar.entries[index]); + result += ar.delim; + } + } + result += memberName.suffix; + return result; + }; + MemberName.create = function create(arg1, arg2, arg3) { + if(typeof arg1 == "string") { + return new MemberNameString(arg1); + } else { + var result = new MemberNameArray(); + if(arg2) { + result.prefix = arg2; + } + if(arg3) { + result.suffix = arg3; + } + result.entries.push(arg1); + return result; + } + }; + return MemberName; + })(); + TypeScript.MemberName = MemberName; + var MemberNameString = (function (_super) { + __extends(MemberNameString, _super); + function MemberNameString(text) { + _super.call(this); + this.text = text; + } + MemberNameString.prototype.isString = function () { + return true; + }; + return MemberNameString; + })(MemberName); + TypeScript.MemberNameString = MemberNameString; + var MemberNameArray = (function (_super) { + __extends(MemberNameArray, _super); + function MemberNameArray() { + _super.apply(this, arguments); + + this.delim = ""; + this.entries = []; + } + MemberNameArray.prototype.isArray = function () { + return true; + }; + MemberNameArray.prototype.add = function (entry) { + this.entries.push(entry); + }; + MemberNameArray.prototype.addAll = function (entries) { + for(var i = 0; i < entries.length; i++) { + this.entries.push(entries[i]); + } + }; + return MemberNameArray; + })(MemberName); + TypeScript.MemberNameArray = MemberNameArray; + var currentTypeID = -1; + var Type = (function () { + function Type() { + this.typeID = currentTypeID++; + this.construct = null; + this.call = null; + this.index = null; + this.passTypeCreated = TypeScript.CompilerDiagnostics.analysisPass; + this.primitiveTypeClass = Primitive.None; + this.typeFlags = TypeScript.TypeFlags.None; + } + Type.prototype.baseClass = function () { + if(this.extendsList && (this.extendsList.length > 0)) { + return this.extendsList[0]; + } else { + return null; + } + }; + Type.prototype.getArrayBase = function (arrInstType, checker) { + return this.arrayCache.specialize(arrInstType, checker); + }; + Type.prototype.isClass = function () { + return this.instanceType != null; + }; + Type.prototype.isArray = function () { + return this.elementType != null; + }; + Type.prototype.isClassInstance = function () { + return this.symbol && !this.elementType && (this.symbol).type.isClass(); + }; + Type.prototype.getInstanceType = function () { + if(this.isClass()) { + return this.instanceType; + } else { + return this; + } + }; + Type.prototype.hasImplementation = function () { + return TypeScript.hasFlag(this.typeFlags, TypeScript.TypeFlags.HasImplementation); + }; + Type.prototype.setHasImplementation = function () { + this.typeFlags |= TypeScript.TypeFlags.HasImplementation; + }; + Type.prototype.isDouble = function () { + return TypeScript.hasFlag(this.primitiveTypeClass, Primitive.Double); + }; + Type.prototype.isString = function () { + return TypeScript.hasFlag(this.primitiveTypeClass, Primitive.String); + }; + Type.prototype.isBoolean = function () { + return TypeScript.hasFlag(this.primitiveTypeClass, Primitive.Boolean); + }; + Type.prototype.isNull = function () { + return TypeScript.hasFlag(this.primitiveTypeClass, Primitive.Null); + }; + Type.prototype.getTypeName = function () { + return this.getMemberTypeName("", true, false, null); + }; + Type.prototype.getScopedTypeName = function (scope, getPrettyTypeName) { + return this.getMemberTypeName("", true, false, scope, getPrettyTypeName); + }; + Type.prototype.getScopedTypeNameEx = function (scope, getPrettyTypeName) { + return this.getMemberTypeNameEx("", true, false, scope, getPrettyTypeName); + }; + Type.prototype.callCount = function () { + var total = 0; + if(this.call) { + total += this.call.signatures.length; + } + if(this.construct) { + total += this.construct.signatures.length; + } + if(this.index) { + total += this.index.signatures.length; + } + return total; + }; + Type.prototype.getMemberTypeName = function (prefix, topLevel, isElementType, scope, getPrettyTypeName) { + var memberName = this.getMemberTypeNameEx(prefix, topLevel, isElementType, scope, getPrettyTypeName); + return memberName.toString(); + }; + Type.prototype.getMemberTypeNameEx = function (prefix, topLevel, isElementType, scope, getPrettyTypeName) { + if(this.elementType) { + return MemberName.create(this.elementType.getMemberTypeNameEx(prefix, false, true, scope), "", "[]"); + } else if(this.symbol && this.symbol.name && this.symbol.name != "_anonymous" && (((this.call == null) && (this.construct == null) && (this.index == null)) || (TypeScript.hasFlag(this.typeFlags, TypeScript.TypeFlags.BuildingName)) || (this.members && (!this.isClass())))) { + var tn = this.symbol.scopeRelativeName(scope); + return MemberName.create(tn == "null" ? "any" : tn); + } else { + if(this.members || this.call || this.construct) { + if(TypeScript.hasFlag(this.typeFlags, TypeScript.TypeFlags.BuildingName)) { + return MemberName.create("this"); + } + this.typeFlags |= TypeScript.TypeFlags.BuildingName; + var builder = ""; + var allMemberNames = new MemberNameArray(); + var curlies = isElementType || this.index != null; + var memCount = 0; + var delim = "; "; + if(this.members) { + this.members.allMembers.map(function (key, s, unused) { + var sym = s; + if(!TypeScript.hasFlag(sym.flags, TypeScript.SymbolFlags.BuiltIn)) { + var typeNameMember = sym.getTypeNameEx(scope); + if(typeNameMember.isArray() && (typeNameMember).delim == delim) { + allMemberNames.addAll((typeNameMember).entries); + } else { + allMemberNames.add(typeNameMember); + } + memCount++; + curlies = true; + } + }, null); + } + var signatureCount = this.callCount(); + var j; + var len = 0; + var getPrettyFunctionOverload = getPrettyTypeName && !curlies && this.call && this.call.signatures.length > 1 && !this.members && !this.construct; + var shortform = !curlies && (signatureCount == 1 || getPrettyFunctionOverload) && topLevel; + if(this.call) { + allMemberNames.addAll(this.call.toStrings(prefix, shortform, scope, getPrettyFunctionOverload)); + } + if(this.construct) { + allMemberNames.addAll(this.construct.toStrings("new", shortform, scope)); + } + if(this.index) { + allMemberNames.addAll(this.index.toStrings("", shortform, scope)); + } + if((curlies) || (!getPrettyFunctionOverload && (signatureCount > 1) && topLevel)) { + allMemberNames.prefix = "{ "; + allMemberNames.suffix = "}"; + allMemberNames.delim = delim; + } else if(allMemberNames.entries.length > 1) { + allMemberNames.delim = delim; + } + this.typeFlags &= (~TypeScript.TypeFlags.BuildingName); + if((signatureCount == 0) && (memCount == 0)) { + return MemberName.create("{}"); + } else { + return allMemberNames; + } + } else { + return MemberName.create("{}"); + } + } + }; + Type.prototype.checkDecl = function (checker) { + if(this.isClassInstance() || this.isClass()) { + if(this.symbol.declAST) { + checker.typeFlow.inScopeTypeCheckDecl(this.symbol.declAST); + } + } + }; + Type.prototype.getMemberScope = function (flow) { + if(this == flow.anyType) { + return null; + } else if(this.isDouble()) { + if(flow.numberInterfaceType) { + return flow.numberInterfaceType.memberScope; + } else { + return null; + } + } else if(this.isBoolean()) { + if(flow.booleanInterfaceType) { + return flow.booleanInterfaceType.memberScope; + } else { + return null; + } + } else if(this == flow.stringType) { + if(flow.stringInterfaceType) { + return flow.stringInterfaceType.memberScope; + } else { + return null; + } + } else if(this.elementType) { + if(flow.arrayInterfaceType) { + var arrInstType = this.elementType.getArrayBase(flow.arrayInterfaceType, flow.checker); + return arrInstType.memberScope; + } else { + return null; + } + } else { + return this.memberScope; + } + }; + Type.prototype.isReferenceType = function () { + return this.members || this.extendsList || this.construct || this.call || this.index || this.elementType; + }; + Type.prototype.specializeType = function (pattern, replacement, checker, membersOnly) { + if(pattern == this) { + return replacement; + } + var result = this; + if(membersOnly) { + if(this.isReferenceType()) { + result = new Type(); + if(this.members) { + result.members = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + this.members.publicMembers.map(function (key, s, unused) { + var sym = s; + var bSym = sym.specializeType(pattern, replacement, checker); + result.members.addPublicMember(bSym.name, bSym); + }, null); + this.members.privateMembers.map(function (key, s, unused) { + var sym = s; + var bSym = sym.specializeType(pattern, replacement, checker); + result.members.addPrivateMember(bSym.name, bSym); + }, null); + } + if(this.ambientMembers) { + result.ambientMembers = new TypeScript.ScopedMembers(new TypeScript.DualStringHashTable(new TypeScript.StringHashTable(), new TypeScript.StringHashTable())); + this.ambientMembers.publicMembers.map(function (key, s, unused) { + var sym = s; + var bSym = sym.specializeType(pattern, replacement, checker); + result.ambientMembers.addPublicMember(bSym.name, bSym); + }, null); + this.ambientMembers.privateMembers.map(function (key, s, unused) { + var sym = s; + var bSym = sym.specializeType(pattern, replacement, checker); + result.ambientMembers.addPrivateMember(bSym.name, bSym); + }, null); + } + result.containedScope = checker.scopeOf(result); + result.memberScope = result.containedScope; + } + } else { + if(this.elementType) { + if(this.elementType == pattern) { + result = checker.makeArrayType(replacement); + } else { + if(this.elementType.elementType == pattern) { + result = checker.makeArrayType(checker.makeArrayType(replacement)); + } + } + } else if(this.call) { + result = new Type(); + result.call = this.call.specializeType(pattern, replacement, checker); + } + } + return result; + }; + Type.prototype.hasBase = function (baseType) { + if(baseType == this) { + return true; + } else { + if(this.extendsList) { + for(var i = 0, len = this.extendsList.length; i < len; i++) { + if(this.extendsList[i].hasBase(baseType)) { + return true; + } + } + } + } + return false; + }; + Type.prototype.mergeOrdered = function (b, checker, acceptVoid, comparisonInfo) { + if((this == checker.anyType) || (b == checker.anyType)) { + return checker.anyType; + } else if(this == b) { + return this; + } else if((b == checker.nullType) && this != checker.nullType) { + return this; + } else if((this == checker.nullType) && (b != checker.nullType)) { + return b; + } else if(acceptVoid && (b == checker.voidType) && this != checker.voidType) { + return this; + } else if(acceptVoid && (this == checker.voidType) && (b != checker.voidType)) { + return b; + } else if((b == checker.undefinedType) && this != checker.undefinedType) { + return this; + } else if((this == checker.undefinedType) && (b != checker.undefinedType)) { + return b; + } else if(this.elementType && b.elementType) { + if(this.elementType == b.elementType) { + return this; + } else { + var mergedET = this.elementType.mergeOrdered(b.elementType, checker, acceptVoid, comparisonInfo); + if(mergedET == null) { + return checker.makeArrayType(checker.anyType); + } else { + return checker.makeArrayType(mergedET); + } + } + } else if(checker.sourceIsSubtypeOfTarget(this, b, comparisonInfo)) { + return b; + } else if(checker.sourceIsSubtypeOfTarget(b, this, comparisonInfo)) { + return this; + } else { + return null; + } + }; + Type.prototype.isModuleType = function () { + return false; + }; + Type.prototype.hasMembers = function () { + return this.members != null; + }; + Type.prototype.getAllEnclosedTypes = function () { + return null; + }; + Type.prototype.getAllAmbientEnclosedTypes = function () { + return null; + }; + Type.prototype.getPublicEnclosedTypes = function () { + return null; + }; + Type.prototype.getpublicAmbientEnclosedTypes = function () { + return null; + }; + Type.prototype.getDocComments = function () { + if(this.elementType || !this.symbol) { + return []; + } + if(this.isClassInstance() || this.isClass()) { + if(this.symbol.declAST.nodeType == TypeScript.NodeType.FuncDecl) { + return (this.symbol.declAST).classDecl.getDocComments(); + } else { + return this.symbol.getDocComments(); + } + } + if(this.symbol.name && this.symbol.name != "_anonymous" && (((this.call == null) && (this.construct == null) && (this.index == null)) || this.members)) { + return this.symbol.getDocComments(); + } + return []; + }; + return Type; + })(); + TypeScript.Type = Type; + var ModuleType = (function (_super) { + __extends(ModuleType, _super); + function ModuleType(enclosedTypes, ambientEnclosedTypes) { + _super.call(this); + this.enclosedTypes = enclosedTypes; + this.ambientEnclosedTypes = ambientEnclosedTypes; + this.importedModules = []; + } + ModuleType.prototype.isModuleType = function () { + return true; + }; + ModuleType.prototype.hasMembers = function () { + return this.members != null || this.enclosedTypes != null; + }; + ModuleType.prototype.getAllEnclosedTypes = function () { + return this.enclosedTypes; + }; + ModuleType.prototype.getAllAmbientEnclosedTypes = function () { + return this.ambientEnclosedTypes; + }; + ModuleType.prototype.getPublicEnclosedTypes = function () { + return null; + }; + ModuleType.prototype.getpublicAmbientEnclosedTypes = function () { + return null; + }; + ModuleType.findDynamicModuleNameInHashTable = function findDynamicModuleNameInHashTable(moduleType, members) { + var moduleName = null; + members.map(function (key, s, c) { + if(moduleName == null && !TypeScript.isQuoted(key)) { + var symbol = s; + var type = symbol.getType(); + if(type == moduleType) { + moduleName = { + name: key, + symbol: symbol + }; + } + } + }, null); + return moduleName; + }; + ModuleType.prototype.findDynamicModuleName = function (moduleType) { + var moduleName = null; + moduleName = ModuleType.findDynamicModuleNameInHashTable(moduleType, this.members.allMembers); + if(moduleName == null) { + moduleName = ModuleType.findDynamicModuleNameInHashTable(moduleType, this.ambientMembers.allMembers); + } + return moduleName; + }; + return ModuleType; + })(Type); + TypeScript.ModuleType = ModuleType; + var TypeLink = (function () { + function TypeLink() { + this.type = null; + this.ast = null; + } + return TypeLink; + })(); + TypeScript.TypeLink = TypeLink; + function getTypeLink(ast, checker, autoVar) { + var result = new TypeLink(); + result.ast = ast; + if((ast == null) && (autoVar)) { + result.type = checker.anyType; + } else { + result.type = null; + } + return result; + } + TypeScript.getTypeLink = getTypeLink; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + function stripQuotes(str) { + return str.replace("\"", "").replace("'", "").replace("'", "").replace("\"", ""); + } + TypeScript.stripQuotes = stripQuotes; + function isSingleQuoted(str) { + return str.indexOf("'") != -1; + } + TypeScript.isSingleQuoted = isSingleQuoted; + function isQuoted(str) { + return str.indexOf("\"") != -1 || isSingleQuoted(str); + } + TypeScript.isQuoted = isQuoted; + function quoteStr(str) { + return "\"" + str + "\""; + } + TypeScript.quoteStr = quoteStr; + function swapQuotes(str) { + if(str.indexOf("\"") != -1) { + str = str.replace("\"", "'"); + str = str.replace("\"", "'"); + } else { + str = str.replace("'", "\""); + str = str.replace("'", "\""); + } + return str; + } + TypeScript.swapQuotes = swapQuotes; + function changeToSingleQuote(str) { + if(str.indexOf("\"") != -1) { + str = str.replace("\"", "'"); + str = str.replace("\"", "'"); + } + return str; + } + TypeScript.changeToSingleQuote = changeToSingleQuote; + function switchToForwardSlashes(path) { + return path.replace(/\\/g, "/"); + } + TypeScript.switchToForwardSlashes = switchToForwardSlashes; + function trimModName(modName) { + if(modName.length > 6 && modName.substring(modName.length - 6, modName.length) == ".d.str") { + return modName.substring(0, modName.length - 6); + } + if(modName.length > 4 && modName.substring(modName.length - 4, modName.length) == ".str") { + return modName.substring(0, modName.length - 4); + } + if(modName.length > 5 && modName.substring(modName.length - 5, modName.length) == ".d.ts") { + return modName.substring(0, modName.length - 5); + } + if(modName.length > 3 && modName.substring(modName.length - 3, modName.length) == ".ts") { + return modName.substring(0, modName.length - 3); + } + if(modName.length > 3 && modName.substring(modName.length - 3, modName.length) == ".js") { + return modName.substring(0, modName.length - 3); + } + return modName; + } + TypeScript.trimModName = trimModName; + function getDeclareFilePath(fname) { + return isSTRFile(fname) ? changePathToDSTR(fname) : isTSFile(fname) ? changePathToDTS(fname) : changePathToDTS(fname); + } + TypeScript.getDeclareFilePath = getDeclareFilePath; + function isFileOfExtension(fname, ext) { + var invariantFname = fname.toLocaleUpperCase(); + var invariantExt = ext.toLocaleUpperCase(); + var extLength = invariantExt.length; + return invariantFname.length > extLength && invariantFname.substring(invariantFname.length - extLength, invariantFname.length) == invariantExt; + } + function isJSFile(fname) { + return isFileOfExtension(fname, ".js"); + } + TypeScript.isJSFile = isJSFile; + function isSTRFile(fname) { + return isFileOfExtension(fname, ".str"); + } + TypeScript.isSTRFile = isSTRFile; + function isTSFile(fname) { + return isFileOfExtension(fname, ".ts"); + } + TypeScript.isTSFile = isTSFile; + function isDSTRFile(fname) { + return isFileOfExtension(fname, ".d.str"); + } + TypeScript.isDSTRFile = isDSTRFile; + function isDTSFile(fname) { + return isFileOfExtension(fname, ".d.ts"); + } + TypeScript.isDTSFile = isDTSFile; + function getPrettyName(modPath, quote, treatAsFileName) { + if (typeof quote === "undefined") { quote = true; } + if (typeof treatAsFileName === "undefined") { treatAsFileName = false; } + var modName = treatAsFileName ? switchToForwardSlashes(modPath) : trimModName(stripQuotes(modPath)); + var components = this.getPathComponents(modName); + return components.length ? (quote ? quoteStr(components[components.length - 1]) : components[components.length - 1]) : modPath; + } + TypeScript.getPrettyName = getPrettyName; + function getPathComponents(path) { + return path.split("/"); + } + TypeScript.getPathComponents = getPathComponents; + function getRelativePathToFixedPath(fixedModFilePath, absoluteModPath) { + absoluteModPath = switchToForwardSlashes(absoluteModPath); + var modComponents = this.getPathComponents(absoluteModPath); + var fixedModComponents = this.getPathComponents(fixedModFilePath); + var joinStartIndex = 0; + for(; joinStartIndex < modComponents.length && joinStartIndex < fixedModComponents.length; joinStartIndex++) { + if(fixedModComponents[joinStartIndex] != modComponents[joinStartIndex]) { + break; + } + } + if(joinStartIndex != 0) { + var relativePath = ""; + var relativePathComponents = modComponents.slice(joinStartIndex, modComponents.length); + for(; joinStartIndex < fixedModComponents.length; joinStartIndex++) { + if(fixedModComponents[joinStartIndex] != "") { + relativePath = relativePath + "../"; + } + } + return relativePath + relativePathComponents.join("/"); + } + return absoluteModPath; + } + TypeScript.getRelativePathToFixedPath = getRelativePathToFixedPath; + function quoteBaseName(modPath) { + var modName = trimModName(stripQuotes(modPath)); + var path = getRootFilePath(modName); + if(path == "") { + return modPath; + } else { + var components = modName.split(path); + var fileIndex = components.length > 1 ? 1 : 0; + return quoteStr(components[fileIndex]); + } + } + TypeScript.quoteBaseName = quoteBaseName; + function changePathToSTR(modPath) { + return trimModName(stripQuotes(modPath)) + ".str"; + } + TypeScript.changePathToSTR = changePathToSTR; + function changePathToDSTR(modPath) { + return trimModName(stripQuotes(modPath)) + ".d.str"; + } + TypeScript.changePathToDSTR = changePathToDSTR; + function changePathToTS(modPath) { + return trimModName(stripQuotes(modPath)) + ".ts"; + } + TypeScript.changePathToTS = changePathToTS; + function changePathToDTS(modPath) { + return trimModName(stripQuotes(modPath)) + ".d.ts"; + } + TypeScript.changePathToDTS = changePathToDTS; + function isRelative(path) { + return path.charAt(0) == "."; + } + TypeScript.isRelative = isRelative; + function isRooted(path) { + return path.charAt(0) == "\\" || path.charAt(0) == "/" || (path.indexOf(":\\") != -1) || (path.indexOf(":/") != -1); + } + TypeScript.isRooted = isRooted; + function getRootFilePath(outFname) { + if(outFname == "") { + return outFname; + } else { + var isPath = outFname.indexOf("/") != -1; + return isPath ? filePath(outFname) : ""; + } + } + TypeScript.getRootFilePath = getRootFilePath; + function filePathComponents(fullPath) { + fullPath = switchToForwardSlashes(fullPath); + var components = getPathComponents(fullPath); + return components.slice(0, components.length - 1); + } + TypeScript.filePathComponents = filePathComponents; + function filePath(fullPath) { + var path = filePathComponents(fullPath); + return path.join("/") + "/"; + } + TypeScript.filePath = filePath; + function normalizeURL(url) { + var hostDomainAndPortRegex = /^(https?:\/\/[\-\w\.]+(:\d+)?\/)(.*)$/i; + var matches = hostDomainAndPortRegex.exec(url); + if(matches) { + var hostDomainAndPort = matches[1]; + var actualPath = matches[3]; + return hostDomainAndPort + normalizePath(actualPath); + } + return normalizePath(url); + } + TypeScript.normalizeURL = normalizeURL; + TypeScript.pathNormalizeRegExp = /\//g; + function normalizePath(path) { + path = switchToForwardSlashes(path); + var startedWithSep = path.charAt(0) === "/"; + var parts = this.getPathComponents(path); + for(var i = 0; i < parts.length; i++) { + if(parts[i] === "." || parts[i] === "") { + parts.splice(i, 1); + i--; + } + if(i > 0 && parts[i] === ".." && parts[i - 1] !== "..") { + parts.splice(i - 1, 2); + i -= 2; + } + } + return (startedWithSep ? "/" : "") + parts.join("/"); + } + TypeScript.normalizePath = normalizePath; + function normalizeImportPath(path) { + return normalizePath(path); + } + TypeScript.normalizeImportPath = normalizeImportPath; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var SourceUnit = (function () { + function SourceUnit(path, content) { + this.path = path; + this.content = content; + this.referencedFiles = null; + } + SourceUnit.prototype.getText = function (start, end) { + return this.content.substring(start, end); + }; + SourceUnit.prototype.getLength = function () { + return this.content.length; + }; + return SourceUnit; + })(); + TypeScript.SourceUnit = SourceUnit; + var CompilationEnvironment = (function () { + function CompilationEnvironment(compilationSettings, ioHost) { + this.compilationSettings = compilationSettings; + this.ioHost = ioHost; + this.residentCode = []; + this.code = []; + this.inputOutputMap = []; + } + return CompilationEnvironment; + })(); + TypeScript.CompilationEnvironment = CompilationEnvironment; + var CodeResolver = (function () { + function CodeResolver(environment) { + this.environment = environment; + this.visited = { + }; + } + CodeResolver.prototype.resolveCode = function (referencePath, parentPath, performSearch, resolutionDispatcher) { + var resolvedFile = { + content: null, + path: referencePath + }; + var ioHost = this.environment.ioHost; + var isRelativePath = TypeScript.isRelative(referencePath); + var isRootedPath = isRelativePath ? false : TypeScript.isRooted(referencePath); + var normalizedPath = isRelativePath ? ioHost.resolvePath(parentPath + "/" + referencePath) : (isRootedPath || !parentPath || performSearch ? referencePath : parentPath + "/" + referencePath); + if(!TypeScript.isSTRFile(normalizedPath) && !TypeScript.isTSFile(normalizedPath)) { + normalizedPath += ".ts"; + } + normalizedPath = TypeScript.switchToForwardSlashes(TypeScript.stripQuotes(normalizedPath)); + var absoluteModuleID = this.environment.compilationSettings.useCaseSensitiveFileResolution ? normalizedPath : normalizedPath.toLocaleUpperCase(); + if(!this.visited[absoluteModuleID]) { + if(isRelativePath || isRootedPath || !performSearch) { + try { + TypeScript.CompilerDiagnostics.debugPrint(" Reading code from " + normalizedPath); + try { + resolvedFile.content = ioHost.readFile(normalizedPath); + } catch (err) { + try { + if(TypeScript.isSTRFile(normalizedPath)) { + normalizedPath = TypeScript.changePathToTS(normalizedPath); + } else if(TypeScript.isTSFile(normalizedPath)) { + normalizedPath = TypeScript.changePathToSTR(normalizedPath); + } + TypeScript.CompilerDiagnostics.debugPrint(" Reading code from " + normalizedPath); + resolvedFile.content = ioHost.readFile(normalizedPath); + } catch (err) { + normalizedPath = TypeScript.changePathToDSTR(normalizedPath); + TypeScript.CompilerDiagnostics.debugPrint(" Reading code from " + normalizedPath); + try { + resolvedFile.content = ioHost.readFile(normalizedPath); + } catch (err) { + normalizedPath = TypeScript.changePathToDTS(normalizedPath); + TypeScript.CompilerDiagnostics.debugPrint(" Reading code from " + normalizedPath); + resolvedFile.content = ioHost.readFile(normalizedPath); + } + } + } + TypeScript.CompilerDiagnostics.debugPrint(" Found code at " + normalizedPath); + resolvedFile.path = normalizedPath; + this.visited[absoluteModuleID] = true; + } catch (err) { + TypeScript.CompilerDiagnostics.debugPrint(" Did not find code for " + referencePath); + return false; + } + } else { + resolvedFile = ioHost.findFile(parentPath, normalizedPath); + if(!resolvedFile) { + if(TypeScript.isSTRFile(normalizedPath)) { + normalizedPath = TypeScript.changePathToTS(normalizedPath); + } else if(TypeScript.isTSFile(normalizedPath)) { + normalizedPath = TypeScript.changePathToSTR(normalizedPath); + } + resolvedFile = ioHost.findFile(parentPath, normalizedPath); + } + if(!resolvedFile) { + normalizedPath = TypeScript.changePathToDTS(normalizedPath); + resolvedFile = ioHost.findFile(parentPath, normalizedPath); + if(!resolvedFile) { + normalizedPath = TypeScript.changePathToDSTR(normalizedPath); + resolvedFile = ioHost.findFile(parentPath, normalizedPath); + } + } + if(resolvedFile) { + resolvedFile.path = TypeScript.switchToForwardSlashes(TypeScript.stripQuotes(resolvedFile.path)); + TypeScript.CompilerDiagnostics.debugPrint(referencePath + " resolved to: " + resolvedFile.path); + resolvedFile.content = resolvedFile.content; + this.visited[absoluteModuleID] = true; + } else { + TypeScript.CompilerDiagnostics.debugPrint("Could not find " + referencePath); + } + } + if(resolvedFile && resolvedFile.content != null) { + var rootDir = ioHost.dirName(resolvedFile.path); + var sourceUnit = new SourceUnit(resolvedFile.path, resolvedFile.content); + var preProcessedFileInfo = TypeScript.preProcessFile(sourceUnit, this.environment.compilationSettings); + var resolvedFilePath = ioHost.resolvePath(resolvedFile.path); + sourceUnit.referencedFiles = preProcessedFileInfo.referencedFiles; + for(var i = 0; i < preProcessedFileInfo.referencedFiles.length; i++) { + var fileReference = preProcessedFileInfo.referencedFiles[i]; + var normalizedPath = TypeScript.isRooted(fileReference.path) ? fileReference.path : rootDir + "/" + fileReference.path; + normalizedPath = ioHost.resolvePath(normalizedPath); + if(resolvedFilePath == normalizedPath) { + resolutionDispatcher.postResolutionError(normalizedPath, fileReference.startLine, fileReference.startCol, "Incorrect reference: File contains reference to itself."); + continue; + } + var resolutionResult = this.resolveCode(fileReference.path, rootDir, false, resolutionDispatcher); + if(!resolutionResult) { + resolutionDispatcher.postResolutionError(resolvedFilePath, fileReference.startLine, fileReference.startCol, "Incorrect reference: referenced file: \"" + fileReference.path + "\" cannot be resolved."); + } + } + for(var i = 0; i < preProcessedFileInfo.importedFiles.length; i++) { + var fileImport = preProcessedFileInfo.importedFiles[i]; + var resolutionResult = this.resolveCode(fileImport.path, rootDir, true, resolutionDispatcher); + if(!resolutionResult) { + resolutionDispatcher.postResolutionError(resolvedFilePath, fileImport.startLine, fileImport.startCol, "Incorrect reference: imported file: \"" + fileImport.path + "\" cannot be resolved."); + } + } + resolutionDispatcher.postResolution(sourceUnit.path, sourceUnit); + } + } + return true; + }; + return CodeResolver; + })(); + TypeScript.CodeResolver = CodeResolver; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var StyleSettings = (function () { + function StyleSettings() { + this.bitwise = false; + this.blockInCompoundStmt = false; + this.eqeqeq = false; + this.forin = false; + this.emptyBlocks = true; + this.newMustBeUsed = false; + this.requireSemi = false; + this.assignmentInCond = false; + this.eqnull = false; + this.evalOK = true; + this.innerScopeDeclEscape = true; + this.funcInLoop = true; + this.reDeclareLocal = true; + this.literalSubscript = true; + this.implicitAny = false; + } + StyleSettings.prototype.setOption = function (opt, val) { + var optExists = this[opt]; + if(optExists !== undefined) { + this[opt] = val; + return true; + } else { + return false; + } + }; + StyleSettings.prototype.parseOptions = function (str) { + var opts = str.split(";"); + for(var i = 0, len = opts.length; i < len; i++) { + var opt = opts[i]; + var val = true; + var colonIndex = opt.lastIndexOf(":"); + if(colonIndex >= 0) { + var valStr = opt.substring(colonIndex + 1); + opt = opt.substring(0, colonIndex); + if(valStr == "off") { + val = false; + } + } + if(!this.setOption(opt, val)) { + return false; + } + } + return true; + }; + return StyleSettings; + })(); + TypeScript.StyleSettings = StyleSettings; + var CompilationSettings = (function () { + function CompilationSettings() { + this.styleSettings = new StyleSettings(); + this.propagateConstants = false; + this.minWhitespace = false; + this.parseOnly = false; + this.errorRecovery = false; + this.emitComments = false; + this.watch = false; + this.exec = false; + this.resolve = true; + this.controlFlow = false; + this.printControlFlow = false; + this.controlFlowUseDef = false; + this.errorOnWith = true; + this.preprocess = true; + this.canCallDefinitionSignature = false; + this.inferPropertiesFromThisAssignment = false; + this.useDefaultLib = true; + this.codeGenTarget = TypeScript.CodeGenTarget.ES3; + this.moduleGenTarget = TypeScript.ModuleGenTarget.Synchronous; + this.outputOption = ""; + this.mapSourceFiles = false; + this.emitFullSourceMapPath = false; + this.generateDeclarationFiles = false; + this.useCaseSensitiveFileResolution = false; + } + CompilationSettings.prototype.setStyleOptions = function (str) { + this.styleSettings.parseOptions(str); + }; + return CompilationSettings; + })(); + TypeScript.CompilationSettings = CompilationSettings; + function getFileReferenceFromReferencePath(comment) { + var referencesRegEx = /^(\/\/\/\s*/gim; + var match = referencesRegEx.exec(comment); + if(match) { + var path = TypeScript.normalizePath(match[3]); + var adjustedPath = TypeScript.normalizePath(path); + var isResident = match.length >= 7 && match[6] == "true"; + if(isResident) { + TypeScript.CompilerDiagnostics.debugPrint(path + " is resident"); + } + return { + minChar: 0, + limChar: 0, + startLine: 0, + startCol: 0, + path: TypeScript.switchToForwardSlashes(adjustedPath), + isResident: isResident + }; + } else { + return null; + } + } + function getAdditionalDependencyPath(comment) { + var amdDependencyRegEx = /^(\/\/\/\s*/gim; + var match = amdDependencyRegEx.exec(comment); + if(match) { + var path = match[3]; + return path; + } else { + return null; + } + } + TypeScript.getAdditionalDependencyPath = getAdditionalDependencyPath; + function getImplicitImport(comment) { + var implicitImportRegEx = /^(\/\/\/\s*/gim; + var match = implicitImportRegEx.exec(comment); + if(match) { + return true; + } + return false; + } + TypeScript.getImplicitImport = getImplicitImport; + function getStyleSettings(comment, styleSettings) { + var styleRegEx = /^(\/\/\/\s*/gim; + var settings = styleRegEx.exec(comment); + if(settings) { + var settingsRegEx = /^([a-zA-Z]+=['"]on['|"])/gim; + settings = settingsRegEx.exec(settings[2]); + if(settings) { + for(var i = 0; i < settings.length; i++) { + var setting = (settings[i]).split("="); + var on = "\"on\""; + switch(setting[0]) { + case "blockInCompoundStmt": + styleSettings.blockInCompoundStmt = setting[1] == on; + break; + case "eqeqeq": + styleSettings.eqeqeq = setting[1] == on; + break; + case "forin": + styleSettings.forin = setting[1] == on; + break; + case "emptyBlocks": + styleSettings.emptyBlocks = setting[1] == on; + break; + case "newMustBeUsed": + styleSettings.newMustBeUsed = setting[1] == on; + break; + case "requireSemi": + styleSettings.requireSemi = setting[1] == on; + break; + case "assignmentInCond": + styleSettings.assignmentInCond = setting[1] == on; + break; + case "eqnull": + styleSettings.eqnull = setting[1] == on; + break; + case "evalOK": + styleSettings.evalOK = setting[1] == on; + break; + case "innerScopeDeclEscape": + styleSettings.innerScopeDeclEscape = setting[1] == on; + break; + case "funcInLoop": + styleSettings.funcInLoop = setting[1] == on; + break; + case "reDeclareLocal": + styleSettings.reDeclareLocal = setting[1] == on; + break; + case "literalSubscript": + styleSettings.literalSubscript = setting[1] == on; + break; + case "implicitAny": + styleSettings.implicitAny = setting[1] == on; + break; + } + } + } + } + } + TypeScript.getStyleSettings = getStyleSettings; + function getReferencedFiles(sourceText) { + var preProcessInfo = preProcessFile(sourceText, null, false); + return preProcessInfo.referencedFiles; + } + TypeScript.getReferencedFiles = getReferencedFiles; + function preProcessFile(sourceText, options, readImportFiles) { + if (typeof options === "undefined") { options = new CompilationSettings(); } + if (typeof readImportFiles === "undefined") { readImportFiles = true; } + var scanner = new TypeScript.Scanner(); + scanner.resetComments(); + scanner.setSourceText(sourceText, TypeScript.LexMode.File); + var tok = scanner.scan(); + var comments = []; + var comment = null; + var leftCurlies = []; + var settings = options; + var referencedFiles = []; + var importedFiles = []; + var isLibFile = false; + while(tok.tokenId != TypeScript.TokenID.EndOfFile) { + if(readImportFiles && tok.tokenId == TypeScript.TokenID.Import) { + tok = scanner.scan(); + if(tok.tokenId == TypeScript.TokenID.Identifier || TypeScript.convertTokToID(tok, false)) { + tok = scanner.scan(); + if(tok.tokenId == TypeScript.TokenID.Equals) { + tok = scanner.scan(); + if(tok.tokenId == TypeScript.TokenID.Module) { + tok = scanner.scan(); + if(tok.tokenId == TypeScript.TokenID.OpenParen) { + tok = scanner.scan(); + if(tok.tokenId == TypeScript.TokenID.StringLiteral) { + var ref = { + minChar: scanner.startPos, + limChar: scanner.pos, + startLine: scanner.line, + startCol: scanner.col, + path: TypeScript.stripQuotes(TypeScript.switchToForwardSlashes(tok.getText())), + isResident: false + }; + importedFiles.push(ref); + } + } + } + } + } + } + if(tok.tokenId == TypeScript.TokenID.OpenBrace) { + leftCurlies.push(tok); + } + if(tok.tokenId == TypeScript.TokenID.CloseBrace) { + leftCurlies.pop(); + } + tok = scanner.scan(); + } + comments = scanner.getComments(); + for(var iComment = 0; iComment < comments.length; iComment++) { + comment = comments[iComment]; + if(!comment.isBlock) { + var referencedCode = getFileReferenceFromReferencePath(comment.getText()); + if(referencedCode) { + referencedCode.minChar = comment.startPos; + referencedCode.limChar = referencedCode.minChar + comment.value.length; + var result = { + line: -1, + col: -1 + }; + TypeScript.getSourceLineColFromMap(result, comment.startPos, scanner.lineMap); + if(result.col >= 0) { + result.col++; + } + referencedCode.startLine = result.line; + referencedCode.startCol = result.col; + referencedFiles.push(referencedCode); + } + if(settings) { + getStyleSettings(comment.getText(), settings.styleSettings); + var isNoLibRegex = /^(\/\/\/\s*/gim; + var isNoLibMatch = isNoLibRegex.exec(comment.getText()); + if(isNoLibMatch) { + isLibFile = (isNoLibMatch[3] == "true"); + } + } + } + } + return { + settings: settings, + referencedFiles: referencedFiles, + importedFiles: importedFiles, + isLibFile: isLibFile + }; + } + TypeScript.preProcessFile = preProcessFile; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var IncrementalParser = (function () { + function IncrementalParser(logger) { + this.logger = logger; + this.astLogger = new TypeScript.AstLogger(this.logger); + } + IncrementalParser.prototype.getEnclosingScopeContextIfSingleScopeEdit = function (previousScript, scriptId, newSourceText, editRange) { + this.logger.log("checkEditsInsideSingleScope(\"" + scriptId + "\")"); + if(editRange === null) { + throw new Error("editRange should be valid"); + } + if(editRange.isUnknown()) { + this.logger.log(" Bailing out because edit range is unknown"); + return null; + } + var scope1 = TypeScript.findEnclosingScopeAt(this.logger, previousScript, newSourceText, editRange.minChar, false); + var scope2 = TypeScript.findEnclosingScopeAt(this.logger, previousScript, newSourceText, editRange.limChar, false); + if(scope1 == null || scope2 == null) { + this.logger.log(" Bailing out because containing scopes cannot be determined"); + return null; + } + if(scope1.scopeStartAST !== scope2.scopeStartAST) { + this.logger.log(" Bailing out because edit overlaps 2 disctint scopes"); + return null; + } + var newScopeLength = scope1.scopeStartAST.limChar - scope1.scopeStartAST.minChar + editRange.delta; + if(newScopeLength <= 0) { + this.logger.log(" Bailing out because scope has been entirely removed from new source text"); + return null; + } + return scope1; + }; + IncrementalParser.prototype.attemptIncrementalUpdateUnit = function (previousScript, scriptId, newSourceText, editRange) { + this.logger.log("attemptIncrementalUpdateUnit(\"" + scriptId + "\")"); + if(editRange === null) { + throw new Error("editRange should be valid"); + } + var scope1 = this.getEnclosingScopeContextIfSingleScopeEdit(previousScript, scriptId, newSourceText, editRange); + if(scope1 === null) { + return null; + } + var newScopeLength = scope1.scopeStartAST.limChar - scope1.scopeStartAST.minChar + editRange.delta; + if(newScopeLength >= newSourceText.getLength() / 2) { + this.logger.log(" Bailing out because range of scope to reparse (" + newScopeLength + " characters) is greater than half the size of the source text"); + return null; + } + var parseErrors = []; + var errorCapture = function (minChar, charLen, message, unitIndex) { + parseErrors.push(new TypeScript.ErrorEntry(unitIndex, minChar, minChar + charLen, message)); + }; + var quickParseResult = TypeScript.quickParse(this.logger, scope1.scopeStartAST, newSourceText, scope1.scopeStartAST.minChar, scope1.scopeStartAST.minChar + newScopeLength, errorCapture); + if(quickParseResult.endLexState != TypeScript.LexState.Start) { + this.logger.log(" Bailing out because scope contains unterminated comment"); + return null; + } + var scriptFragment = quickParseResult.Script; + if(scriptFragment.vars.members.length !== 0) { + this.logger.log(" Bailing out because new source text defines variables"); + return null; + } + if(scriptFragment.bod.members.length !== 1) { + this.logger.log(" Bailing out because new source text defines more than one scope (or none)"); + return null; + } + var oldScope = scope1.scopeStartAST; + var newScope = scriptFragment.bod.members[0]; + if(oldScope.nodeType != newScope.nodeType) { + this.logger.log(" Bailing out because new source text does not define the same scope type as the existing scope"); + return null; + } + if(!(oldScope).leftCurlyCount || !(oldScope).rightCurlyCount) { + this.logger.log(" Bailing out because sopce doesn't have left/right curly count"); + return null; + } + if((oldScope).leftCurlyCount !== (newScope).leftCurlyCount) { + this.logger.log(" Bailing out because new source text contains more (or fewer) left curly braces"); + return null; + } + if((oldScope).rightCurlyCount !== (newScope).rightCurlyCount) { + this.logger.log(" Bailing out because new source text contains more (or fewer) right curly braces"); + return null; + } + if(newScope.minChar !== 0) { + this.logger.log(" Bailing out because new function declaration does not start at position 0"); + return null; + } + if(newScope.limChar !== newScopeLength) { + this.logger.log(" Bailing out because new function declaration does not end at the new end position"); + return null; + } + return TypeScript.UpdateUnitResult.singleScopeEdits(previousScript, scriptFragment, oldScope, newScope, editRange, parseErrors); + }; + IncrementalParser.prototype.mergeTrees = function (updateResult) { + var _this = this; + TypeScript.timeFunction(this.logger, "mergeTrees()", function () { + var editRange = new TypeScript.ScriptEditRange(updateResult.scope1.minChar, updateResult.scope1.limChar, updateResult.editRange.delta); + _this.applyDeltaPosition(updateResult.script1, editRange.limChar, editRange.delta); + _this.applyDeltaPosition(updateResult.script2, 0, editRange.minChar); + _this.mergeLocationInfo(updateResult.script1, updateResult.script2, editRange); + _this.replaceAST(updateResult.script1, updateResult.scope1, updateResult.scope2); + }); + }; + IncrementalParser.prototype.replaceAST = function (script, oldAst, newAst) { + var _this = this; + var pre = function (cur, parent, walker) { + if(cur === oldAst) { + newAst.preComments = cur.preComments; + newAst.postComments = cur.postComments; + _this.logger.log("replaced old AST node with new one in script AST"); + walker.options.stopWalk(); + return newAst; + } + if(TypeScript.isValidAstNode(cur)) { + if(cur.limChar < oldAst.minChar || cur.minChar > oldAst.limChar) { + walker.options.goChildren = false; + } + } + return cur; + }; + TypeScript.getAstWalkerFactory().walk(script, pre); + }; + IncrementalParser.prototype.mergeLocationInfo = function (script, partial, editRange) { + var lineMap1 = script.locationInfo.lineMap; + var lineMap2 = partial.locationInfo.lineMap; + if(this.logger.information()) { + this.logger.log("lineMap1 (before):"); + this.astLogger.logLinemap(lineMap1); + this.logger.log("lineMap2 (quick parse):"); + this.astLogger.logLinemap(lineMap2); + this.logger.log("EditRange=" + editRange); + } + var i1 = 2; + var i2 = 2; + var len1 = lineMap1.length; + var len2 = lineMap2.length; + while(i1 < len1) { + if(lineMap1[i1] <= editRange.minChar) { + i1++; + } else if(lineMap1[i1] >= editRange.limChar) { + lineMap1[i1] += editRange.delta; + i1++; + } else { + if(i2 < len2) { + lineMap1.splice(i1, 0, lineMap2[i2] + editRange.minChar); + i1++; + len1++; + i2++; + } else { + lineMap1.splice(i1, 1); + len1--; + } + } + } + if(i2 < len2) { + if(lineMap1[len1 - 1] >= (lineMap2[i2] + editRange.minChar)) { + i1 = 2; + while(i1 < len1 && i2 < len2) { + if(lineMap1[i1] < (lineMap2[i2] + editRange.minChar)) { + i1++; + } else { + lineMap1.splice(i1, 0, lineMap2[i2] + editRange.minChar); + i1++; + len1++; + i2++; + } + } + } + for(; i2 < len2; i2++) { + lineMap1.push(lineMap2[i2] + editRange.minChar); + } + } + if(this.logger.information()) { + this.logger.log("lineMap1 (after merge):"); + this.astLogger.logLinemap(lineMap1); + } + }; + IncrementalParser.prototype.applyDeltaPosition = function (ast, start, delta) { + var applyDelta = function (ast) { + if(ast.minChar !== -1 && ast.minChar >= start) { + ast.minChar += delta; + } + if(ast.limChar !== -1 && ast.limChar >= start) { + ast.limChar += delta; + } + }; + var applyDeltaToComments = function (comments) { + if(comments && comments.length > 0) { + for(var i = 0; i < comments.length; i++) { + applyDelta(comments[i]); + } + } + }; + var pre = function (cur, parent, walker) { + if(cur.limChar !== -1 && cur.limChar < start) { + walker.options.goChildren = false; + } + applyDelta(cur); + applyDeltaToComments(cur.preComments); + applyDeltaToComments(cur.postComments); + return cur; + }; + TypeScript.getAstWalkerFactory().walk(ast, pre); + }; + return IncrementalParser; + })(); + TypeScript.IncrementalParser = IncrementalParser; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + var DeclFileWriter = (function () { + function DeclFileWriter(declFile) { + this.declFile = declFile; + this.onNewLine = true; + } + DeclFileWriter.prototype.Write = function (s) { + this.declFile.Write(s); + this.onNewLine = false; + }; + DeclFileWriter.prototype.WriteLine = function (s) { + this.declFile.WriteLine(s); + this.onNewLine = true; + }; + DeclFileWriter.prototype.Close = function () { + this.declFile.Close(); + }; + return DeclFileWriter; + })(); + TypeScript.DeclFileWriter = DeclFileWriter; + var DeclarationEmitter = (function () { + function DeclarationEmitter(checker, emitOptions, errorReporter) { + this.checker = checker; + this.emitOptions = emitOptions; + this.errorReporter = errorReporter; + this.declFile = null; + this.indenter = new TypeScript.Indenter(); + this.declarationContainerStack = []; + this.isDottedModuleName = []; + this.ignoreCallbackAst = null; + this.singleDeclFile = null; + this.varListCount = 0; + } + DeclarationEmitter.prototype.getAstDeclarationContainer = function () { + return this.declarationContainerStack[this.declarationContainerStack.length - 1]; + }; + DeclarationEmitter.prototype.emitDottedModuleName = function () { + return (this.isDottedModuleName.length == 0) ? false : this.isDottedModuleName[this.isDottedModuleName.length - 1]; + }; + DeclarationEmitter.prototype.setDeclarationFile = function (file) { + this.declFile = new DeclFileWriter(file); + }; + DeclarationEmitter.prototype.Close = function () { + try { + this.declFile.Close(); + } catch (ex) { + this.errorReporter.emitterError(null, ex.message); + } + }; + DeclarationEmitter.prototype.emitDeclarations = function (script) { + TypeScript.AstWalkerWithDetailCallback.walk(script, this); + }; + DeclarationEmitter.prototype.getIndentString = function (declIndent) { + if (typeof declIndent === "undefined") { declIndent = false; } + if(this.emitOptions.minWhitespace) { + return ""; + } else { + return this.indenter.getIndent(); + } + }; + DeclarationEmitter.prototype.emitIndent = function () { + this.declFile.Write(this.getIndentString()); + }; + DeclarationEmitter.prototype.canEmitSignature = function (declFlags, canEmitGlobalAmbientDecl, useDeclarationContainerTop) { + if (typeof canEmitGlobalAmbientDecl === "undefined") { canEmitGlobalAmbientDecl = true; } + if (typeof useDeclarationContainerTop === "undefined") { useDeclarationContainerTop = true; } + var container; + if(useDeclarationContainerTop) { + container = this.getAstDeclarationContainer(); + } else { + container = this.declarationContainerStack[this.declarationContainerStack.length - 2]; + } + if(container.nodeType == TypeScript.NodeType.ModuleDeclaration && !TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Exported)) { + return false; + } + if(!canEmitGlobalAmbientDecl && container.nodeType == TypeScript.NodeType.Script && TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Ambient)) { + return false; + } + return true; + }; + DeclarationEmitter.prototype.canEmitPrePostAstSignature = function (declFlags, astWithPrePostCallback, preCallback) { + if(this.ignoreCallbackAst) { + TypeScript.CompilerDiagnostics.assert(this.ignoreCallbackAst != astWithPrePostCallback, "Ignore Callback AST mismatch"); + this.ignoreCallbackAst = null; + return false; + } else if(preCallback && !this.canEmitSignature(declFlags, true, preCallback)) { + this.ignoreCallbackAst = astWithPrePostCallback; + return false; + } + return true; + }; + DeclarationEmitter.prototype.getDeclFlagsString = function (declFlags, typeString) { + var result = this.getIndentString(); + var accessorString = ""; + if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.GetAccessor)) { + accessorString = "get "; + } else if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.SetAccessor)) { + accessorString = "set "; + } + var container = this.getAstDeclarationContainer(); + if(container.nodeType == TypeScript.NodeType.ModuleDeclaration && TypeScript.hasFlag((container).modFlags, TypeScript.ModuleFlags.IsWholeFile) && TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Exported)) { + result += "export "; + } + if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.LocalStatic) || TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Static)) { + if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Private)) { + result += "private "; + } + result += "static " + accessorString; + } else { + if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Private)) { + result += "private " + accessorString; + } else if(TypeScript.hasFlag(declFlags, TypeScript.DeclFlags.Public)) { + result += "public " + accessorString; + } else { + if(accessorString == "") { + result += typeString + " "; + } else { + result += accessorString; + } + } + } + return result; + }; + DeclarationEmitter.prototype.emitDeclFlags = function (declFlags, typeString) { + this.declFile.Write(this.getDeclFlagsString(declFlags, typeString)); + }; + DeclarationEmitter.prototype.canEmitTypeAnnotationSignature = function (declFlag) { + if (typeof declFlag === "undefined") { declFlag = TypeScript.DeclFlags.None; } + return !TypeScript.hasFlag(declFlag, TypeScript.DeclFlags.Private); + }; + DeclarationEmitter.prototype.pushDeclarationContainer = function (ast) { + this.declarationContainerStack.push(ast); + }; + DeclarationEmitter.prototype.popDeclarationContainer = function (ast) { + TypeScript.CompilerDiagnostics.assert(ast != this.getAstDeclarationContainer(), 'Declaration container mismatch'); + this.declarationContainerStack.pop(); + }; + DeclarationEmitter.prototype.emitTypeNamesMember = function (memberName, emitIndent) { + if (typeof emitIndent === "undefined") { emitIndent = false; } + if(memberName.prefix == "{ ") { + if(emitIndent) { + this.emitIndent(); + } + this.declFile.WriteLine("{"); + this.indenter.increaseIndent(); + emitIndent = true; + } else if(memberName.prefix != "") { + if(emitIndent) { + this.emitIndent(); + } + this.declFile.Write(memberName.prefix); + emitIndent = false; + } + if(memberName.isString()) { + if(emitIndent) { + this.emitIndent(); + } + this.declFile.Write((memberName).text); + } else { + var ar = memberName; + for(var index = 0; index < ar.entries.length; index++) { + this.emitTypeNamesMember(ar.entries[index], emitIndent); + if(ar.delim == "; ") { + this.declFile.WriteLine(";"); + } + } + } + if(memberName.suffix == "}") { + this.indenter.decreaseIndent(); + this.emitIndent(); + this.declFile.Write(memberName.suffix); + } else { + this.declFile.Write(memberName.suffix); + } + }; + DeclarationEmitter.prototype.emitTypeSignature = function (type) { + var containingScope = null; + var declarationContainerAst = this.getAstDeclarationContainer(); + switch(declarationContainerAst.nodeType) { + case TypeScript.NodeType.ModuleDeclaration: + case TypeScript.NodeType.InterfaceDeclaration: + case TypeScript.NodeType.FuncDecl: + if(declarationContainerAst.type) { + containingScope = declarationContainerAst.type.containedScope; + } + break; + case TypeScript.NodeType.Script: + var script = declarationContainerAst; + if(script.bod) { + containingScope = script.bod.enclosingScope; + } + break; + case TypeScript.NodeType.ClassDeclaration: + if(declarationContainerAst.type) { + containingScope = declarationContainerAst.type.instanceType.containedScope; + } + break; + default: + TypeScript.CompilerDiagnostics.debugPrint("Unknown containing scope"); + } + var typeNameMembers = type.getScopedTypeNameEx(containingScope); + this.emitTypeNamesMember(typeNameMembers); + }; + DeclarationEmitter.prototype.emitComment = function (comment) { + var text = comment.getText(); + if(this.declFile.onNewLine) { + this.emitIndent(); + } else if(!comment.isBlockComment) { + this.declFile.WriteLine(""); + this.emitIndent(); + } + this.declFile.Write(text[0]); + for(var i = 1; i < text.length; i++) { + this.declFile.WriteLine(""); + this.emitIndent(); + this.declFile.Write(text[i]); + } + if(comment.endsLine || !comment.isBlockComment) { + this.declFile.WriteLine(""); + } else { + this.declFile.Write(" "); + } + }; + DeclarationEmitter.prototype.emitDeclarationComments = function (astOrSymbol, endLine) { + if (typeof endLine === "undefined") { endLine = true; } + if(!this.emitOptions.emitComments) { + return; + } + var declComments = astOrSymbol.getDocComments(); + if(declComments.length > 0) { + for(var i = 0; i < declComments.length; i++) { + this.emitComment(declComments[i]); + } + if(endLine) { + if(!this.declFile.onNewLine) { + this.declFile.WriteLine(""); + } + } else { + if(this.declFile.onNewLine) { + this.emitIndent(); + } + } + } + }; + DeclarationEmitter.prototype.VarDeclCallback = function (pre, varDecl) { + if(pre && this.canEmitSignature(TypeScript.ToDeclFlags(varDecl.varFlags), false)) { + var interfaceMember = (this.getAstDeclarationContainer().nodeType == TypeScript.NodeType.InterfaceDeclaration); + this.emitDeclarationComments(varDecl); + if(!interfaceMember) { + if(this.varListCount >= 0) { + this.emitDeclFlags(TypeScript.ToDeclFlags(varDecl.varFlags), "var"); + this.varListCount = -this.varListCount; + } + this.declFile.Write(varDecl.id.text); + } else { + this.emitIndent(); + this.declFile.Write(varDecl.id.text); + if(TypeScript.hasFlag(varDecl.id.flags, TypeScript.ASTFlags.OptionalName)) { + this.declFile.Write("?"); + } + } + var type = null; + if(varDecl.typeExpr && varDecl.typeExpr.type) { + type = varDecl.typeExpr.type; + } else if(varDecl.sym) { + type = (varDecl.sym).getType(); + if(type == this.checker.anyType) { + type = null; + } + } + if(type && this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(varDecl.varFlags))) { + this.declFile.Write(": "); + this.emitTypeSignature(type); + } + if(this.varListCount > 0) { + this.varListCount--; + } else if(this.varListCount < 0) { + this.varListCount++; + } + if(this.varListCount < 0) { + this.declFile.Write(", "); + } else { + this.declFile.WriteLine(";"); + } + } + return false; + }; + DeclarationEmitter.prototype.BlockCallback = function (pre, block) { + if(!block.isStatementBlock) { + if(pre) { + this.varListCount = block.statements.members.length; + } else { + this.varListCount = 0; + } + return true; + } + return false; + }; + DeclarationEmitter.prototype.emitArgDecl = function (argDecl, funcDecl) { + this.emitDeclarationComments(argDecl, false); + this.declFile.Write(argDecl.id.text); + if(argDecl.isOptionalArg()) { + this.declFile.Write("?"); + } + if((argDecl.typeExpr || argDecl.type != this.checker.anyType) && this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(funcDecl.fncFlags))) { + this.declFile.Write(": "); + this.emitTypeSignature(argDecl.type); + } + }; + DeclarationEmitter.prototype.FuncDeclCallback = function (pre, funcDecl) { + if(!pre) { + return false; + } + if(funcDecl.isAccessor()) { + return this.emitPropertyAccessorSignature(funcDecl); + } + var isInterfaceMember = (this.getAstDeclarationContainer().nodeType == TypeScript.NodeType.InterfaceDeclaration); + if(funcDecl.bod) { + if(funcDecl.isConstructor) { + if(funcDecl.type.construct && funcDecl.type.construct.signatures.length > 1) { + return false; + } + } else { + if(funcDecl.type.call && funcDecl.type.call.signatures.length > 1) { + return false; + } + } + } else if(!isInterfaceMember && TypeScript.hasFlag(funcDecl.fncFlags, TypeScript.FncFlags.Private) && funcDecl.type.call && funcDecl.type.call.signatures.length > 1) { + var signatures = funcDecl.type.call.signatures; + var firstSignature = signatures[0].declAST; + if(firstSignature.bod) { + firstSignature = signatures[1].declAST; + } + if(firstSignature != funcDecl) { + return false; + } + } + if(!this.canEmitSignature(TypeScript.ToDeclFlags(funcDecl.fncFlags), false)) { + return false; + } + this.emitDeclarationComments(funcDecl); + if(funcDecl.isConstructor) { + this.emitIndent(); + this.declFile.Write("constructor"); + } else { + var id = funcDecl.getNameText(); + if(!isInterfaceMember) { + this.emitDeclFlags(TypeScript.ToDeclFlags(funcDecl.fncFlags), "function"); + if(id != "__missing" || !funcDecl.name || !funcDecl.name.isMissing()) { + this.declFile.Write(id); + } else if(funcDecl.isConstructMember()) { + this.declFile.Write("new"); + } + } else { + this.emitIndent(); + if(funcDecl.isConstructMember()) { + this.declFile.Write("new"); + } else if(!funcDecl.isCallMember() && !funcDecl.isIndexerMember()) { + this.declFile.Write(id); + if(TypeScript.hasFlag(funcDecl.name.flags, TypeScript.ASTFlags.OptionalName)) { + this.declFile.Write("? "); + } + } + } + } + if(!funcDecl.isIndexerMember()) { + this.declFile.Write("("); + } else { + this.declFile.Write("["); + } + this.indenter.increaseIndent(); + if(funcDecl.arguments) { + var argsLen = funcDecl.arguments.members.length; + if(funcDecl.variableArgList) { + argsLen--; + } + for(var i = 0; i < argsLen; i++) { + var argDecl = funcDecl.arguments.members[i]; + this.emitArgDecl(argDecl, funcDecl); + if(i < (argsLen - 1)) { + this.declFile.Write(", "); + } + } + } + if(funcDecl.variableArgList) { + var lastArg = funcDecl.arguments.members[funcDecl.arguments.members.length - 1]; + if(funcDecl.arguments.members.length > 1) { + this.declFile.Write(", ..."); + } else { + this.declFile.Write("..."); + } + this.emitArgDecl(lastArg, funcDecl); + } + this.indenter.decreaseIndent(); + if(!funcDecl.isIndexerMember()) { + this.declFile.Write(")"); + } else { + this.declFile.Write("]"); + } + if(!funcDecl.isConstructor && (funcDecl.returnTypeAnnotation || funcDecl.signature.returnType.type != this.checker.anyType) && this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(funcDecl.fncFlags))) { + this.declFile.Write(": "); + this.emitTypeSignature(funcDecl.signature.returnType.type); + } + this.declFile.WriteLine(";"); + return false; + }; + DeclarationEmitter.prototype.emitBaseList = function (bases, qual) { + if(bases && (bases.members.length > 0)) { + this.declFile.Write(" " + qual + " "); + var basesLen = bases.members.length; + for(var i = 0; i < basesLen; i++) { + var baseExpr = bases.members[i]; + var baseSymbol = baseExpr.type.symbol; + var baseType = baseExpr.type; + if(i > 0) { + this.declFile.Write(", "); + } + this.emitTypeSignature(baseType); + } + } + }; + DeclarationEmitter.prototype.emitPropertyAccessorSignature = function (funcDecl) { + var accessorSymbol = funcDecl.accessorSymbol; + if(accessorSymbol.getter && accessorSymbol.getter.declAST != funcDecl) { + return false; + } + this.emitDeclarationComments(accessorSymbol); + this.emitDeclFlags(TypeScript.ToDeclFlags(accessorSymbol.flags), "var"); + this.declFile.Write(funcDecl.name.text); + var propertyType = accessorSymbol.getType(); + if(this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(accessorSymbol.flags))) { + this.declFile.Write(" : "); + this.emitTypeSignature(propertyType); + } + this.declFile.WriteLine(";"); + return false; + }; + DeclarationEmitter.prototype.emitClassMembersFromConstructorDefinition = function (funcDecl) { + if(funcDecl.arguments) { + var argsLen = funcDecl.arguments.members.length; + if(funcDecl.variableArgList) { + argsLen--; + } + for(var i = 0; i < argsLen; i++) { + var argDecl = funcDecl.arguments.members[i]; + if(TypeScript.hasFlag(argDecl.varFlags, TypeScript.VarFlags.Property)) { + this.emitDeclarationComments(argDecl); + this.emitDeclFlags(TypeScript.ToDeclFlags(argDecl.varFlags), "var"); + this.declFile.Write(argDecl.id.text); + if(argDecl.typeExpr && this.canEmitTypeAnnotationSignature(TypeScript.ToDeclFlags(argDecl.varFlags))) { + this.declFile.Write(": "); + this.emitTypeSignature(argDecl.type); + } + this.declFile.WriteLine(";"); + } + } + } + }; + DeclarationEmitter.prototype.ClassDeclarationCallback = function (pre, classDecl) { + if(!this.canEmitPrePostAstSignature(TypeScript.ToDeclFlags(classDecl.varFlags), classDecl, pre)) { + return false; + } + if(pre) { + var className = classDecl.name.text; + this.emitDeclarationComments(classDecl); + this.emitDeclFlags(TypeScript.ToDeclFlags(classDecl.varFlags), "class"); + this.declFile.Write(className); + this.emitBaseList(classDecl.extendsList, "extends"); + this.emitBaseList(classDecl.implementsList, "implements"); + this.declFile.WriteLine(" {"); + this.pushDeclarationContainer(classDecl); + this.indenter.increaseIndent(); + if(classDecl.constructorDecl) { + this.emitClassMembersFromConstructorDefinition(classDecl.constructorDecl); + } + } else { + this.indenter.decreaseIndent(); + this.popDeclarationContainer(classDecl); + this.emitIndent(); + this.declFile.WriteLine("}"); + } + return true; + }; + DeclarationEmitter.prototype.InterfaceDeclarationCallback = function (pre, interfaceDecl) { + if(!this.canEmitPrePostAstSignature(TypeScript.ToDeclFlags(interfaceDecl.varFlags), interfaceDecl, pre)) { + return false; + } + if(pre) { + var interfaceName = interfaceDecl.name.text; + this.emitDeclarationComments(interfaceDecl); + this.emitDeclFlags(TypeScript.ToDeclFlags(interfaceDecl.varFlags), "interface"); + this.declFile.Write(interfaceName); + this.emitBaseList(interfaceDecl.extendsList, "extends"); + this.declFile.WriteLine(" {"); + this.indenter.increaseIndent(); + this.pushDeclarationContainer(interfaceDecl); + } else { + this.indenter.decreaseIndent(); + this.popDeclarationContainer(interfaceDecl); + this.emitIndent(); + this.declFile.WriteLine("}"); + } + return true; + }; + DeclarationEmitter.prototype.ImportDeclarationCallback = function (pre, importDecl) { + if(pre) { + if((this.declarationContainerStack[0]).isExternallyVisibleSymbol(importDecl.id.sym)) { + this.emitDeclarationComments(importDecl); + this.emitIndent(); + this.declFile.Write("import "); + this.declFile.Write(importDecl.id.text + " = "); + if(importDecl.isDynamicImport) { + this.declFile.WriteLine("module (" + importDecl.getAliasName() + ");"); + } else { + this.declFile.WriteLine(importDecl.getAliasName() + ";"); + } + } + } + return false; + }; + DeclarationEmitter.prototype.emitEnumSignature = function (moduleDecl) { + if(!this.canEmitSignature(TypeScript.ToDeclFlags(moduleDecl.modFlags))) { + return false; + } + this.emitDeclarationComments(moduleDecl); + this.emitDeclFlags(TypeScript.ToDeclFlags(moduleDecl.modFlags), "enum"); + this.declFile.WriteLine(moduleDecl.name.text + " {"); + this.indenter.increaseIndent(); + var membersLen = moduleDecl.members.members.length; + for(var j = 1; j < membersLen; j++) { + var memberDecl = moduleDecl.members.members[j]; + if(memberDecl.nodeType == TypeScript.NodeType.VarDecl) { + this.emitDeclarationComments(memberDecl); + this.emitIndent(); + this.declFile.WriteLine((memberDecl).id.text + ","); + } else { + TypeScript.CompilerDiagnostics.assert(memberDecl.nodeType != TypeScript.NodeType.Asg, "We want to catch this"); + } + } + this.indenter.decreaseIndent(); + this.emitIndent(); + this.declFile.WriteLine("}"); + return false; + }; + DeclarationEmitter.prototype.ModuleDeclarationCallback = function (pre, moduleDecl) { + if(TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsWholeFile)) { + if(TypeScript.hasFlag(moduleDecl.modFlags, TypeScript.ModuleFlags.IsDynamic)) { + if(pre) { + if(!this.emitOptions.outputMany) { + this.singleDeclFile = this.declFile; + TypeScript.CompilerDiagnostics.assert(this.indenter.indentAmt == 0, "Indent has to be 0 when outputing new file"); + var declareFileName = this.emitOptions.mapOutputFileName(TypeScript.stripQuotes(moduleDecl.name.sym.name), TypeScript.TypeScriptCompiler.mapToDTSFileName); + var useUTF8InOutputfile = moduleDecl.containsUnicodeChar || (this.emitOptions.emitComments && moduleDecl.containsUnicodeCharInComment); + try { + this.declFile = new DeclFileWriter(this.emitOptions.ioHost.createFile(declareFileName, useUTF8InOutputfile)); + } catch (ex) { + this.errorReporter.emitterError(null, ex.message); + } + } + this.pushDeclarationContainer(moduleDecl); + } else { + if(!this.emitOptions.outputMany) { + TypeScript.CompilerDiagnostics.assert(this.singleDeclFile != this.declFile, "singleDeclFile cannot be null as we are going to revert back to it"); + TypeScript.CompilerDiagnostics.assert(this.indenter.indentAmt == 0, "Indent has to be 0 when outputing new file"); + try { + this.declFile.Close(); + } catch (ex) { + this.errorReporter.emitterError(null, ex.message); + } + this.declFile = this.singleDeclFile; + } + this.popDeclarationContainer(moduleDecl); + } + } + return true; + } + if(moduleDecl.isEnum()) { + if(pre) { + this.emitEnumSignature(moduleDecl); + } + return false; + } + if(!this.canEmitPrePostAstSignature(TypeScript.ToDeclFlags(moduleDecl.modFlags), moduleDecl, pre)) { + return false; + } + if(pre) { + if(this.emitDottedModuleName()) { + this.dottedModuleEmit += "."; + } else { + this.dottedModuleEmit = this.getDeclFlagsString(TypeScript.ToDeclFlags(moduleDecl.modFlags), "module"); + } + this.dottedModuleEmit += moduleDecl.name.text; + var isCurrentModuleDotted = (moduleDecl.members.members.length == 1 && moduleDecl.members.members[0].nodeType == TypeScript.NodeType.ModuleDeclaration && !(moduleDecl.members.members[0]).isEnum() && TypeScript.hasFlag((moduleDecl.members.members[0]).modFlags, TypeScript.ModuleFlags.Exported)); + var moduleDeclComments = moduleDecl.getDocComments(); + isCurrentModuleDotted = isCurrentModuleDotted && (moduleDeclComments == null || moduleDeclComments.length == 0); + this.isDottedModuleName.push(isCurrentModuleDotted); + this.pushDeclarationContainer(moduleDecl); + if(!isCurrentModuleDotted) { + this.emitDeclarationComments(moduleDecl); + this.declFile.Write(this.dottedModuleEmit); + this.declFile.WriteLine(" {"); + this.indenter.increaseIndent(); + } + } else { + if(!this.emitDottedModuleName()) { + this.indenter.decreaseIndent(); + this.emitIndent(); + this.declFile.WriteLine("}"); + } + this.popDeclarationContainer(moduleDecl); + this.isDottedModuleName.pop(); + } + return true; + }; + DeclarationEmitter.prototype.ScriptCallback = function (pre, script) { + if(pre) { + if(this.emitOptions.outputMany) { + for(var i = 0; i < script.referencedFiles.length; i++) { + var referencePath = script.referencedFiles[i].path; + var declareFileName; + if(TypeScript.isRooted(referencePath)) { + declareFileName = this.emitOptions.mapOutputFileName(referencePath, TypeScript.TypeScriptCompiler.mapToDTSFileName); + } else { + declareFileName = TypeScript.getDeclareFilePath(script.referencedFiles[i].path); + } + this.declFile.WriteLine('/// '); + } + } + this.pushDeclarationContainer(script); + } else { + this.popDeclarationContainer(script); + } + return true; + }; + DeclarationEmitter.prototype.DefaultCallback = function (pre, ast) { + return !TypeScript.hasFlag(ast.flags, TypeScript.ASTFlags.IsStatement); + }; + return DeclarationEmitter; + })(); + TypeScript.DeclarationEmitter = DeclarationEmitter; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (UpdateUnitKind) { + UpdateUnitKind._map = []; + UpdateUnitKind._map[0] = "Unknown"; + UpdateUnitKind.Unknown = 0; + UpdateUnitKind._map[1] = "NoEdits"; + UpdateUnitKind.NoEdits = 1; + UpdateUnitKind._map[2] = "EditsInsideSingleScope"; + UpdateUnitKind.EditsInsideSingleScope = 2; + })(TypeScript.UpdateUnitKind || (TypeScript.UpdateUnitKind = {})); + var UpdateUnitKind = TypeScript.UpdateUnitKind; + var ScriptEditRange = (function () { + function ScriptEditRange(minChar, limChar, delta) { + this.minChar = minChar; + this.limChar = limChar; + this.delta = delta; + } + ScriptEditRange.unknown = function unknown() { + return new ScriptEditRange(-1, -1, -1); + }; + ScriptEditRange.prototype.isUnknown = function () { + return this.minChar === -1 && this.limChar === -1 && this.delta === -1; + }; + ScriptEditRange.prototype.containsPosition = function (pos) { + return (this.minChar <= pos && pos < this.limChar) || (this.minChar <= pos && pos < this.limChar + this.delta); + }; + ScriptEditRange.prototype.toString = function () { + return "editRange(minChar=" + this.minChar + ", limChar=" + this.limChar + ", delta=" + this.delta + ")"; + }; + return ScriptEditRange; + })(); + TypeScript.ScriptEditRange = ScriptEditRange; + var UpdateUnitResult = (function () { + function UpdateUnitResult(kind, unitIndex, script1, script2) { + this.kind = kind; + this.unitIndex = unitIndex; + this.script1 = script1; + this.script2 = script2; + this.scope1 = null; + this.scope2 = null; + this.editRange = null; + this.parseErrors = []; + } + UpdateUnitResult.noEdits = function noEdits(unitIndex) { + return new UpdateUnitResult(UpdateUnitKind.NoEdits, unitIndex, null, null); + }; + UpdateUnitResult.unknownEdits = function unknownEdits(script1, script2, parseErrors) { + var result = new UpdateUnitResult(UpdateUnitKind.Unknown, script1.locationInfo.unitIndex, script1, script2); + result.parseErrors = parseErrors; + return result; + }; + UpdateUnitResult.singleScopeEdits = function singleScopeEdits(script1, script2, scope1, scope2, editRange, parseErrors) { + var result = new UpdateUnitResult(UpdateUnitKind.EditsInsideSingleScope, script1.locationInfo.unitIndex, script1, script2); + result.scope1 = scope1; + result.scope2 = scope2; + result.editRange = editRange; + result.parseErrors = parseErrors; + return result; + }; + return UpdateUnitResult; + })(); + TypeScript.UpdateUnitResult = UpdateUnitResult; + var ErrorEntry = (function () { + function ErrorEntry(unitIndex, minChar, limChar, message) { + this.unitIndex = unitIndex; + this.minChar = minChar; + this.limChar = limChar; + this.message = message; + } + return ErrorEntry; + })(); + TypeScript.ErrorEntry = ErrorEntry; + TypeScript.defaultSettings = new TypeScript.CompilationSettings(); + var TypeScriptCompiler = (function () { + function TypeScriptCompiler(errorOutput, logger, settings) { + if (typeof logger === "undefined") { logger = new TypeScript.NullLogger(); } + if (typeof settings === "undefined") { settings = TypeScript.defaultSettings; } + this.errorOutput = errorOutput; + this.logger = logger; + this.settings = settings; + this.parser = new TypeScript.Parser(); + this.typeFlow = null; + this.scripts = new TypeScript.ASTList(); + this.units = new Array(); + this.errorReporter = new TypeScript.ErrorReporter(this.errorOutput); + this.persistentTypeState = new TypeScript.PersistentGlobalTypeState(this.errorReporter); + this.errorReporter.parser = this.parser; + this.initTypeChecker(this.errorOutput); + this.parser.style_requireSemi = this.settings.styleSettings.requireSemi; + this.parser.style_funcInLoop = this.settings.styleSettings.funcInLoop; + this.parser.inferPropertiesFromThisAssignment = this.settings.inferPropertiesFromThisAssignment; + this.emitSettings = new TypeScript.EmitOptions(this.settings); + TypeScript.codeGenTarget = settings.codeGenTarget; + } + TypeScriptCompiler.prototype.timeFunction = function (funcDescription, func) { + return TypeScript.timeFunction(this.logger, funcDescription, func); + }; + TypeScriptCompiler.prototype.initTypeChecker = function (errorOutput) { + this.persistentTypeState.refreshPersistentState(); + this.typeChecker = new TypeScript.TypeChecker(this.persistentTypeState); + this.typeChecker.errorReporter = this.errorReporter; + this.typeChecker.checkControlFlow = this.settings.controlFlow; + this.typeChecker.checkControlFlowUseDef = this.settings.controlFlowUseDef; + this.typeChecker.printControlFlowGraph = this.settings.printControlFlow; + this.typeChecker.errorsOnWith = this.settings.errorOnWith; + this.typeChecker.styleSettings = this.settings.styleSettings; + this.typeChecker.canCallDefinitionSignature = this.settings.canCallDefinitionSignature; + this.errorReporter.checker = this.typeChecker; + this.setErrorOutput(this.errorOutput); + }; + TypeScriptCompiler.prototype.setErrorOutput = function (outerr) { + this.errorOutput = outerr; + this.errorReporter.setErrOut(outerr); + this.parser.outfile = outerr; + }; + TypeScriptCompiler.prototype.emitCommentsToOutput = function () { + this.emitSettings = new TypeScript.EmitOptions(this.settings); + }; + TypeScriptCompiler.prototype.setErrorCallback = function (fn) { + this.parser.errorCallback = fn; + }; + TypeScriptCompiler.prototype.updateUnit = function (prog, filename, setRecovery) { + return this.updateSourceUnit(new TypeScript.StringSourceText(prog), filename, setRecovery); + }; + TypeScriptCompiler.prototype.updateSourceUnit = function (sourceText, filename, setRecovery) { + var _this = this; + return this.timeFunction("updateSourceUnit(" + filename + ")", function () { + var updateResult = _this.partialUpdateUnit(sourceText, filename, setRecovery); + return _this.applyUpdateResult(updateResult); + }); + }; + TypeScriptCompiler.prototype.applyUpdateResult = function (updateResult) { + switch(updateResult.kind) { + case UpdateUnitKind.NoEdits: + return false; + case UpdateUnitKind.Unknown: + this.scripts.members[updateResult.unitIndex] = updateResult.script2; + this.units[updateResult.unitIndex] = updateResult.script2.locationInfo; + for(var i = 0, len = updateResult.parseErrors.length; i < len; i++) { + var e = updateResult.parseErrors[i]; + if(this.parser.errorCallback) { + this.parser.errorCallback(e.minChar, e.limChar - e.minChar, e.message, e.unitIndex); + } + } + return true; + case UpdateUnitKind.EditsInsideSingleScope: + new TypeScript.IncrementalParser(this.logger).mergeTrees(updateResult); + return true; + } + }; + TypeScriptCompiler.prototype.partialUpdateUnit = function (sourceText, filename, setRecovery) { + var _this = this; + return this.timeFunction("partialUpdateUnit(" + filename + ")", function () { + for(var i = 0, len = _this.units.length; i < len; i++) { + if(_this.units[i].filename == filename) { + if((_this.scripts.members[i]).isResident) { + return UpdateUnitResult.noEdits(i); + } + if(setRecovery) { + _this.parser.setErrorRecovery(null); + } + var updateResult; + var parseErrors = []; + var errorCapture = function (minChar, charLen, message, unitIndex) { + parseErrors.push(new ErrorEntry(unitIndex, minChar, minChar + charLen, message)); + }; + var svErrorCallback = _this.parser.errorCallback; + if(svErrorCallback) { + _this.parser.errorCallback = errorCapture; + } + var oldScript = _this.scripts.members[i]; + var newScript = _this.parser.parse(sourceText, filename, i); + if(svErrorCallback) { + _this.parser.errorCallback = svErrorCallback; + } + updateResult = UpdateUnitResult.unknownEdits(oldScript, newScript, parseErrors); + return updateResult; + } + } + throw new Error("Unknown file \"" + filename + "\""); + }); + }; + TypeScriptCompiler.prototype.addUnit = function (prog, filename, keepResident, referencedFiles) { + if (typeof keepResident === "undefined") { keepResident = false; } + if (typeof referencedFiles === "undefined") { referencedFiles = []; } + return this.addSourceUnit(new TypeScript.StringSourceText(prog), filename, keepResident, referencedFiles); + }; + TypeScriptCompiler.prototype.addSourceUnit = function (sourceText, filename, keepResident, referencedFiles) { + if (typeof referencedFiles === "undefined") { referencedFiles = []; } + var _this = this; + return this.timeFunction("addSourceUnit(" + filename + ", " + keepResident + ")", function () { + var script = _this.parser.parse(sourceText, filename, _this.units.length, TypeScript.AllowedElements.Global); + script.referencedFiles = referencedFiles; + script.isResident = keepResident; + _this.persistentTypeState.setCollectionMode(keepResident ? TypeScript.TypeCheckCollectionMode.Resident : TypeScript.TypeCheckCollectionMode.Transient); + var index = _this.units.length; + _this.units[index] = script.locationInfo; + _this.typeChecker.collectTypes(script); + _this.scripts.append(script); + return script; + }); + }; + TypeScriptCompiler.prototype.parseUnit = function (prog, filename) { + return this.parseSourceUnit(new TypeScript.StringSourceText(prog), filename); + }; + TypeScriptCompiler.prototype.parseSourceUnit = function (sourceText, filename) { + this.parser.setErrorRecovery(this.errorOutput); + var script = this.parser.parse(sourceText, filename, 0); + var index = this.units.length; + this.units[index] = script.locationInfo; + this.typeChecker.collectTypes(script); + this.scripts.append(script); + }; + TypeScriptCompiler.prototype.typeCheck = function () { + var _this = this; + return this.timeFunction("typeCheck()", function () { + var binder = new TypeScript.Binder(_this.typeChecker); + _this.typeChecker.units = _this.units; + binder.bind(_this.typeChecker.globalScope, _this.typeChecker.globals); + binder.bind(_this.typeChecker.globalScope, _this.typeChecker.ambientGlobals); + binder.bind(_this.typeChecker.globalScope, _this.typeChecker.globalTypes); + binder.bind(_this.typeChecker.globalScope, _this.typeChecker.ambientGlobalTypes); + _this.typeFlow = new TypeScript.TypeFlow(_this.logger, _this.typeChecker.globalScope, _this.parser, _this.typeChecker); + var i = 0; + var script = null; + var len = _this.scripts.members.length; + _this.persistentTypeState.setCollectionMode(TypeScript.TypeCheckCollectionMode.Resident); + for(i = 0; i < len; i++) { + script = _this.scripts.members[i]; + if(!script.isResident || script.hasBeenTypeChecked) { + continue; + } + _this.typeFlow.assignScopes(script); + _this.typeFlow.initLibs(); + } + for(i = 0; i < len; i++) { + script = _this.scripts.members[i]; + if(!script.isResident || script.hasBeenTypeChecked) { + continue; + } + _this.typeFlow.typeCheck(script); + script.hasBeenTypeChecked = true; + } + _this.persistentTypeState.setCollectionMode(TypeScript.TypeCheckCollectionMode.Transient); + len = _this.scripts.members.length; + for(i = 0; i < len; i++) { + script = _this.scripts.members[i]; + if(script.isResident) { + continue; + } + _this.typeFlow.assignScopes(script); + _this.typeFlow.initLibs(); + } + for(i = 0; i < len; i++) { + script = _this.scripts.members[i]; + if(script.isResident) { + continue; + } + _this.typeFlow.typeCheck(script); + } + return null; + }); + }; + TypeScriptCompiler.prototype.cleanASTTypesForReTypeCheck = function (ast) { + function cleanASTType(ast, parent) { + ast.type = null; + if(ast.nodeType == TypeScript.NodeType.VarDecl) { + var vardecl = ast; + vardecl.sym = null; + } else if(ast.nodeType == TypeScript.NodeType.ArgDecl) { + var argdecl = ast; + argdecl.sym = null; + } else if(ast.nodeType == TypeScript.NodeType.Name) { + var name = ast; + name.sym = null; + } else if(ast.nodeType == TypeScript.NodeType.FuncDecl) { + var funcdecl = ast; + funcdecl.signature = null; + funcdecl.freeVariables = new Array(); + funcdecl.symbols = null; + funcdecl.accessorSymbol = null; + funcdecl.scopeType = null; + } else if(ast.nodeType == TypeScript.NodeType.ModuleDeclaration) { + var modDecl = ast; + modDecl.mod = null; + } else if(ast.nodeType == TypeScript.NodeType.With) { + (ast).withSym = null; + } else if(ast.nodeType == TypeScript.NodeType.Catch) { + (ast).containedScope = null; + } else if(ast.nodeType === TypeScript.NodeType.Script) { + (ast).externallyVisibleImportedSymbols = []; + } + return ast; + } + TypeScript.getAstWalkerFactory().walk(ast, cleanASTType); + }; + TypeScriptCompiler.prototype.cleanTypesForReTypeCheck = function () { + var _this = this; + return this.timeFunction("cleanTypesForReTypeCheck()", function () { + for(var i = 0, len = _this.scripts.members.length; i < len; i++) { + var script = _this.scripts.members[i]; + if((script).isResident) { + continue; + } + _this.cleanASTTypesForReTypeCheck(script); + _this.typeChecker.collectTypes(script); + } + return null; + }); + }; + TypeScriptCompiler.prototype.attemptIncrementalTypeCheck = function (updateResult) { + return this.timeFunction("attemptIncrementalTypeCheck()", function () { + return false; + }); + }; + TypeScriptCompiler.prototype.reTypeCheck = function () { + var _this = this; + return this.timeFunction("reTypeCheck()", function () { + TypeScript.CompilerDiagnostics.analysisPass++; + _this.initTypeChecker(_this.errorOutput); + _this.persistentTypeState.setCollectionMode(TypeScript.TypeCheckCollectionMode.Transient); + _this.cleanTypesForReTypeCheck(); + return _this.typeCheck(); + }); + }; + TypeScriptCompiler.prototype.isDynamicModuleCompilation = function () { + for(var i = 0, len = this.scripts.members.length; i < len; i++) { + var script = this.scripts.members[i]; + if(!script.isDeclareFile && script.topLevelMod != null) { + return true; + } + } + return false; + }; + TypeScriptCompiler.prototype.updateCommonDirectoryPath = function () { + var commonComponents = []; + var commonComponentsLength = -1; + for(var i = 0, len = this.scripts.members.length; i < len; i++) { + var script = this.scripts.members[i]; + if(script.emitRequired(this.emitSettings)) { + var fileName = script.locationInfo.filename; + var fileComponents = TypeScript.filePathComponents(fileName); + if(commonComponentsLength == -1) { + commonComponents = fileComponents; + commonComponentsLength = commonComponents.length; + } else { + var updatedPath = false; + for(var j = 0; j < commonComponentsLength && j < fileComponents.length; j++) { + if(commonComponents[j] != fileComponents[j]) { + commonComponentsLength = j; + updatedPath = true; + if(j == 0) { + this.errorReporter.emitterError(null, "Cannot find the common subdirectory path for the input files"); + return; + } + break; + } + } + if(!updatedPath && fileComponents.length < commonComponentsLength) { + commonComponentsLength = fileComponents.length; + } + } + } + } + this.emitSettings.commonDirectoryPath = commonComponents.slice(0, commonComponentsLength).join("/") + "/"; + if(this.emitSettings.outputOption.charAt(this.emitSettings.outputOption.length - 1) != "/") { + this.emitSettings.outputOption += "/"; + } + }; + TypeScriptCompiler.prototype.parseEmitOption = function (ioHost) { + this.emitSettings.ioHost = ioHost; + if(this.emitSettings.outputOption == "") { + this.emitSettings.outputMany = true; + this.emitSettings.commonDirectoryPath = ""; + return; + } + this.emitSettings.outputOption = TypeScript.switchToForwardSlashes(this.emitSettings.ioHost.resolvePath(this.emitSettings.outputOption)); + if(this.emitSettings.ioHost.directoryExists(this.emitSettings.outputOption)) { + this.emitSettings.outputMany = true; + } else if(this.emitSettings.ioHost.fileExists(this.emitSettings.outputOption)) { + this.emitSettings.outputMany = false; + } else { + this.emitSettings.outputMany = !TypeScript.isJSFile(this.emitSettings.outputOption); + } + if(this.isDynamicModuleCompilation() && !this.emitSettings.outputMany) { + this.errorReporter.emitterError(null, "Cannot compile dynamic modules when emitting into single file"); + } + if(this.emitSettings.outputMany) { + this.updateCommonDirectoryPath(); + } + }; + TypeScriptCompiler.prototype.useUTF8ForFile = function (script) { + if(this.emitSettings.outputMany) { + return this.outputScriptToUTF8(script); + } else { + return this.outputScriptsToUTF8((this.scripts.members)); + } + }; + TypeScriptCompiler.mapToDTSFileName = function mapToDTSFileName(fileName, wholeFileNameReplaced) { + return TypeScript.getDeclareFilePath(fileName); + }; + TypeScriptCompiler.prototype.canEmitDeclarations = function (script) { + if(!this.settings.generateDeclarationFiles) { + return false; + } + if(!!script && (script.isDeclareFile || script.isResident || script.bod == null)) { + return false; + } + return true; + }; + TypeScriptCompiler.prototype.emitDeclarationsUnit = function (script, reuseEmitter, declarationEmitter) { + if(!this.canEmitDeclarations(script)) { + return null; + } + if(!declarationEmitter) { + var declareFileName = this.emitSettings.mapOutputFileName(script.locationInfo.filename, TypeScriptCompiler.mapToDTSFileName); + var declareFile = this.createFile(declareFileName, this.useUTF8ForFile(script)); + declarationEmitter = new TypeScript.DeclarationEmitter(this.typeChecker, this.emitSettings, this.errorReporter); + declarationEmitter.setDeclarationFile(declareFile); + } + declarationEmitter.emitDeclarations(script); + if(!reuseEmitter) { + declarationEmitter.Close(); + return null; + } else { + return declarationEmitter; + } + }; + TypeScriptCompiler.prototype.emitDeclarations = function () { + if(!this.canEmitDeclarations()) { + return; + } + if(this.errorReporter.hasErrors) { + return; + } + if(this.scripts.members.length == 0) { + return; + } + var declarationEmitter = null; + for(var i = 0, len = this.scripts.members.length; i < len; i++) { + var script = this.scripts.members[i]; + if(this.emitSettings.outputMany || declarationEmitter == null) { + declarationEmitter = this.emitDeclarationsUnit(script, !this.emitSettings.outputMany); + } else { + this.emitDeclarationsUnit(script, true, declarationEmitter); + } + } + if(declarationEmitter) { + declarationEmitter.Close(); + } + }; + TypeScriptCompiler.mapToFileNameExtension = function mapToFileNameExtension(extension, fileName, wholeFileNameReplaced) { + if(wholeFileNameReplaced) { + return fileName; + } else { + var splitFname = fileName.split("."); + splitFname.pop(); + return splitFname.join(".") + extension; + } + }; + TypeScriptCompiler.mapToJSFileName = function mapToJSFileName(fileName, wholeFileNameReplaced) { + return TypeScriptCompiler.mapToFileNameExtension(".js", fileName, wholeFileNameReplaced); + }; + TypeScriptCompiler.prototype.emitUnit = function (script, reuseEmitter, emitter, inputOutputMapper) { + if(!script.emitRequired(this.emitSettings)) { + return null; + } + var fname = script.locationInfo.filename; + if(!emitter) { + var outFname = this.emitSettings.mapOutputFileName(fname, TypeScriptCompiler.mapToJSFileName); + var outFile = this.createFile(outFname, this.useUTF8ForFile(script)); + emitter = new TypeScript.Emitter(this.typeChecker, outFname, outFile, this.emitSettings, this.errorReporter); + if(this.settings.mapSourceFiles) { + emitter.setSourceMappings(new TypeScript.SourceMapper(fname, outFname, outFile, this.createFile(outFname + TypeScript.SourceMapper.MapFileExtension, false), this.errorReporter, this.settings.emitFullSourceMapPath)); + } + if(inputOutputMapper) { + inputOutputMapper(script.locationInfo.unitIndex, outFname); + } + } else if(this.settings.mapSourceFiles) { + emitter.setSourceMappings(new TypeScript.SourceMapper(fname, emitter.emittingFileName, emitter.outfile, emitter.sourceMapper.sourceMapOut, this.errorReporter, this.settings.emitFullSourceMapPath)); + } + this.typeChecker.locationInfo = script.locationInfo; + emitter.emitJavascript(script, TypeScript.TokenID.Comma, false); + if(!reuseEmitter) { + emitter.Close(); + return null; + } else { + return emitter; + } + }; + TypeScriptCompiler.prototype.emit = function (ioHost, inputOutputMapper) { + this.parseEmitOption(ioHost); + var emitter = null; + for(var i = 0, len = this.scripts.members.length; i < len; i++) { + var script = this.scripts.members[i]; + if(this.emitSettings.outputMany || emitter == null) { + emitter = this.emitUnit(script, !this.emitSettings.outputMany, null, inputOutputMapper); + } else { + this.emitUnit(script, true, emitter); + } + } + if(emitter) { + emitter.Close(); + } + }; + TypeScriptCompiler.prototype.emitToOutfile = function (outputFile) { + if(this.settings.mapSourceFiles) { + throw Error("Cannot generate source map"); + } + if(this.settings.generateDeclarationFiles) { + throw Error("Cannot generate declaration files"); + } + if(this.settings.outputOption != "") { + throw Error("Cannot parse output option"); + } + var emitter = emitter = new TypeScript.Emitter(this.typeChecker, "stdout", outputFile, this.emitSettings, this.errorReporter); + ; + for(var i = 0, len = this.scripts.members.length; i < len; i++) { + var script = this.scripts.members[i]; + this.typeChecker.locationInfo = script.locationInfo; + emitter.emitJavascript(script, TypeScript.TokenID.Comma, false); + } + }; + TypeScriptCompiler.prototype.emitAST = function (ioHost) { + this.parseEmitOption(ioHost); + var outFile = null; + var context = null; + for(var i = 0, len = this.scripts.members.length; i < len; i++) { + var script = this.scripts.members[i]; + if(this.emitSettings.outputMany || context == null) { + var fname = this.units[i].filename; + var mapToTxtFileName = function (fileName, wholeFileNameReplaced) { + return TypeScriptCompiler.mapToFileNameExtension(".txt", fileName, wholeFileNameReplaced); + }; + var outFname = this.emitSettings.mapOutputFileName(fname, mapToTxtFileName); + outFile = this.createFile(outFname, this.useUTF8ForFile(script)); + context = new TypeScript.PrintContext(outFile, this.parser); + } + TypeScript.getAstWalkerFactory().walk(script, TypeScript.prePrintAST, TypeScript.postPrintAST, null, context); + if(this.emitSettings.outputMany) { + try { + outFile.Close(); + } catch (e) { + this.errorReporter.emitterError(null, e.message); + } + } + } + if(!this.emitSettings.outputMany) { + try { + outFile.Close(); + } catch (e) { + this.errorReporter.emitterError(null, e.message); + } + } + }; + TypeScriptCompiler.prototype.outputScriptToUTF8 = function (script) { + return script.containsUnicodeChar || (this.emitSettings.emitComments && script.containsUnicodeCharInComment); + }; + TypeScriptCompiler.prototype.outputScriptsToUTF8 = function (scripts) { + for(var i = 0, len = scripts.length; i < len; i++) { + var script = scripts[i]; + if(this.outputScriptToUTF8(script)) { + return true; + } + } + return false; + }; + TypeScriptCompiler.prototype.createFile = function (fileName, useUTF8) { + try { + return this.emitSettings.ioHost.createFile(fileName, useUTF8); + } catch (ex) { + this.errorReporter.emitterError(null, ex.message); + } + }; + return TypeScriptCompiler; + })(); + TypeScript.TypeScriptCompiler = TypeScriptCompiler; + var ScopeEntry = (function () { + function ScopeEntry(name, type, sym) { + this.name = name; + this.type = type; + this.sym = sym; + } + return ScopeEntry; + })(); + TypeScript.ScopeEntry = ScopeEntry; + var ScopeTraversal = (function () { + function ScopeTraversal(compiler) { + this.compiler = compiler; + } + ScopeTraversal.prototype.getScope = function (enclosingScopeContext) { + if(enclosingScopeContext.enclosingObjectLit && enclosingScopeContext.isMemberCompletion) { + return enclosingScopeContext.getObjectLiteralScope(); + } else if(enclosingScopeContext.isMemberCompletion) { + if(enclosingScopeContext.useFullAst) { + return this.compiler.typeFlow.findMemberScopeAtFullAst(enclosingScopeContext); + } else { + return this.compiler.typeFlow.findMemberScopeAt(enclosingScopeContext); + } + } else { + return enclosingScopeContext.getScope(); + } + }; + ScopeTraversal.prototype.getScopeEntries = function (enclosingScopeContext, getPrettyTypeName) { + var scope = this.getScope(enclosingScopeContext); + if(scope == null) { + return []; + } + var inScopeNames = new TypeScript.StringHashTable(); + var allSymbolNames = scope.getAllSymbolNames(enclosingScopeContext.isMemberCompletion); + for(var i = 0; i < allSymbolNames.length; i++) { + var name = allSymbolNames[i]; + if(name == TypeScript.globalId || name == "_Core" || name == "_element") { + continue; + } + inScopeNames.add(name, ""); + } + var svModuleDecl = this.compiler.typeChecker.currentModDecl; + this.compiler.typeChecker.currentModDecl = enclosingScopeContext.deepestModuleDecl; + var result = this.getTypeNamesForNames(enclosingScopeContext, inScopeNames.getAllKeys(), scope, getPrettyTypeName); + this.compiler.typeChecker.currentModDecl = svModuleDecl; + return result; + }; + ScopeTraversal.prototype.getTypeNamesForNames = function (enclosingScopeContext, allNames, scope, getPrettyTypeName) { + var result = []; + var enclosingScope = enclosingScopeContext.getScope(); + for(var i = 0; i < allNames.length; i++) { + var name = allNames[i]; + var publicsOnly = enclosingScopeContext.publicsOnly && enclosingScopeContext.isMemberCompletion; + var symbol = scope.find(name, publicsOnly, false); + if(symbol == null) { + symbol = scope.find(name, publicsOnly, true); + } + var displayThisMember = symbol && symbol.flags & TypeScript.SymbolFlags.Private ? symbol.container == scope.container : true; + if(symbol) { + if(displayThisMember && !TypeScript.isQuoted(symbol.name) && !TypeScript.isRelative(symbol.name)) { + var getPrettyOverload = getPrettyTypeName && symbol.declAST && symbol.declAST.nodeType == TypeScript.NodeType.FuncDecl; + var type = symbol.getType(); + var typeName = type ? type.getScopedTypeName(enclosingScope, getPrettyOverload) : ""; + result.push(new ScopeEntry(name, typeName, symbol)); + } + } else { + if(name == "true" || name == "false") { + result.push(new ScopeEntry(name, "bool", this.compiler.typeChecker.booleanType.symbol)); + } + } + } + return result; + }; + return ScopeTraversal; + })(); + TypeScript.ScopeTraversal = ScopeTraversal; +})(TypeScript || (TypeScript = {})); +var TypeScript; +(function (TypeScript) { + (function (CompilerDiagnostics) { + CompilerDiagnostics.debug = false; + CompilerDiagnostics.diagnosticWriter = null; + CompilerDiagnostics.analysisPass = 0; + function Alert(output) { + if(CompilerDiagnostics.diagnosticWriter) { + CompilerDiagnostics.diagnosticWriter.Alert(output); + } + } + CompilerDiagnostics.Alert = Alert; + function debugPrint(s) { + if(CompilerDiagnostics.debug) { + Alert(s); + } + } + CompilerDiagnostics.debugPrint = debugPrint; + function assert(condition, s) { + if(CompilerDiagnostics.debug) { + if(!condition) { + Alert(s); + } + } + } + CompilerDiagnostics.assert = assert; + })(TypeScript.CompilerDiagnostics || (TypeScript.CompilerDiagnostics = {})); + var CompilerDiagnostics = TypeScript.CompilerDiagnostics; + var NullLogger = (function () { + function NullLogger() { } + NullLogger.prototype.information = function () { + return false; + }; + NullLogger.prototype.debug = function () { + return false; + }; + NullLogger.prototype.warning = function () { + return false; + }; + NullLogger.prototype.error = function () { + return false; + }; + NullLogger.prototype.fatal = function () { + return false; + }; + NullLogger.prototype.log = function (s) { + }; + return NullLogger; + })(); + TypeScript.NullLogger = NullLogger; + var LoggerAdapter = (function () { + function LoggerAdapter(logger) { + this.logger = logger; + this._information = this.logger.information(); + this._debug = this.logger.debug(); + this._warning = this.logger.warning(); + this._error = this.logger.error(); + this._fatal = this.logger.fatal(); + } + LoggerAdapter.prototype.information = function () { + return this._information; + }; + LoggerAdapter.prototype.debug = function () { + return this._debug; + }; + LoggerAdapter.prototype.warning = function () { + return this._warning; + }; + LoggerAdapter.prototype.error = function () { + return this._error; + }; + LoggerAdapter.prototype.fatal = function () { + return this._fatal; + }; + LoggerAdapter.prototype.log = function (s) { + this.logger.log(s); + }; + return LoggerAdapter; + })(); + TypeScript.LoggerAdapter = LoggerAdapter; + var BufferedLogger = (function () { + function BufferedLogger() { + this.logContents = []; + } + BufferedLogger.prototype.information = function () { + return false; + }; + BufferedLogger.prototype.debug = function () { + return false; + }; + BufferedLogger.prototype.warning = function () { + return false; + }; + BufferedLogger.prototype.error = function () { + return false; + }; + BufferedLogger.prototype.fatal = function () { + return false; + }; + BufferedLogger.prototype.log = function (s) { + this.logContents.push(s); + }; + return BufferedLogger; + })(); + TypeScript.BufferedLogger = BufferedLogger; + function timeFunction(logger, funcDescription, func) { + var start = +new Date(); + var result = func(); + var end = +new Date(); + logger.log(funcDescription + " completed in " + (end - start) + " msec"); + return result; + } + TypeScript.timeFunction = timeFunction; + function stringToLiteral(value, length) { + var result = ""; + var addChar = function (index) { + var ch = value.charCodeAt(index); + switch(ch) { + case 0x09: + result += "\\t"; + break; + case 0x0a: + result += "\\n"; + break; + case 0x0b: + result += "\\v"; + break; + case 0x0c: + result += "\\f"; + break; + case 0x0d: + result += "\\r"; + break; + case 0x22: + result += "\\\""; + break; + case 0x27: + result += "\\\'"; + break; + case 0x5c: + result += "\\"; + break; + default: + result += value.charAt(index); + } + }; + var tooLong = (value.length > length); + if(tooLong) { + var mid = length >> 1; + for(var i = 0; i < mid; i++) { + addChar(i); + } + result += "(...)"; + for(var i = value.length - mid; i < value.length; i++) { + addChar(i); + } + } else { + length = value.length; + for(var i = 0; i < length; i++) { + addChar(i); + } + } + return result; + } + TypeScript.stringToLiteral = stringToLiteral; +})(TypeScript || (TypeScript = {})); diff --git a/ace/ace.d.ts b/ace/ace.d.ts new file mode 100644 index 0000000000..58d65ed4f7 --- /dev/null +++ b/ace/ace.d.ts @@ -0,0 +1,2937 @@ +// Type definitions for Ace Ajax.org Cloud9 Editor +// Project: http://ace.ajax.org/ +// Definitions by: Diullei Gomes +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +module AceAjax { + + export interface Delta { + action: string; + range: Range; + text: string; + lines: string[]; + } + + export interface EditorCommand { + + name:string; + + bindKey:any; + + exec:Function; + } + + export interface CommandManager { + + byName; + + commands; + + platform: string; + + addCommands(commands:EditorCommand[]); + + addCommand(command:EditorCommand); + + exec(name: string, editor: Editor, args: any); + } + + export interface Annotation { + + row: number; + + column: number; + + text: string; + + type: string; + } + + export interface TokenInfo { + + value: string; + } + + export interface Position { + + row: number; + + column: number; + } + + export interface KeyBinding { + + setDefaultHandler(kb); + + setKeyboardHandler(kb); + + addKeyboardHandler(kb, pos); + + removeKeyboardHandler(kb): bool; + + getKeyboardHandler(): any; + + onCommandKey(e, hashId, keyCode); + + onTextInput(text); + } + declare var KeyBinding: { + new(editor: Editor): KeyBinding; + } + + export interface TextMode { + + getTokenizer(): any; + + toggleCommentLines(state, doc, startRow, endRow); + + getNextLineIndent (state, line, tab): string; + + checkOutdent(state, line, input): bool; + + autoOutdent(state, doc, row); + + createWorker(session): any; + + createModeDelegates (mapping); + + transformAction(state, action, editor, session, param): any; + } + + //////////////// + /// Ace + //////////////// + + /** + * The main class required to set up an Ace instance in the browser. + **/ + export interface Ace { + + /** + * Provides access to require in packed noconflict mode + * @param moduleName + **/ + require(moduleName: string): any; + + /** + * Embeds the Ace editor into the DOM, at the element provided by `el`. + * @param el Either the id of an element, or the element itself + **/ + edit(el: string): Editor; + + /** + * Embeds the Ace editor into the DOM, at the element provided by `el`. + * @param el Either the id of an element, or the element itself + **/ + edit(el: HTMLElement): Editor; + + /** + * Creates a new [[EditSession]], and returns the associated [[Document]]. + * @param text {:textParam} + * @param mode {:modeParam} + **/ + createEditSession(text: Document, mode: TextMode): IEditSession; + + /** + * Creates a new [[EditSession]], and returns the associated [[Document]]. + * @param text {:textParam} + * @param mode {:modeParam} + **/ + createEditSession(text: string, mode: TextMode): IEditSession; + } + + //////////////// + /// Anchor + //////////////// + + /** + * Defines the floating pointer in the document. Whenever text is inserted or deleted before the cursor, the position of the cursor is updated. + **/ + export interface Anchor { + + on(event: string, fn: (e) => any); + + /** + * Returns an object identifying the `row` and `column` position of the current anchor. + **/ + getPosition(): Position; + + /** + * Returns the current document. + **/ + getDocument(): Document; + + /** + * Fires whenever the anchor position changes. + * Both of these objects have a `row` and `column` property corresponding to the position. + * Events that can trigger this function include [[Anchor.setPosition `setPosition()`]]. + * @param e An object containing information about the anchor position. It has two properties: + * - `old`: An object describing the old Anchor position + * - `value`: An object describing the new Anchor position + **/ + onChange(e: any); + + /** + * Sets the anchor position to the specified row and column. If `noClip` is `true`, the position is not clipped. + * @param row The row index to move the anchor to + * @param column The column index to move the anchor to + * @param noClip Identifies if you want the position to be clipped + **/ + setPosition(row: number, column: number, noClip: bool); + + /** + * When called, the `'change'` event listener is removed. + **/ + detach(); + } + declare var Anchor: { + /** + * Creates a new `Anchor` and associates it with a document. + * @param doc The document to associate with the anchor + * @param row The starting row position + * @param column The starting column position + **/ + new(doc: Document, row: number, column: number): Anchor; + } + + //////////////////////////////// + /// BackgroundTokenizer + //////////////////////////////// + + /** + * Tokenizes the current [[Document `Document`]] in the background, and caches the tokenized rows for future use. + * If a certain row is changed, everything below that row is re-tokenized. + **/ + export interface BackgroundTokenizer { + + states: any[]; + + /** + * Sets a new tokenizer for this object. + * @param tokenizer The new tokenizer to use + **/ + setTokenizer(tokenizer: Tokenizer); + + /** + * Sets a new document to associate with this object. + * @param doc The new document to associate with + **/ + setDocument(doc: Document); + + /** + * Emits the `'update'` event. `firstRow` and `lastRow` are used to define the boundaries of the region to be updated. + * @param firstRow The starting row region + * @param lastRow The final row region + **/ + fireUpdateEvent(firstRow: number, lastRow: number); + + /** + * Starts tokenizing at the row indicated. + * @param startRow The row to start at + **/ + start(startRow: number); + + /** + * Stops tokenizing. + **/ + stop(); + + /** + * Gives list of tokens of the row. (tokens are cached) + * @param row The row to get tokens at + **/ + getTokens(row: number): TokenInfo[]; + + /** + * [Returns the state of tokenization at the end of a row.]{: #BackgroundTokenizer.getState} + * @param row The row to get state at + **/ + getState(row: number): string; + } + declare var BackgroundTokenizer: { + /** + * Creates a new `BackgroundTokenizer` object. + * @param tokenizer The tokenizer to use + * @param editor The editor to associate with + **/ + new(tokenizer: Tokenizer, editor: Editor): BackgroundTokenizer; + } + + //////////////// + /// Document + //////////////// + + /** + * Contains the text of the document. Document can be attached to several [[EditSession `EditSession`]]s. + * At its core, `Document`s are just an array of strings, with each row in the document matching up to the array index. + **/ + export interface Document { + + on(event: string, fn: (e) => any); + + /** + * Replaces all the lines in the current `Document` with the value of `text`. + * @param text The text to use + **/ + setValue(text: string); + + /** + * Returns all the lines in the document as a single string, split by the new line character. + **/ + getValue(): string; + + /** + * Creates a new `Anchor` to define a floating point in the document. + * @param row The row number to use + * @param column The column number to use + **/ + createAnchor(row: number, column: number); + + /** + * Returns the newline character that's being used, depending on the value of `newLineMode`. + **/ + getNewLineCharacter(): string; + + /** + * [Sets the new line mode.]{: #Document.setNewLineMode.desc} + * @param newLineMode [The newline mode to use; can be either `windows`, `unix`, or `auto`]{: #Document.setNewLineMode.param} + **/ + setNewLineMode(newLineMode: string); + + /** + * [Returns the type of newlines being used; either `windows`, `unix`, or `auto`]{: #Document.getNewLineMode} + **/ + getNewLineMode(): string; + + /** + * Returns `true` if `text` is a newline character (either `\r\n`, `\r`, or `\n`). + * @param text The text to check + **/ + isNewLine(text: string): bool; + + /** + * Returns a verbatim copy of the given line as it is in the document + * @param row The row index to retrieve + **/ + getLine(row: number): string; + + /** + * Returns an array of strings of the rows between `firstRow` and `lastRow`. This function is inclusive of `lastRow`. + * @param firstRow The first row index to retrieve + * @param lastRow The final row index to retrieve + **/ + getLines(firstRow: number, lastRow: number): string[]; + + /** + * Returns all lines in the document as string array. Warning: The caller should not modify this array! + **/ + getAllLines(): string[]; + + /** + * Returns the number of rows in the document. + **/ + getLength(): number; + + /** + * [Given a range within the document, this function returns all the text within that range as a single string.]{: #Document.getTextRange.desc} + * @param range The range to work with + **/ + getTextRange(range: Range): string; + + /** + * Inserts a block of `text` and the indicated `position`. + * @param position The position to start inserting at + * @param text A chunk of text to insert + **/ + insert(position: Position, text: string): any; + + /** + * Inserts the elements in `lines` into the document, starting at the row index given by `row`. This method also triggers the `'change'` event. + * @param row The index of the row to insert at + * @param lines An array of strings + **/ + insertLines(row: number, lines: string[]): any; + + /** + * Inserts a new line into the document at the current row's `position`. This method also triggers the `'change'` event. + * @param position The position to insert at + **/ + insertNewLine(position: Position): any; + + /** + * Inserts `text` into the `position` at the current row. This method also triggers the `'change'` event. + * @param position The position to insert at + * @param text A chunk of text + **/ + insertInLine(position: any, text: string): any; + + /** + * Removes the `range` from the document. + * @param range A specified Range to remove + **/ + remove(range: Range): any; + + /** + * Removes the specified columns from the `row`. This method also triggers the `'change'` event. + * @param row The row to remove from + * @param startColumn The column to start removing at + * @param endColumn The column to stop removing at + **/ + removeInLine(row: number, startColumn: number, endColumn: number): any; + + /** + * Removes a range of full lines. This method also triggers the `'change'` event. + * @param firstRow The first row to be removed + * @param lastRow The last row to be removed + **/ + removeLines(firstRow: number, lastRow: number): string[]; + + /** + * Removes the new line between `row` and the row immediately following it. This method also triggers the `'change'` event. + * @param row The row to check + **/ + removeNewLine(row: number); + + /** + * Replaces a range in the document with the new `text`. + * @param range A specified Range to replace + * @param text The new text to use as a replacement + **/ + replace(range: Range, text: string): any; + + /** + * Applies all the changes previously accumulated. These can be either `'includeText'`, `'insertLines'`, `'removeText'`, and `'removeLines'`. + **/ + applyDeltas(deltas: Delta[]); + + /** + * Reverts any changes previously applied. These can be either `'includeText'`, `'insertLines'`, `'removeText'`, and `'removeLines'`. + **/ + revertDeltas(deltas: Delta[]); + + /** + * Converts an index position in a document to a `{row, column}` object. + * Index refers to the "absolute position" of a character in the document. For example: + * ```javascript + * var x = 0; // 10 characters, plus one for newline + * var y = -1; + * ``` + * Here, `y` is an index 15: 11 characters for the first row, and 5 characters until `y` in the second. + * @param index An index to convert + * @param startRow=0 The row from which to start the conversion + **/ + indexToPosition(index: number, startRow: number): Position; + + /** + * Converts the `{row, column}` position in a document to the character's index. + * Index refers to the "absolute position" of a character in the document. For example: + * ```javascript + * var x = 0; // 10 characters, plus one for newline + * var y = -1; + * ``` + * Here, `y` is an index 15: 11 characters for the first row, and 5 characters until `y` in the second. + * @param pos The `{row, column}` to convert + * @param startRow=0 The row from which to start the conversion + **/ + positionToIndex(pos: Position, startRow: number): number; + } + declare var Document: { + /** + * Creates a new `Document`. If `text` is included, the `Document` contains those strings; otherwise, it's empty. + * @param text The starting text + **/ + new(text?: string): Document; + /** + * Creates a new `Document`. If `text` is included, the `Document` contains those strings; otherwise, it's empty. + * @param text The starting text + **/ + new(text?: string[]): Document; + } + + //////////////////////////////// + /// EditSession + //////////////////////////////// + + /** + * Stores all the data about [[Editor `Editor`]] state providing easy way to change editors state. + * `EditSession` can be attached to only one [[Document `Document`]]. Same `Document` can be attached to several `EditSession`s. + **/ + export interface IEditSession { + + selection: Selection; + + bgTokenizer: BackgroundTokenizer; + + doc: Document; + + on(event: string, fn: (e) => any); + + findMatchingBracket(position: Position); + + addFold(text: string, range: Range); + + getFoldAt(row: number, column: number): any; + + removeFold(arg: any); + + expandFold(arg: any); + + unfold(arg1: any, arg2: bool); + + screenToDocumentColumn(row: number, column: number); + + getFoldDisplayLine(foldLine: any, docRow: number, docColumn: number): any; + + getFoldsInRange(range: Range): any; + + highlight(text: string); + + /** + * Sets the `EditSession` to point to a new `Document`. If a `BackgroundTokenizer` exists, it also points to `doc`. + * @param doc The new `Document` to use + **/ + setDocument(doc: Document); + + /** + * Returns the `Document` associated with this session. + **/ + getDocument(): Document; + + /** + * undefined + * @param row The row to work with + **/ + $resetRowCache(row: number); + + /** + * Sets the session text. + * @param text The new text to place + **/ + setValue(text: string); + + setMode(mode: string); + + /** + * Returns the current [[Document `Document`]] as a string. + **/ + getValue(): string; + + /** + * Returns the string of the current selection. + **/ + getSelection(): Selection; + + /** + * {:BackgroundTokenizer.getState} + * @param row The row to start at + **/ + getState(row: number): string; + + /** + * Starts tokenizing at the row indicated. Returns a list of objects of the tokenized rows. + * @param row The row to start at + **/ + getTokens(row: number): TokenInfo[]; + + /** + * Returns an object indicating the token at the current row. The object has two properties: `index` and `start`. + * @param row The row number to retrieve from + * @param column The column number to retrieve from + **/ + getTokenAt(row: number, column: number): TokenInfo; + + /** + * Sets the undo manager. + * @param undoManager The new undo manager + **/ + setUndoManager(undoManager: UndoManager); + + /** + * Returns the current undo manager. + **/ + getUndoManager(): UndoManager; + + /** + * Returns the current value for tabs. If the user is using soft tabs, this will be a series of spaces (defined by [[EditSession.getTabSize `getTabSize()`]]); otherwise it's simply `'\t'`. + **/ + getTabString(): string; + + /** + * Pass `true` to enable the use of soft tabs. Soft tabs means you're using spaces instead of the tab character (`'\t'`). + * @param useSoftTabs Value indicating whether or not to use soft tabs + **/ + setUseSoftTabs(useSoftTabs: bool); + + /** + * Returns `true` if soft tabs are being used, `false` otherwise. + **/ + getUseSoftTabs(): bool; + + /** + * Set the number of spaces that define a soft tab; for example, passing in `4` transforms the soft tabs to be equivalent to four spaces. This function also emits the `changeTabSize` event. + * @param tabSize The new tab size + **/ + setTabSize(tabSize: number); + + /** + * Returns the current tab size. + **/ + getTabSize(): string; + + /** + * Returns `true` if the character at the position is a soft tab. + * @param position The position to check + **/ + isTabStop(position: any): bool; + + /** + * Pass in `true` to enable overwrites in your session, or `false` to disable. + * If overwrites is enabled, any text you enter will type over any text after it. If the value of `overwrite` changes, this function also emites the `changeOverwrite` event. + * @param overwrite Defines wheter or not to set overwrites + **/ + setOverwrite(overwrite: bool); + + /** + * Returns `true` if overwrites are enabled; `false` otherwise. + **/ + getOverwrite(): bool; + + /** + * Sets the value of overwrite to the opposite of whatever it currently is. + **/ + toggleOverwrite(); + + /** + * Adds `className` to the `row`, to be used for CSS stylings and whatnot. + * @param row The row number + * @param className The class to add + **/ + addGutterDecoration(row: number, className: string); + + /** + * Removes `className` from the `row`. + * @param row The row number + * @param className The class to add + **/ + removeGutterDecoration(row: number, className: string); + + /** + * Returns an array of numbers, indicating which rows have breakpoints. + **/ + getBreakpoints(): number[]; + + /** + * Sets a breakpoint on every row number given by `rows`. This function also emites the `'changeBreakpoint'` event. + * @param rows An array of row indices + **/ + setBreakpoints(rows: Array); + + /** + * Removes all breakpoints on the rows. This function also emites the `'changeBreakpoint'` event. + **/ + clearBreakpoints(); + + /** + * Sets a breakpoint on the row number given by `rows`. This function also emites the `'changeBreakpoint'` event. + * @param row A row index + * @param className Class of the breakpoint + **/ + setBreakpoint(row: number, className: string); + + /** + * Removes a breakpoint on the row number given by `rows`. This function also emites the `'changeBreakpoint'` event. + * @param row A row index + **/ + clearBreakpoint(row: number); + + /** + * Adds a new marker to the given `Range`. If `inFront` is `true`, a front marker is defined, and the `'changeFrontMarker'` event fires; otherwise, the `'changeBackMarker'` event fires. + * @param range Define the range of the marker + * @param clazz Set the CSS class for the marker + * @param type Identify the type of the marker + * @param inFront Set to `true` to establish a front marker + **/ + addMarker(range: Range, clazz: string, type: Function, inFront: bool); + + /** + * Adds a new marker to the given `Range`. If `inFront` is `true`, a front marker is defined, and the `'changeFrontMarker'` event fires; otherwise, the `'changeBackMarker'` event fires. + * @param range Define the range of the marker + * @param clazz Set the CSS class for the marker + * @param type Identify the type of the marker + * @param inFront Set to `true` to establish a front marker + **/ + addMarker(range: Range, clazz: string, type: string, inFront: bool); + + /** + * Adds a dynamic marker to the session. + * @param marker object with update method + * @param inFront Set to `true` to establish a front marker + **/ + addDynamicMarker(marker: any, inFront: bool); + + /** + * Removes the marker with the specified ID. If this marker was in front, the `'changeFrontMarker'` event is emitted. If the marker was in the back, the `'changeBackMarker'` event is emitted. + * @param markerId A number representing a marker + **/ + removeMarker(markerId: number); + + /** + * Returns an array containing the IDs of all the markers, either front or back. + * @param inFront If `true`, indicates you only want front markers; `false` indicates only back markers + **/ + getMarkers(inFront: bool): Array; + + /** + * Sets annotations for the `EditSession`. This functions emits the `'changeAnnotation'` event. + * @param annotations A list of annotations + **/ + setAnnotations(annotations: Annotation[]); + + /** + * Returns the annotations for the `EditSession`. + **/ + getAnnotations(): any; + + /** + * Clears all the annotations for this session. This function also triggers the `'changeAnnotation'` event. + **/ + clearAnnotations(); + + /** + * If `text` contains either the newline (`\n`) or carriage-return ('\r') characters, `$autoNewLine` stores that value. + * @param text A block of text + **/ + $detectNewLine(text: string); + + /** + * Given a starting row and column, this method returns the `Range` of the first word boundary it finds. + * @param row The row to start at + * @param column The column to start at + **/ + getWordRange(row: number, column: number): Range; + + /** + * Gets the range of a word, including its right whitespace. + * @param row The row number to start from + * @param column The column number to start from + **/ + getAWordRange(row: number, column: number): any; + + /** + * {:Document.setNewLineMode.desc} + * @param newLineMode {:Document.setNewLineMode.param} + **/ + setNewLineMode(newLineMode: string); + + /** + * Returns the current new line mode. + **/ + getNewLineMode(): string; + + /** + * Identifies if you want to use a worker for the `EditSession`. + * @param useWorker Set to `true` to use a worker + **/ + setUseWorker(useWorker: bool); + + /** + * Returns `true` if workers are being used. + **/ + getUseWorker(): bool; + + /** + * Reloads all the tokens on the current session. This function calls [[BackgroundTokenizer.start `BackgroundTokenizer.start ()`]] to all the rows; it also emits the `'tokenizerUpdate'` event. + **/ + onReloadTokenizer(); + + /** + * Sets a new text mode for the `EditSession`. This method also emits the `'changeMode'` event. If a [[BackgroundTokenizer `BackgroundTokenizer`]] is set, the `'tokenizerUpdate'` event is also emitted. + * @param mode Set a new text mode + **/ + $mode(mode: TextMode); + + /** + * Returns the current text mode. + **/ + getMode(): TextMode; + + /** + * This function sets the scroll top value. It also emits the `'changeScrollTop'` event. + * @param scrollTop The new scroll top value + **/ + setScrollTop(scrollTop: number); + + /** + * [Returns the value of the distance between the top of the editor and the topmost part of the visible content.]{: #EditSession.getScrollTop} + **/ + getScrollTop(): number; + + /** + * [Sets the value of the distance between the left of the editor and the leftmost part of the visible content.]{: #EditSession.setScrollLeft} + **/ + setScrollLeft(); + + /** + * [Returns the value of the distance between the left of the editor and the leftmost part of the visible content.]{: #EditSession.getScrollLeft} + **/ + getScrollLeft(): number; + + /** + * Returns the width of the screen. + **/ + getScreenWidth(): number; + + /** + * Returns a verbatim copy of the given line as it is in the document + * @param row The row to retrieve from + **/ + getLine(row: number): string; + + /** + * Returns an array of strings of the rows between `firstRow` and `lastRow`. This function is inclusive of `lastRow`. + * @param firstRow The first row index to retrieve + * @param lastRow The final row index to retrieve + **/ + getLines(firstRow: number, lastRow: number): string[]; + + /** + * Returns the number of rows in the document. + **/ + getLength(): number; + + /** + * {:Document.getTextRange.desc} + * @param range The range to work with + **/ + getTextRange(range: Range): string; + + /** + * Inserts a block of `text` and the indicated `position`. + * @param position The position {row, column} to start inserting at + * @param text A chunk of text to insert + **/ + insert(position: Position, text: string): any; + + /** + * Removes the `range` from the document. + * @param range A specified Range to remove + **/ + remove(range: Range): any; + + /** + * Reverts previous changes to your document. + * @param deltas An array of previous changes + * @param dontSelect [If `true`, doesn't select the range of where the change occured]{: #dontSelect} + **/ + undoChanges(deltas: Array, dontSelect: bool): Range; + + /** + * Re-implements a previously undone change to your document. + * @param deltas An array of previous changes + * @param dontSelect {:dontSelect} + **/ + redoChanges(deltas: Array, dontSelect: bool): Range; + + /** + * Enables or disables highlighting of the range where an undo occured. + * @param enable If `true`, selects the range of the reinserted change + **/ + setUndoSelect(enable: bool); + + /** + * Replaces a range in the document with the new `text`. + * @param range A specified Range to replace + * @param text The new text to use as a replacement + **/ + replace(range: Range, text: string): any; + + /** + * Moves a range of text from the given range to the given position. `toPosition` is an object that looks like this: + * ```json + * { row: newRowLocation, column: newColumnLocation } + * ``` + * @param fromRange The range of text you want moved within the document + * @param toPosition The location (row and column) where you want to move the text to + **/ + moveText(fromRange: Range, toPosition: any): Range; + + /** + * Indents all the rows, from `startRow` to `endRow` (inclusive), by prefixing each row with the token in `indentString`. + * If `indentString` contains the `'\t'` character, it's replaced by whatever is defined by [[EditSession.getTabString `getTabString()`]]. + * @param startRow Starting row + * @param endRow Ending row + * @param indentString The indent token + **/ + indentRows(startRow: number, endRow: number, indentString: string); + + /** + * Outdents all the rows defined by the `start` and `end` properties of `range`. + * @param range A range of rows + **/ + outdentRows(range: Range); + + /** + * Shifts all the lines in the document up one, starting from `firstRow` and ending at `lastRow`. + * @param firstRow The starting row to move up + * @param lastRow The final row to move up + **/ + moveLinesUp(firstRow: number, lastRow: number): number; + + /** + * Shifts all the lines in the document down one, starting from `firstRow` and ending at `lastRow`. + * @param firstRow The starting row to move down + * @param lastRow The final row to move down + **/ + moveLinesDown(firstRow: number, lastRow: number): number; + + /** + * Duplicates all the text between `firstRow` and `lastRow`. + * @param firstRow The starting row to duplicate + * @param lastRow The final row to duplicate + **/ + duplicateLines(firstRow: number, lastRow: number): number; + + /** + * Sets whether or not line wrapping is enabled. If `useWrapMode` is different than the current value, the `'changeWrapMode'` event is emitted. + * @param useWrapMode Enable (or disable) wrap mode + **/ + setUseWrapMode(useWrapMode: bool); + + /** + * Returns `true` if wrap mode is being used; `false` otherwise. + **/ + getUseWrapMode(): bool; + + /** + * Sets the boundaries of wrap. Either value can be `null` to have an unconstrained wrap, or, they can be the same number to pin the limit. If the wrap limits for `min` or `max` are different, this method also emits the `'changeWrapMode'` event. + * @param min The minimum wrap value (the left side wrap) + * @param max The maximum wrap value (the right side wrap) + **/ + setWrapLimitRange(min: number, max: number); + + /** + * This should generally only be called by the renderer when a resize is detected. + * @param desiredLimit The new wrap limit + **/ + adjustWrapLimit(desiredLimit: number): bool; + + /** + * Returns the value of wrap limit. + **/ + getWrapLimit(): number; + + /** + * Returns an object that defines the minimum and maximum of the wrap limit; it looks something like this: + * { min: wrapLimitRange_min, max: wrapLimitRange_max } + **/ + getWrapLimitRange(): any; + + /** + * Given a string, returns an array of the display characters, including tabs and spaces. + * @param str The string to check + * @param offset The value to start at + **/ + $getDisplayTokens(str: string, offset: number); + + /** + * Calculates the width of the string `str` on the screen while assuming that the string starts at the first column on the screen. + * @param str The string to calculate the screen width of + * @param maxScreenColumn + * @param screenColumn + **/ + $getStringScreenWidth(str: string, maxScreenColumn: number, screenColumn: number): number[]; + + /** + * Returns number of screenrows in a wrapped line. + * @param row The row number to check + **/ + getRowLength(row: number): number; + + /** + * Returns the position (on screen) for the last character in the provided screen row. + * @param screenRow The screen row to check + **/ + getScreenLastRowColumn(screenRow: number): number; + + /** + * For the given document row and column, this returns the column position of the last screen row. + * @param docRow + * @param docColumn + **/ + getDocumentLastRowColumn(docRow: number, docColumn: number): number; + + /** + * For the given document row and column, this returns the document position of the last row. + * @param docRow + * @param docColumn + **/ + getDocumentLastRowColumnPosition(docRow: number, docColumn: number): number; + + /** + * For the given row, this returns the split data. + **/ + getRowSplitData(): string; + + /** + * The distance to the next tab stop at the specified screen column. + * @param screenColumn The screen column to check + **/ + getScreenTabSize(screenColumn: number): number; + + /** + * Converts characters coordinates on the screen to characters coordinates within the document. [This takes into account code folding, word wrap, tab size, and any other visual modifications.]{: #conversionConsiderations} + * @param screenRow The screen row to check + * @param screenColumn The screen column to check + **/ + screenToDocumentPosition(screenRow: number, screenColumn: number): any; + + /** + * Converts document coordinates to screen coordinates. {:conversionConsiderations} + * @param docRow The document row to check + * @param docColumn The document column to check + **/ + documentToScreenPosition(docRow: number, docColumn: number): any; + + /** + * For the given document row and column, returns the screen column. + * @param row + * @param docColumn + **/ + documentToScreenColumn(row: number, docColumn: number): number; + + /** + * For the given document row and column, returns the screen row. + * @param docRow + * @param docColumn + **/ + documentToScreenRow(docRow: number, docColumn: number); + + /** + * Returns the length of the screen. + **/ + getScreenLength(): number; + } + declare var EditSession: { + /** + * Sets up a new `EditSession` and associates it with the given `Document` and `TextMode`. + * @param text [If `text` is a `Document`, it associates the `EditSession` with it. Otherwise, a new `Document` is created, with the initial text]{: #textParam} + * @param mode [The inital language mode to use for the document]{: #modeParam} + **/ + new(text: string, mode?: TextMode): IEditSession; + + new(content: string, mode?: string): IEditSession; + + new (text: string[], mode?: string): IEditSession; + } + + //////////////////////////////// + /// Editor + //////////////////////////////// + + /** + * The main entry point into the Ace functionality. + * The `Editor` manages the [[EditSession]] (which manages [[Document]]s), as well as the [[VirtualRenderer]], which draws everything to the screen. + * Event sessions dealing with the mouse and keyboard are bubbled up from `Document` to the `Editor`, which decides what to do with them. + **/ + export interface Editor { + + inMultiSelectMode: bool; + + selectMoreLines(n: number); + + onTextInput(text: string); + + onCommandKey(e, hashId, keyCode); + + commands: CommandManager; + + session: IEditSession; + + selection: Selection; + + renderer: VirtualRenderer; + + keyBinding: KeyBinding; + + container: HTMLElement; + + onSelectionChange(e); + + onChangeMode(e?); + + execCommand(command:string, args?: any); + + /** + * Sets a new key handler, such as "vim" or "windows". + * @param keyboardHandler The new key handler + **/ + setKeyboardHandler(keyboardHandler: string); + + /** + * Returns the keyboard handler, such as "vim" or "windows". + **/ + getKeyboardHandler(): string; + + /** + * Sets a new editsession to use. This method also emits the `'changeSession'` event. + * @param session The new session to use + **/ + setSession(session: IEditSession); + + /** + * Returns the current session being used. + **/ + getSession(): IEditSession; + + /** + * Sets the current document to `val`. + * @param val The new value to set for the document + * @param cursorPos Where to set the new value. `undefined` or 0 is selectAll, -1 is at the document start, and 1 is at the end + **/ + setValue(val: string, cursorPos?: number): string; + + /** + * Returns the current session's content. + **/ + getValue(): string; + + /** + * Returns the currently highlighted selection. + **/ + getSelection(): Selection; + + /** + * {:VirtualRenderer.onResize} + * @param force If `true`, recomputes the size, even if the height and width haven't changed + **/ + resize(force?: bool); + + /** + * {:VirtualRenderer.setTheme} + * @param theme The path to a theme + **/ + setTheme(theme: string); + + /** + * {:VirtualRenderer.getTheme} + **/ + getTheme(): string; + + /** + * {:VirtualRenderer.setStyle} + * @param style A class name + **/ + setStyle(style: string); + + /** + * {:VirtualRenderer.unsetStyle} + **/ + unsetStyle(); + + /** + * Set a new font size (in pixels) for the editor text. + * @param size A font size ( _e.g._ "12px") + **/ + setFontSize(size: string); + + /** + * Brings the current `textInput` into focus. + **/ + focus(); + + /** + * Returns `true` if the current `textInput` is in focus. + **/ + isFocused(); + + /** + * Blurs the current `textInput`. + **/ + blur(); + + /** + * Emitted once the editor comes into focus. + **/ + onFocus(); + + /** + * Emitted once the editor has been blurred. + **/ + onBlur(); + + /** + * Emitted whenever the document is changed. + * @param e Contains a single property, `data`, which has the delta of changes + **/ + onDocumentChange(e: any); + + /** + * Emitted when the selection changes. + **/ + onCursorChange(); + + /** + * Returns the string of text currently highlighted. + **/ + getCopyText(): string; + + /** + * Called whenever a text "copy" happens. + **/ + onCopy(); + + /** + * Called whenever a text "cut" happens. + **/ + onCut(); + + /** + * Called whenever a text "paste" happens. + * @param text The pasted text + **/ + onPaste(text: string); + + /** + * Inserts `text` into wherever the cursor is pointing. + * @param text The new text to add + **/ + insert(text: string); + + /** + * Pass in `true` to enable overwrites in your session, or `false` to disable. If overwrites is enabled, any text you enter will type over any text after it. If the value of `overwrite` changes, this function also emites the `changeOverwrite` event. + * @param overwrite Defines wheter or not to set overwrites + **/ + setOverwrite(overwrite: bool); + + /** + * Returns `true` if overwrites are enabled; `false` otherwise. + **/ + getOverwrite(): bool; + + /** + * Sets the value of overwrite to the opposite of whatever it currently is. + **/ + toggleOverwrite(); + + /** + * Sets how fast the mouse scrolling should do. + * @param speed A value indicating the new speed (in milliseconds) + **/ + setScrollSpeed(speed: number); + + /** + * Returns the value indicating how fast the mouse scroll speed is (in milliseconds). + **/ + getScrollSpeed(): number; + + /** + * Sets the delay (in milliseconds) of the mouse drag. + * @param dragDelay A value indicating the new delay + **/ + setDragDelay(dragDelay: number); + + /** + * Returns the current mouse drag delay. + **/ + getDragDelay(): number; + + /** + * Indicates how selections should occur. + * By default, selections are set to "line". There are no other styles at the moment, + * although this code change in the future. + * This function also emits the `'changeSelectionStyle'` event. + * @param style The new selection style + **/ + setSelectionStyle(style: string); + + /** + * Returns the current selection style. + **/ + getSelectionStyle(): string; + + /** + * Determines whether or not the current line should be highlighted. + * @param shouldHighlight Set to `true` to highlight the current line + **/ + setHighlightActiveLine(shouldHighlight: bool); + + /** + * Returns `true` if current lines are always highlighted. + **/ + getHighlightActiveLine(); + + /** + * Determines if the currently selected word should be highlighted. + * @param shouldHighlight Set to `true` to highlight the currently selected word + **/ + setHighlightSelectedWord(shouldHighlight: bool); + + /** + * Returns `true` if currently highlighted words are to be highlighted. + **/ + getHighlightSelectedWord(): bool; + + /** + * If `showInvisibiles` is set to `true`, invisible characters—like spaces or new lines—are show in the editor. + * @param showInvisibles Specifies whether or not to show invisible characters + **/ + setShowInvisibles(showInvisibles: bool); + + /** + * Returns `true` if invisible characters are being shown. + **/ + getShowInvisibles(): bool; + + /** + * If `showPrintMargin` is set to `true`, the print margin is shown in the editor. + * @param showPrintMargin Specifies whether or not to show the print margin + **/ + setShowPrintMargin(showPrintMargin: bool); + + /** + * Returns `true` if the print margin is being shown. + **/ + getShowPrintMargin(): bool; + + /** + * Sets the column defining where the print margin should be. + * @param showPrintMargin Specifies the new print margin + **/ + setPrintMarginColumn(showPrintMargin: number); + + /** + * Returns the column number of where the print margin is. + **/ + getPrintMarginColumn(): number; + + /** + * If `readOnly` is true, then the editor is set to read-only mode, and none of the content can change. + * @param readOnly Specifies whether the editor can be modified or not + **/ + setReadOnly(readOnly: bool); + + /** + * Returns `true` if the editor is set to read-only mode. + **/ + getReadOnly(): bool; + + /** + * Specifies whether to use behaviors or not. ["Behaviors" in this case is the auto-pairing of special characters, like quotation marks, parenthesis, or brackets.]{: #BehaviorsDef} + * @param enabled Enables or disables behaviors + **/ + setBehavioursEnabled(enabled: bool); + + /** + * Returns `true` if the behaviors are currently enabled. {:BehaviorsDef} + **/ + getBehavioursEnabled(): bool; + + /** + * Specifies whether to use wrapping behaviors or not, i.e. automatically wrapping the selection with characters such as brackets + * when such a character is typed in. + * @param enabled Enables or disables wrapping behaviors + **/ + setWrapBehavioursEnabled(enabled: bool); + + /** + * Returns `true` if the wrapping behaviors are currently enabled. + **/ + getWrapBehavioursEnabled(); + + /** + * Indicates whether the fold widgets are shown or not. + * @param show Specifies whether the fold widgets are shown + **/ + setShowFoldWidgets(show: bool); + + /** + * Returns `true` if the fold widgets are shown. + **/ + getShowFoldWidgets(); + + /** + * Removes words of text from the editor. A "word" is defined as a string of characters bookended by whitespace. + * @param dir The direction of the deletion to occur, either "left" or "right" + **/ + remove(dir: string); + + /** + * Removes the word directly to the right of the current selection. + **/ + removeWordRight(); + + /** + * Removes the word directly to the left of the current selection. + **/ + removeWordLeft(); + + /** + * Removes all the words to the left of the current selection, until the start of the line. + **/ + removeToLineStart(); + + /** + * Removes all the words to the right of the current selection, until the end of the line. + **/ + removeToLineEnd(); + + /** + * Splits the line at the current selection (by inserting an `'\n'`). + **/ + splitLine(); + + /** + * Transposes current line. + **/ + transposeLetters(); + + /** + * Converts the current selection entirely into lowercase. + **/ + toLowerCase(); + + /** + * Converts the current selection entirely into uppercase. + **/ + toUpperCase(); + + /** + * Inserts an indentation into the current cursor position or indents the selected lines. + **/ + indent(); + + /** + * Indents the current line. + **/ + blockIndent(); + + /** + * Outdents the current line. + **/ + blockOutdent(arg?: string); + + /** + * Given the currently selected range, this function either comments all the lines, or uncomments all of them. + **/ + toggleCommentLines(); + + /** + * Works like [[EditSession.getTokenAt]], except it returns a number. + **/ + getNumberAt(): number; + + /** + * If the character before the cursor is a number, this functions changes its value by `amount`. + * @param amount The value to change the numeral by (can be negative to decrease value) + **/ + modifyNumber(amount: number); + + /** + * Removes all the lines in the current selection + **/ + removeLines(); + + /** + * Shifts all the selected lines down one row. + **/ + moveLinesDown(): number; + + /** + * Shifts all the selected lines up one row. + **/ + moveLinesUp(): number; + + /** + * Moves a range of text from the given range to the given position. `toPosition` is an object that looks like this: + * ```json + * { row: newRowLocation, column: newColumnLocation } + * ``` + * @param fromRange The range of text you want moved within the document + * @param toPosition The location (row and column) where you want to move the text to + **/ + moveText(fromRange: Range, toPosition: any): Range; + + /** + * Copies all the selected lines up one row. + **/ + copyLinesUp(): number; + + /** + * Copies all the selected lines down one row. + **/ + copyLinesDown(): number; + + /** + * {:VirtualRenderer.getFirstVisibleRow} + **/ + getFirstVisibleRow(): number; + + /** + * {:VirtualRenderer.getLastVisibleRow} + **/ + getLastVisibleRow(): number; + + /** + * Indicates if the row is currently visible on the screen. + * @param row The row to check + **/ + isRowVisible(row: number): bool; + + /** + * Indicates if the entire row is currently visible on the screen. + * @param row The row to check + **/ + isRowFullyVisible(row: number): bool; + + /** + * Selects the text from the current position of the document until where a "page down" finishes. + **/ + selectPageDown(); + + /** + * Selects the text from the current position of the document until where a "page up" finishes. + **/ + selectPageUp(); + + /** + * Shifts the document to wherever "page down" is, as well as moving the cursor position. + **/ + gotoPageDown(); + + /** + * Shifts the document to wherever "page up" is, as well as moving the cursor position. + **/ + gotoPageUp(); + + /** + * Scrolls the document to wherever "page down" is, without changing the cursor position. + **/ + scrollPageDown(); + + /** + * Scrolls the document to wherever "page up" is, without changing the cursor position. + **/ + scrollPageUp(); + + /** + * Moves the editor to the specified row. + **/ + scrollToRow(); + + /** + * Scrolls to a line. If `center` is `true`, it puts the line in middle of screen (or attempts to). + * @param line The line to scroll to + * @param center If `true` + * @param animate If `true` animates scrolling + * @param callback Function to be called when the animation has finished + **/ + scrollToLine(line: number, center: bool, animate: bool, callback: Function); + + /** + * Attempts to center the current selection on the screen. + **/ + centerSelection(); + + /** + * Gets the current position of the cursor. + **/ + getCursorPosition(): Position; + + /** + * Returns the screen position of the cursor. + **/ + getCursorPositionScreen(): number; + + /** + * {:Selection.getRange} + **/ + getSelectionRange(): Range; + + /** + * Selects all the text in editor. + **/ + selectAll(); + + /** + * {:Selection.clearSelection} + **/ + clearSelection(); + + /** + * Moves the cursor to the specified row and column. Note that this does not de-select the current selection. + * @param row The new row number + * @param column The new column number + **/ + moveCursorTo(row: number, column?: number, animate?:bool); + + /** + * Moves the cursor to the position indicated by `pos.row` and `pos.column`. + * @param position An object with two properties, row and column + **/ + moveCursorToPosition(position: Position); + + /** + * Moves the cursor's row and column to the next matching bracket. + **/ + jumpToMatching(); + + /** + * Moves the cursor to the specified line number, and also into the indiciated column. + * @param lineNumber The line number to go to + * @param column A column number to go to + * @param animate If `true` animates scolling + **/ + gotoLine(lineNumber: number, column?: number, animate?: bool); + + /** + * Moves the cursor to the specified row and column. Note that this does de-select the current selection. + * @param row The new row number + * @param column The new column number + **/ + navigateTo(row: number, column: number); + + /** + * Moves the cursor up in the document the specified number of times. Note that this does de-select the current selection. + * @param times The number of times to change navigation + **/ + navigateUp(times?: number); + + /** + * Moves the cursor down in the document the specified number of times. Note that this does de-select the current selection. + * @param times The number of times to change navigation + **/ + navigateDown(times?: number); + + /** + * Moves the cursor left in the document the specified number of times. Note that this does de-select the current selection. + * @param times The number of times to change navigation + **/ + navigateLeft(times?: number); + + /** + * Moves the cursor right in the document the specified number of times. Note that this does de-select the current selection. + * @param times The number of times to change navigation + **/ + navigateRight(times: number); + + /** + * Moves the cursor to the start of the current line. Note that this does de-select the current selection. + **/ + navigateLineStart(); + + /** + * Moves the cursor to the end of the current line. Note that this does de-select the current selection. + **/ + navigateLineEnd(); + + /** + * Moves the cursor to the end of the current file. Note that this does de-select the current selection. + **/ + navigateFileEnd(); + + /** + * Moves the cursor to the start of the current file. Note that this does de-select the current selection. + **/ + navigateFileStart(); + + /** + * Moves the cursor to the word immediately to the right of the current position. Note that this does de-select the current selection. + **/ + navigateWordRight(); + + /** + * Moves the cursor to the word immediately to the left of the current position. Note that this does de-select the current selection. + **/ + navigateWordLeft(); + + /** + * Replaces the first occurance of `options.needle` with the value in `replacement`. + * @param replacement The text to replace with + * @param options The [[Search `Search`]] options to use + **/ + replace(replacement: string, options?: any); + + /** + * Replaces all occurances of `options.needle` with the value in `replacement`. + * @param replacement The text to replace with + * @param options The [[Search `Search`]] options to use + **/ + replaceAll(replacement: string, options?: any); + + /** + * {:Search.getOptions} For more information on `options`, see [[Search `Search`]]. + **/ + getLastSearchOptions(): any; + + /** + * Attempts to find `needle` within the document. For more information on `options`, see [[Search `Search`]]. + * @param needle The text to search for (optional) + * @param options An object defining various search properties + * @param animate If `true` animate scrolling + **/ + find(needle: string, options?: any, animate?: bool); + + /** + * Performs another search for `needle` in the document. For more information on `options`, see [[Search `Search`]]. + * @param options search options + * @param animate If `true` animate scrolling + **/ + findNext(options?: any, animate?: bool); + + /** + * Performs a search for `needle` backwards. For more information on `options`, see [[Search `Search`]]. + * @param options search options + * @param animate If `true` animate scrolling + **/ + findPrevious(options?: any, animate?: bool); + + /** + * {:UndoManager.undo} + **/ + undo(); + + /** + * {:UndoManager.redo} + **/ + redo(); + + /** + * Cleans up the entire editor. + **/ + destroy(); + + } + + declare var Editor: { + /** + * Creates a new `Editor` object. + * @param renderer Associated `VirtualRenderer` that draws everything + * @param session The `EditSession` to refer to + **/ + new(renderer: VirtualRenderer, session?: IEditSession): Editor; + } + + //////////////////////////////// + /// PlaceHolder + //////////////////////////////// + + export interface PlaceHolder { + + on(event: string, fn: (e) => any); + + /** + * PlaceHolder.setup() + * TODO + **/ + setup(); + + /** + * PlaceHolder.showOtherMarkers() + * TODO + **/ + showOtherMarkers(); + + /** + * PlaceHolder.hideOtherMarkers() + * Hides all over markers in the [[EditSession `EditSession`]] that are not the currently selected one. + **/ + hideOtherMarkers(); + + /** + * PlaceHolder@onUpdate(e) + * Emitted when the place holder updates. + **/ + onUpdate(); + + /** + * PlaceHolder@onCursorChange(e) + * Emitted when the cursor changes. + **/ + onCursorChange(); + + /** + * PlaceHolder.detach() + * TODO + **/ + detach(); + + /** + * PlaceHolder.cancel() + * TODO + **/ + cancel(); + } + declare var PlaceHolder: { + /** + * - @param session (Document): The document to associate with the anchor + * - @param length (Number): The starting row position + * - @param pos (Number): The starting column position + * - @param others (String): + * - @param mainClass (String): + * - @param othersClass (String): + **/ + new (session: Document, length: number, pos: number, others: string, mainClass: string, othersClass: string): PlaceHolder; + + new (session: IEditSession, length: number, pos: Position, positions: Position[]): PlaceHolder; + } + + //////////////// + /// RangeList + //////////////// + + export interface IRangeList { + ranges: Range[]; + + pointIndex(pos: Position, startIndex?: number); + + addList(ranges: Range[]); + + add(ranges: Range); + + merge(): Range[]; + + substractPoint(pos: Position); + } + export var RangeList: { + new (): IRangeList; + } + + //////////////// + /// Range + //////////////// + + /** + * This object is used in various places to indicate a region within the editor. To better visualize how this works, imagine a rectangle. Each quadrant of the rectangle is analogus to a range, as ranges contain a starting row and starting column, and an ending row, and ending column. + **/ + export interface Range { + + startRow:number; + + startColumn:number; + + endRow:number; + + endColumn:number; + + start: Position; + + end: Position; + + isEmpty(): bool; + + /** + * Returns `true` if and only if the starting row and column, and ending row and column, are equivalent to those given by `range`. + * @param range A range to check against + **/ + isEqual(range: Range); + + /** + * Returns a string containing the range's row and column information, given like this: + * ``` + * [start.row/start.column] -> [end.row/end.column] + * ``` + **/ + toString(); + + /** + * Returns `true` if the `row` and `column` provided are within the given range. This can better be expressed as returning `true` if: + * ```javascript + * this.start.row <= row <= this.end.row && + * this.start.column <= column <= this.end.column + * ``` + * @param row A row to check for + * @param column A column to check for + **/ + contains(row: number, column: number): bool; + + /** + * Compares `this` range (A) with another range (B). + * @param range A range to compare with + **/ + compareRange(range: Range): number; + + /** + * Checks the row and column points of `p` with the row and column points of the calling range. + * @param p A point to compare with + **/ + comparePoint(p: Range): number; + + /** + * Checks the start and end points of `range` and compares them to the calling range. Returns `true` if the `range` is contained within the caller's range. + * @param range A range to compare with + **/ + containsRange(range: Range): bool; + + /** + * Returns `true` if passed in `range` intersects with the one calling this method. + * @param range A range to compare with + **/ + intersects(range: Range): bool; + + /** + * Returns `true` if the caller's ending row point is the same as `row`, and if the caller's ending column is the same as `column`. + * @param row A row point to compare with + * @param column A column point to compare with + **/ + isEnd(row: number, column: number): bool; + + /** + * Returns `true` if the caller's starting row point is the same as `row`, and if the caller's starting column is the same as `column`. + * @param row A row point to compare with + * @param column A column point to compare with + **/ + isStart(row: number, column: number): bool; + + /** + * Sets the starting row and column for the range. + * @param row A row point to set + * @param column A column point to set + **/ + setStart(row: number, column: number); + + /** + * Sets the starting row and column for the range. + * @param row A row point to set + * @param column A column point to set + **/ + setEnd(row: number, column: number); + + /** + * Returns `true` if the `row` and `column` are within the given range. + * @param row A row point to compare with + * @param column A column point to compare with + **/ + inside(row: number, column: number): bool; + + /** + * Returns `true` if the `row` and `column` are within the given range's starting points. + * @param row A row point to compare with + * @param column A column point to compare with + **/ + insideStart(row: number, column: number): bool; + + /** + * Returns `true` if the `row` and `column` are within the given range's ending points. + * @param row A row point to compare with + * @param column A column point to compare with + **/ + insideEnd(row: number, column: number): bool; + + /** + * Checks the row and column points with the row and column points of the calling range. + * @param row A row point to compare with + * @param column A column point to compare with + **/ + compare(row: number, column: number): number; + + /** + * Checks the row and column points with the row and column points of the calling range. + * @param row A row point to compare with + * @param column A column point to compare with + **/ + compareStart(row: number, column: number): number; + + /** + * Checks the row and column points with the row and column points of the calling range. + * @param row A row point to compare with + * @param column A column point to compare with + **/ + compareEnd(row: number, column: number): number; + + /** + * Checks the row and column points with the row and column points of the calling range. + * @param row A row point to compare with + * @param column A column point to compare with + **/ + compareInside(row: number, column: number): number; + + /** + * Returns the part of the current `Range` that occurs within the boundaries of `firstRow` and `lastRow` as a new `Range` object. + * @param firstRow The starting row + * @param lastRow The ending row + **/ + clipRows(firstRow: number, lastRow: number): Range; + + /** + * Changes the row and column points for the calling range for both the starting and ending points. + * @param row A new row to extend to + * @param column A new column to extend to + **/ + extend(row: number, column: number): Range; + + /** + * Returns `true` if the range spans across multiple lines. + **/ + isMultiLine(): bool; + + /** + * Returns a duplicate of the calling range. + **/ + clone(): Range; + + /** + * Returns a range containing the starting and ending rows of the original range, but with a column value of `0`. + **/ + collapseRows(): Range; + + /** + * Given the current `Range`, this function converts those starting and ending points into screen positions, and then returns a new `Range` object. + * @param session The `EditSession` to retrieve coordinates from + **/ + toScreenRange(session: IEditSession): Range; + + /** + * Creates and returns a new `Range` based on the row and column of the given parameters. + * @param start A starting point to use + * @param end An ending point to use + **/ + fromPoints(start: Range, end: Range): Range; + + } + /** + * Creates a new `Range` object with the given starting and ending row and column points. + * @param startRow The starting row + * @param startColumn The starting column + * @param endRow The ending row + * @param endColumn The ending column + **/ + declare var Range: { + fromPoints(pos1: Position, pos2: Position): Range; + new(startRow: number, startColumn: number, endRow: number, endColumn: number): Range; + } + + //////////////// + /// RenderLoop + //////////////// + + export interface RenderLoop { } + declare var RenderLoop: { + new(): RenderLoop; + } + + //////////////// + /// ScrollBar + //////////////// + + /** + * A set of methods for setting and retrieving the editor's scrollbar. + **/ + export interface ScrollBar { + + /** + * Emitted when the scroll bar, well, scrolls. + * @param e Contains one property, `"data"`, which indicates the current scroll top position + **/ + onScroll(e: any); + + /** + * Returns the width of the scroll bar. + **/ + getWidth(): number; + + /** + * Sets the height of the scroll bar, in pixels. + * @param height The new height + **/ + setHeight(height: number); + + /** + * Sets the inner height of the scroll bar, in pixels. + * @param height The new inner height + **/ + setInnerHeight(height: number); + + /** + * Sets the scroll top of the scroll bar. + * @param scrollTop The new scroll top + **/ + setScrollTop(scrollTop: number); + } + declare var ScrollBar: { + /** + * Creates a new `ScrollBar`. `parent` is the owner of the scroll bar. + * @param parent A DOM element + **/ + new(parent: HTMLElement): ScrollBar; + } + + //////////////// + /// Search + //////////////// + + /** + * A class designed to handle all sorts of text searches within a [[Document `Document`]]. + **/ + export interface Search { + + /** + * Sets the search options via the `options` parameter. + * @param options An object containing all the new search properties + **/ + set(options: any): Search; + + /** + * [Returns an object containing all the search options.]{: #Search.getOptions} + **/ + getOptions(): any; + + /** + * Sets the search options via the `options` parameter. + * @param An object containing all the search propertie + **/ + setOptions(An: any); + + /** + * Searches for `options.needle`. If found, this method returns the [[Range `Range`]] where the text first occurs. If `options.backwards` is `true`, the search goes backwards in the session. + * @param session The session to search with + **/ + find(session: IEditSession): Range; + + /** + * Searches for all occurances `options.needle`. If found, this method returns an array of [[Range `Range`s]] where the text first occurs. If `options.backwards` is `true`, the search goes backwards in the session. + * @param session The session to search with + **/ + findAll(session: IEditSession): Range[]; + + /** + * Searches for `options.needle` in `input`, and, if found, replaces it with `replacement`. + * @param input The text to search in + * @param replacement The replacing text + * + (String): If `options.regExp` is `true`, this function returns `input` with the replacement already made. Otherwise, this function just returns `replacement`.
+ * If `options.needle` was not found, this function returns `null`. + **/ + replace(input: string, replacement: string): string; + } + declare var Search: { + /** + * Creates a new `Search` object. The following search options are avaliable: + * - `needle`: The string or regular expression you're looking for + * - `backwards`: Whether to search backwards from where cursor currently is. Defaults to `false`. + * - `wrap`: Whether to wrap the search back to the beginning when it hits the end. Defaults to `false`. + * - `caseSensitive`: Whether the search ought to be case-sensitive. Defaults to `false`. + * - `wholeWord`: Whether the search matches only on whole words. Defaults to `false`. + * - `range`: The [[Range]] to search within. Set this to `null` for the whole document + * - `regExp`: Whether the search is a regular expression or not. Defaults to `false`. + * - `start`: The starting [[Range]] or cursor position to begin the search + * - `skipCurrent`: Whether or not to include the current line in the search. Default to `false`. + **/ + new(): Search; + } + + //////////////// + /// Search + //////////////// + + /** + * Contains the cursor position and the text selection of an edit session. + * The row/columns used in the selection are in document coordinates representing ths coordinates as thez appear in the document before applying soft wrap and folding. + **/ + export interface Selection { + + addEventListener(ev: string, callback: Function); + + moveCursorWordLeft(); + + moveCursorWordRight(); + + fromOrientedRange(range: Range); + + setSelectionRange(match); + + getAllRanges(): Range[]; + + on(event: string, fn: (e) => any); + + addRange(range: Range); + + /** + * Returns `true` if the selection is empty. + **/ + isEmpty(): bool; + + /** + * Returns `true` if the selection is a multi-line. + **/ + isMultiLine(): bool; + + /** + * Gets the current position of the cursor. + **/ + getCursor(): number; + + /** + * Sets the row and column position of the anchor. This function also emits the `'changeSelection'` event. + * @param row The new row + * @param column The new column + **/ + setSelectionAnchor(row: number, column: number); + + /** + * Returns an object containing the `row` and `column` of the calling selection anchor. + **/ + getSelectionAnchor(): any; + + /** + * Returns an object containing the `row` and `column` of the calling selection lead. + **/ + getSelectionLead(): any; + + /** + * Shifts the selection up (or down, if [[Selection.isBackwards `isBackwards()`]] is true) the given number of columns. + * @param columns The number of columns to shift by + **/ + shiftSelection(columns: number); + + /** + * Returns `true` if the selection is going backwards in the document. + **/ + isBackwards(): bool; + + /** + * [Returns the [[Range]] for the selected text.]{: #Selection.getRange} + **/ + getRange(): Range; + + /** + * [Empties the selection (by de-selecting it). This function also emits the `'changeSelection'` event.]{: #Selection.clearSelection} + **/ + clearSelection(); + + /** + * Selects all the text in the document. + **/ + selectAll(); + + /** + * Sets the selection to the provided range. + * @param range The range of text to select + * @param reverse Indicates if the range should go backwards (`true`) or not + **/ + setRange(range: Range, reverse: bool); + + /** + * Moves the selection cursor to the indicated row and column. + * @param row The row to select to + * @param column The column to select to + **/ + selectTo(row: number, column: number); + + /** + * Moves the selection cursor to the row and column indicated by `pos`. + * @param pos An object containing the row and column + **/ + selectToPosition(pos: any); + + /** + * Moves the selection up one row. + **/ + selectUp(); + + /** + * Moves the selection down one row. + **/ + selectDown(); + + /** + * Moves the selection right one column. + **/ + selectRight(); + + /** + * Moves the selection left one column. + **/ + selectLeft(); + + /** + * Moves the selection to the beginning of the current line. + **/ + selectLineStart(); + + /** + * Moves the selection to the end of the current line. + **/ + selectLineEnd(); + + /** + * Moves the selection to the end of the file. + **/ + selectFileEnd(); + + /** + * Moves the selection to the start of the file. + **/ + selectFileStart(); + + /** + * Moves the selection to the first word on the right. + **/ + selectWordRight(); + + /** + * Moves the selection to the first word on the left. + **/ + selectWordLeft(); + + /** + * Moves the selection to highlight the entire word. + **/ + getWordRange(); + + /** + * Selects an entire word boundary. + **/ + selectWord(); + + /** + * Selects a word, including its right whitespace. + **/ + selectAWord(); + + /** + * Selects the entire line. + **/ + selectLine(); + + /** + * Moves the cursor up one row. + **/ + moveCursorUp(); + + /** + * Moves the cursor down one row. + **/ + moveCursorDown(); + + /** + * Moves the cursor left one column. + **/ + moveCursorLeft(); + + /** + * Moves the cursor right one column. + **/ + moveCursorRight(); + + /** + * Moves the cursor to the start of the line. + **/ + moveCursorLineStart(); + + /** + * Moves the cursor to the end of the line. + **/ + moveCursorLineEnd(); + + /** + * Moves the cursor to the end of the file. + **/ + moveCursorFileEnd(); + + /** + * Moves the cursor to the start of the file. + **/ + moveCursorFileStart(); + + /** + * Moves the cursor to the word on the right. + **/ + moveCursorLongWordRight(); + + /** + * Moves the cursor to the word on the left. + **/ + moveCursorLongWordLeft(); + + /** + * Moves the cursor to position indicated by the parameters. Negative numbers move the cursor backwards in the document. + * @param rows The number of rows to move by + * @param chars The number of characters to move by + **/ + moveCursorBy(rows: number, chars: number); + + /** + * Moves the selection to the position indicated by its `row` and `column`. + * @param position The position to move to + **/ + moveCursorToPosition(position: any); + + /** + * Moves the cursor to the row and column provided. [If `preventUpdateDesiredColumn` is `true`, then the cursor stays in the same column position as its original point.]{: #preventUpdateBoolDesc} + * @param row The row to move to + * @param column The column to move to + * @param keepDesiredColumn [If `true`, the cursor move does not respect the previous column]{: #preventUpdateBool} + **/ + moveCursorTo(row: number, column: number, keepDesiredColumn?: bool); + + /** + * Moves the cursor to the screen position indicated by row and column. {:preventUpdateBoolDesc} + * @param row The row to move to + * @param column The column to move to + * @param keepDesiredColumn {:preventUpdateBool} + **/ + moveCursorToScreen(row: number, column: number, keepDesiredColumn: bool); + } + declare var Selection: { + /** + * Creates a new `Selection` object. + * @param session The session to use + **/ + new(session: IEditSession): Selection; + } + + //////////////// + /// Split + //////////////// + + export interface Split { + + /** + * Returns the number of splits. + **/ + getSplits(): number; + + /** + * Returns the editor identified by the index `idx`. + * @param idx The index of the editor you want + **/ + getEditor(idx: number); + + /** + * Returns the current editor. + **/ + getCurrentEditor(): Editor; + + /** + * Focuses the current editor. + **/ + focus(); + + /** + * Blurs the current editor. + **/ + blur(); + + /** + * Sets a theme for each of the available editors. + * @param theme The name of the theme to set + **/ + setTheme(theme: string); + + /** + * Sets the keyboard handler for the editor. + * @param keybinding + **/ + setKeyboardHandler(keybinding: string); + + /** + * Executes `callback` on all of the available editors. + * @param callback A callback function to execute + * @param scope The default scope for the callback + **/ + forEach(callback: Function, scope: string); + + /** + * Sets the font size, in pixels, for all the available editors. + * @param size The new font size + **/ + setFontSize(size: number); + + /** + * Sets a new [[EditSession `EditSession`]] for the indicated editor. + * @param session The new edit session + * @param idx The editor's index you're interested in + **/ + setSession(session: IEditSession, idx: number); + + /** + * Returns the orientation. + **/ + getOrientation(): number; + + /** + * Sets the orientation. + * @param orientation The new orientation value + **/ + setOrientation(orientation: number); + + /** + * Resizes the editor. + **/ + resize(); + } + declare var Split: { + new(): Split; + } + + ////////////////// + /// TokenIterator + ////////////////// + + /** + * This class provides an essay way to treat the document as a stream of tokens, and provides methods to iterate over these tokens. + **/ + export interface TokenIterator { + + /** + * Tokenizes all the items from the current point to the row prior in the document. + **/ + stepBackward(): string[]; + + /** + * Tokenizes all the items from the current point until the next row in the document. If the current point is at the end of the file, this function returns `null`. Otherwise, it returns the tokenized string. + **/ + stepForward(): string; + + /** + * Returns the current tokenized string. + **/ + getCurrentToken(): TokenInfo; + + /** + * Returns the current row. + **/ + getCurrentTokenRow(): number; + + /** + * Returns the current column. + **/ + getCurrentTokenColumn(): number; + } + declare var TokenIterator: { + /** + * Creates a new token iterator object. The inital token index is set to the provided row and column coordinates. + * @param session The session to associate with + * @param initialRow The row to start the tokenizing at + * @param initialColumn The column to start the tokenizing at + **/ + new(session: IEditSession, initialRow: number, initialColumn: number): TokenIterator; + } + + ////////////////// + /// Tokenizer + ////////////////// + + + /** + * This class takes a set of highlighting rules, and creates a tokenizer out of them. For more information, see [the wiki on extending highlighters](https://github.com/ajaxorg/ace/wiki/Creating-or-Extending-an-Edit-Mode#wiki-extendingTheHighlighter). + **/ + export interface Tokenizer { + + /** + * Returns an object containing two properties: `tokens`, which contains all the tokens; and `state`, the current state. + **/ + getLineTokens(): any; + } + declare var Tokenizer: { + /** + * Constructs a new tokenizer based on the given rules and flags. + * @param rules The highlighting rules + * @param flag Any additional regular expression flags to pass (like "i" for case insensitive) + **/ + new(rules: any, flag: string): Tokenizer; + } + + ////////////////// + /// UndoManager + ////////////////// + + /** + * This object maintains the undo stack for an [[EditSession `EditSession`]]. + **/ + export interface UndoManager { + + /** + * Provides a means for implementing your own undo manager. `options` has one property, `args`, an [[Array `Array`]], with two elements: + * - `args[0]` is an array of deltas + * - `args[1]` is the document to associate with + * @param options Contains additional properties + **/ + execute(options: any); + + /** + * [Perform an undo operation on the document, reverting the last change.]{: #UndoManager.undo} + * @param dontSelect {:dontSelect} + **/ + undo(dontSelect?: bool): Range; + + /** + * [Perform a redo operation on the document, reimplementing the last change.]{: #UndoManager.redo} + * @param dontSelect {:dontSelect} + **/ + redo(dontSelect: bool); + + /** + * Destroys the stack of undo and redo redo operations. + **/ + reset(); + + /** + * Returns `true` if there are undo operations left to perform. + **/ + hasUndo(): bool; + + /** + * Returns `true` if there are redo operations left to perform. + **/ + hasRedo(): bool; + + } + declare var UndoManager: { + /** + * Resets the current undo state and creates a new `UndoManager`. + **/ + new(): UndoManager; + } + + //////////////////// + /// VirtualRenderer + //////////////////// + + /** + * The class that is responsible for drawing everything you see on the screen! + **/ + export interface VirtualRenderer { + + scroller: any; + + characterWidth: number; + + lineHeight: number; + + screenToTextCoordinates(left: number, top: number); + + /** + * Associates the renderer with an [[EditSession `EditSession`]]. + **/ + setSession(session: IEditSession); + + /** + * Triggers a partial update of the text, from the range given by the two parameters. + * @param firstRow The first row to update + * @param lastRow The last row to update + **/ + updateLines(firstRow: number, lastRow: number); + + /** + * Triggers a full update of the text, for all the rows. + **/ + updateText(); + + /** + * Triggers a full update of all the layers, for all the rows. + * @param force If `true`, forces the changes through + **/ + updateFull(force: bool); + + /** + * Updates the font size. + **/ + updateFontSize(); + + /** + * [Triggers a resize of the editor.]{: #VirtualRenderer.onResize} + * @param force If `true`, recomputes the size, even if the height and width haven't changed + * @param gutterWidth The width of the gutter in pixels + * @param width The width of the editor in pixels + * @param height The hiehgt of the editor, in pixels + **/ + onResize(force: bool, gutterWidth: number, width: number, height: number); + + /** + * Adjusts the wrap limit, which is the number of characters that can fit within the width of the edit area on screen. + **/ + adjustWrapLimit(); + + /** + * Identifies whether you want to have an animated scroll or not. + * @param shouldAnimate Set to `true` to show animated scrolls + **/ + setAnimatedScroll(shouldAnimate: bool); + + /** + * Returns whether an animated scroll happens or not. + **/ + getAnimatedScroll(): bool; + + /** + * Identifies whether you want to show invisible characters or not. + * @param showInvisibles Set to `true` to show invisibles + **/ + setShowInvisibles(showInvisibles: bool); + + /** + * Returns whether invisible characters are being shown or not. + **/ + getShowInvisibles(): bool; + + /** + * Identifies whether you want to show the print margin or not. + * @param showPrintMargin Set to `true` to show the print margin + **/ + setShowPrintMargin(showPrintMargin: bool); + + /** + * Returns whether the print margin is being shown or not. + **/ + getShowPrintMargin(): bool; + + /** + * Identifies whether you want to show the print margin column or not. + * @param showPrintMargin Set to `true` to show the print margin column + **/ + setPrintMarginColumn(showPrintMargin: bool); + + /** + * Returns whether the print margin column is being shown or not. + **/ + getPrintMarginColumn(): bool; + + /** + * Returns `true` if the gutter is being shown. + **/ + getShowGutter(): bool; + + /** + * Identifies whether you want to show the gutter or not. + * @param show Set to `true` to show the gutter + **/ + setShowGutter(show: bool); + + /** + * Returns the root element containing this renderer. + **/ + getContainerElement(): HTMLElement; + + /** + * Returns the element that the mouse events are attached to + **/ + getMouseEventTarget(): HTMLElement; + + /** + * Returns the element to which the hidden text area is added. + **/ + getTextAreaContainer(): HTMLElement; + + /** + * [Returns the index of the first visible row.]{: #VirtualRenderer.getFirstVisibleRow} + **/ + getFirstVisibleRow(): number; + + /** + * Returns the index of the first fully visible row. "Fully" here means that the characters in the row are not truncated; that the top and the bottom of the row are on the screen. + **/ + getFirstFullyVisibleRow(): number; + + /** + * Returns the index of the last fully visible row. "Fully" here means that the characters in the row are not truncated; that the top and the bottom of the row are on the screen. + **/ + getLastFullyVisibleRow(): number; + + /** + * [Returns the index of the last visible row.]{: #VirtualRenderer.getLastVisibleRow} + **/ + getLastVisibleRow(): number; + + /** + * Sets the padding for all the layers. + * @param padding A new padding value (in pixels) + **/ + setPadding(padding: number); + + /** + * Returns whether the horizontal scrollbar is set to be always visible. + **/ + getHScrollBarAlwaysVisible(): bool; + + /** + * Identifies whether you want to show the horizontal scrollbar or not. + * @param alwaysVisible Set to `true` to make the horizontal scroll bar visible + **/ + setHScrollBarAlwaysVisible(alwaysVisible: bool); + + /** + * Schedules an update to all the front markers in the document. + **/ + updateFrontMarkers(); + + /** + * Schedules an update to all the back markers in the document. + **/ + updateBackMarkers(); + + /** + * Deprecated; (moved to [[EditSession]]) + **/ + addGutterDecoration(); + + /** + * Deprecated; (moved to [[EditSession]]) + **/ + removeGutterDecoration(); + + /** + * Redraw breakpoints. + **/ + updateBreakpoints(); + + /** + * Sets annotations for the gutter. + * @param annotations An array containing annotations + **/ + setAnnotations(annotations: Array); + + /** + * Updates the cursor icon. + **/ + updateCursor(); + + /** + * Hides the cursor icon. + **/ + hideCursor(); + + /** + * Shows the cursor icon. + **/ + showCursor(); + + /** + * Scrolls the cursor into the first visibile area of the editor + **/ + scrollCursorIntoView(); + + /** + * {:EditSession.getScrollTop} + **/ + getScrollTop(): number; + + /** + * {:EditSession.getScrollLeft} + **/ + getScrollLeft(): number; + + /** + * Returns the first visible row, regardless of whether it's fully visible or not. + **/ + getScrollTopRow(): number; + + /** + * Returns the last visible row, regardless of whether it's fully visible or not. + **/ + getScrollBottomRow(): number; + + /** + * Gracefully scrolls from the top of the editor to the row indicated. + * @param row A row id + **/ + scrollToRow(row: number); + + /** + * Gracefully scrolls the editor to the row indicated. + * @param line A line number + * @param center If `true`, centers the editor the to indicated line + * @param animate If `true` animates scrolling + * @param callback Function to be called after the animation has finished + **/ + scrollToLine(line: number, center: bool, animate: bool, callback: Function); + + /** + * Scrolls the editor to the y pixel indicated. + * @param scrollTop The position to scroll to + **/ + scrollToY(scrollTop: number): number; + + /** + * Scrolls the editor across the x-axis to the pixel indicated. + * @param scrollLeft The position to scroll to + **/ + scrollToX(scrollLeft: number): number; + + /** + * Scrolls the editor across both x- and y-axes. + * @param deltaX The x value to scroll by + * @param deltaY The y value to scroll by + **/ + scrollBy(deltaX: number, deltaY: number); + + /** + * Returns `true` if you can still scroll by either parameter; in other words, you haven't reached the end of the file or line. + * @param deltaX The x value to scroll by + * @param deltaY The y value to scroll by + **/ + isScrollableBy(deltaX: number, deltaY: number): bool; + + /** + * Returns an object containing the `pageX` and `pageY` coordinates of the document position. + * @param row The document row position + * @param column The document column position + **/ + textToScreenCoordinates(row: number, column: number): any; + + /** + * Focuses the current container. + **/ + visualizeFocus(); + + /** + * Blurs the current container. + **/ + visualizeBlur(); + + /** + * undefined + * @param position + **/ + showComposition(position: number); + + /** + * Sets the inner text of the current composition to `text`. + * @param text A string of text to use + **/ + setCompositionText(text: string); + + /** + * Hides the current composition. + **/ + hideComposition(); + + /** + * [Sets a new theme for the editor. `theme` should exist, and be a directory path, like `ace/theme/textmate`.]{: #VirtualRenderer.setTheme} + * @param theme The path to a theme + **/ + setTheme(theme: string); + + /** + * [Returns the path of the current theme.]{: #VirtualRenderer.getTheme} + **/ + getTheme(): string; + + /** + * [Adds a new class, `style`, to the editor.]{: #VirtualRenderer.setStyle} + * @param style A class name + **/ + setStyle(style: string); + + /** + * [Removes the class `style` from the editor.]{: #VirtualRenderer.unsetStyle} + * @param style A class name + **/ + unsetStyle(style: string); + + /** + * Destroys the text and cursor layers for this renderer. + **/ + destroy(); + + } + declare var VirtualRenderer: { + /** + * Constructs a new `VirtualRenderer` within the `container` specified, applying the given `theme`. + * @param container The root element of the editor + * @param theme The starting theme + **/ + new(container: HTMLElement, theme?: string): VirtualRenderer; + } +} + +declare var ace: AceAjax.Ace; \ No newline at end of file diff --git a/ace/all-tests.ts b/ace/all-tests.ts new file mode 100644 index 0000000000..80717ac5da --- /dev/null +++ b/ace/all-tests.ts @@ -0,0 +1,26 @@ +/// + +var exports: any; +var assert: any; +var MockRenderer = null; +var JavaScriptMode = null; + +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// + + + diff --git a/ace/tests/ace-anchor-tests.ts b/ace/tests/ace-anchor-tests.ts new file mode 100644 index 0000000000..40e81600ab --- /dev/null +++ b/ace/tests/ace-anchor-tests.ts @@ -0,0 +1,131 @@ +/// + +exports = { + + "test create anchor" : function() { + var doc = new AceAjax.Document("juhu"); + var anchor = new AceAjax.Anchor(doc, 0, 0); + + assert.position(anchor.getPosition(), 0, 0); + assert.equal(anchor.getDocument(), doc); + }, + + "test insert text in same row before cursor should move anchor column": function() { + var doc = new AceAjax.Document("juhu\nkinners"); + var anchor = new AceAjax.Anchor(doc, 1, 4); + + doc.insert({row: 1, column: 1}, "123"); + assert.position(anchor.getPosition(), 1, 7); + }, + + "test insert lines before cursor should move anchor row": function() { + var doc = new AceAjax.Document("juhu\nkinners"); + var anchor = new AceAjax.Anchor(doc, 1, 4); + + doc.insertLines(1, ["123", "456"]); + assert.position(anchor.getPosition(), 3, 4); + }, + + "test insert new line before cursor should move anchor column": function() { + var doc = new AceAjax.Document("juhu\nkinners"); + var anchor = new AceAjax.Anchor(doc, 1, 4); + + doc.insertNewLine({row: 0, column: 0}); + assert.position(anchor.getPosition(), 2, 4); + }, + + "test insert new line in anchor line before anchor should move anchor column and row": function() { + var doc = new AceAjax.Document("juhu\nkinners"); + var anchor = new AceAjax.Anchor(doc, 1, 4); + + doc.insertNewLine({row: 1, column: 2}); + assert.position(anchor.getPosition(), 2, 2); + }, + + "test delete text in anchor line before anchor should move anchor column": function() { + var doc = new AceAjax.Document("juhu\nkinners"); + var anchor = new AceAjax.Anchor(doc, 1, 4); + + doc.remove(new AceAjax.Range(1, 1, 1, 3)); + assert.position(anchor.getPosition(), 1, 2); + }, + + "test remove range which contains the anchor should move the anchor to the start of the range": function() { + var doc = new AceAjax.Document("juhu\nkinners"); + var anchor = new AceAjax.Anchor(doc, 0, 3); + + doc.remove(new AceAjax.Range(0, 1, 1, 3)); + assert.position(anchor.getPosition(), 0, 1); + }, + + "test delete character before the anchor should have no effect": function() { + var doc = new AceAjax.Document("juhu\nkinners"); + var anchor = new AceAjax.Anchor(doc, 1, 4); + + doc.remove(new AceAjax.Range(1, 4, 1, 5)); + assert.position(anchor.getPosition(), 1, 4); + }, + + "test delete lines in anchor line before anchor should move anchor row": function() { + var doc = new AceAjax.Document("juhu\n1\n2\nkinners"); + var anchor = new AceAjax.Anchor(doc, 3, 4); + + doc.removeLines(1, 2); + assert.position(anchor.getPosition(), 1, 4); + }, + + "test remove new line before the cursor": function() { + var doc = new AceAjax.Document("juhu\nkinners"); + var anchor = new AceAjax.Anchor(doc, 1, 4); + + doc.removeNewLine(0); + assert.position(anchor.getPosition(), 0, 8); + }, + + "test delete range which contains the anchor should move anchor to the end of the range": function() { + var doc = new AceAjax.Document("juhu\nkinners"); + var anchor = new AceAjax.Anchor(doc, 1, 4); + + doc.remove(new AceAjax.Range(0, 2, 1, 2)); + assert.position(anchor.getPosition(), 0, 4); + }, + + "test delete line which contains the anchor should move anchor to the end of the range": function() { + var doc = new AceAjax.Document("juhu\nkinners\n123"); + var anchor = new AceAjax.Anchor(doc, 1, 5); + + doc.removeLines(1, 1); + assert.position(anchor.getPosition(), 1, 0); + }, + + "test remove after the anchor should have no effect": function() { + var doc = new AceAjax.Document("juhu\nkinners\n123"); + var anchor = new AceAjax.Anchor(doc, 1, 2); + + doc.remove(new AceAjax.Range(1, 4, 2, 2)); + assert.position(anchor.getPosition(), 1, 2); + }, + + "test anchor changes triggered by document changes should emit change event": function(next) { + var doc = new AceAjax.Document("juhu\nkinners\n123"); + var anchor = new AceAjax.Anchor(doc, 1, 5); + + anchor.on("change", function(e) { + assert.position(anchor.getPosition(), 0, 0); + next(); + }); + + doc.remove(new AceAjax.Range(0, 0, 2, 1)); + }, + + "test only fire change event if position changes": function() { + var doc = new AceAjax.Document("juhu\nkinners\n123"); + var anchor = new AceAjax.Anchor(doc, 1, 5); + + anchor.on("change", function(e) { + assert.fail(); + }); + + doc.remove(new AceAjax.Range(2, 0, 2, 1)); + } +}; diff --git a/ace/tests/ace-background_tokenizer-tests.ts b/ace/tests/ace-background_tokenizer-tests.ts new file mode 100644 index 0000000000..8c29358a40 --- /dev/null +++ b/ace/tests/ace-background_tokenizer-tests.ts @@ -0,0 +1,39 @@ +/// + +function forceTokenize(session) { + for (var i = 0, l = session.getLength(); i < l; i++) + session.getTokens(i) +} + +function testStates(session, states) { + for (var i = 0, l = session.getLength(); i < l; i++) + assert.equal(session.bgTokenizer.states[i], states[i]) + assert.ok(l == states.length) +} + +exports = { + + "test background tokenizer update on session change": function() { + var doc = new AceAjax.EditSession([ + "/*", + "*/", + "var juhu" + ]); + doc.setMode("./mode/javascript") + + forceTokenize(doc) + testStates(doc, ["comment", "start", "start"]) + + doc.remove(new AceAjax.Range(0, 2, 1, 2)) + testStates(doc, [null, "start"]) + + forceTokenize(doc) + testStates(doc, ["comment", "comment"]) + + doc.insert({ row: 0, column: 2 }, "\n*/") + testStates(doc, [undefined, undefined, "comment"]) + + forceTokenize(doc) + testStates(doc, ["comment", "start", "start"]) + } +}; diff --git a/ace/tests/ace-default-tests.ts b/ace/tests/ace-default-tests.ts new file mode 100644 index 0000000000..dcd1ab1033 --- /dev/null +++ b/ace/tests/ace-default-tests.ts @@ -0,0 +1,450 @@ +/// + +var editor = ace.edit("editor"); +editor.setTheme("ace/theme/monokai"); +editor.getSession().setMode("ace/mode/javascript"); + +editor.setTheme("ace/theme/twilight"); + +editor.getSession().setMode("ace/mode/javascript"); + +editor.setValue("the new text here"); // or session.setValue +editor.getValue(); // or session.getValue + +editor.session.getTextRange(editor.getSelectionRange()); + +editor.insert("Something cool"); + +editor.selection.getCursor(); + +editor.gotoLine(123); + +editor.session.getLength(); + +editor.getSession().setTabSize(4); + +editor.getSession().setUseSoftTabs(true); + +document.getElementById('editor').style.fontSize = '12px'; + +editor.getSession().setUseWrapMode(true); + +editor.setHighlightActiveLine(false); + +editor.setShowPrintMargin(false); + +editor.setReadOnly(true); // false to make it editable + +editor.resize() + +editor.find('needle', { + backwards: false, + wrap: false, + caseSensitive: false, + wholeWord: false, + regExp: false +}); +editor.findNext(); +editor.findPrevious(); + +editor.find('foo'); +editor.replace('bar'); + +editor.replaceAll('bar'); + +editor.getSession().on('change', function (e) { +// e.type, etc +}); + +editor.getSession().selection.on('changeSelection', function (e) { +}); + +editor.getSession().selection.on('changeCursor', function (e) { +}); + +editor.commands.addCommand({ +name: 'myCommand', +bindKey: { win: 'Ctrl-M', mac: 'Command-M' }, +exec: function (editor) { +//... +}, +readOnly: true // false if this command should not apply in readOnly mode +}); + +editor.moveCursorTo(1, 1); +editor.removeLines(); + +editor.removeLines(); + +editor.removeLines(); + +editor.removeLines(); + +editor.moveCursorTo(1, 1); +editor.getSelection().selectDown(); + +editor.removeLines(); + +editor.removeLines(); + +editor.moveCursorTo(3, 0); + +editor.removeLines(); + +editor.removeLines(); + +editor.moveCursorTo(1, 3); +editor.getSelection().selectDown(); + +editor.indent(); + +var range = editor.getSelectionRange(); + +editor.moveCursorTo(1, 0); +editor.getSelection().selectDown(); + +editor.indent(); + +editor.moveCursorTo(0, 0); +editor.onTextInput("\n"); + +editor.moveCursorTo(0, 5); +editor.getSelection().selectDown(); +editor.getSelection().selectDown(); + +editor.blockOutdent(); + +editor.moveCursorTo(1, 1); +editor.removeLines(); + +var session = new AceAjax.EditSession(["a", "b", "c", "d"].join("\n")); + +assert.equal(session.toString(), "a\nc\nd"); +assert.position(editor.getCursorPosition(), 1, 0); + +editor.removeLines(); + +assert.equal(session.toString(), "a\nd"); +assert.position(editor.getCursorPosition(), 1, 0); + +editor.removeLines(); + +assert.equal(session.toString(), "a"); +assert.position(editor.getCursorPosition(), 0, 1); + +editor.removeLines(); + +assert.equal(session.toString(), ""); +assert.position(editor.getCursorPosition(), 0, 0); + +editor.moveCursorTo(1, 1); +editor.getSelection().selectDown(); + +editor.removeLines(); +assert.equal(session.toString(), "a\nd"); +assert.position(editor.getCursorPosition(), 1, 0); + + +editor.removeLines(); + +assert.equal(session.toString(), "b\nc"); +assert.position(editor.getCursorPosition(), 0, 0); + + +editor.moveCursorTo(3, 0); + +editor.removeLines(); +assert.equal(session.toString(), "a\nb\nc"); +assert.position(editor.getCursorPosition(), 2, 1); + +editor.removeLines(); +assert.equal(session.toString(), "a\nb"); +assert.position(editor.getCursorPosition(), 1, 1); + + +editor.moveCursorTo(1, 3); +editor.getSelection().selectDown(); + +editor.indent(); + +assert.equal(["a12345", " b12345", " c12345"].join("\n"), session.toString()); + +assert.position(editor.getCursorPosition(), 2, 7); + +range = editor.getSelectionRange(); +assert.position(range.start, 1, 7); +assert.position(range.end, 2, 7); + + +editor.moveCursorTo(1, 0); +editor.getSelection().selectDown(); + +editor.indent(); +assert.equal(["a12345", " b12345", "c12345"].join("\n"), session.toString()); + + +editor.moveCursorTo(0, 0); +editor.onTextInput("\n"); +assert.equal(["", "{"].join("\n"), session.toString()); + + +editor.moveCursorTo(0, 5); +editor.getSelection().selectDown(); +editor.getSelection().selectDown(); + +editor.blockOutdent(); +assert.equal(session.toString(), [" a12345", "b12345", " c12345"].join("\n")); + +assert.position(editor.getCursorPosition(), 2, 1); + +range = editor.getSelectionRange(); +assert.position(range.start, 0, 1); +assert.position(range.end, 2, 1); + +editor.blockOutdent(); +assert.equal(session.toString(), ["a12345", "b12345", "c12345"].join("\n")); + +range = editor.getSelectionRange(); +assert.position(range.start, 0, 0); +assert.position(range.end, 2, 0); + + +editor.moveCursorTo(0, 3); +editor.blockOutdent(" "); + +assert.equal(session.toString(), " 12"); +assert.position(editor.getCursorPosition(), 0, 0); + + +editor.moveCursorTo(0, 2); +editor.getSelection().selectDown(); +editor.toggleCommentLines(); + +assert.equal(["// abc", "//cde"].join("\n"), session.toString()); + +var selection = editor.getSelectionRange(); +assert.position(selection.start, 0, 4); +assert.position(selection.end, 1, 4); + + +editor.moveCursorTo(0, 1); +editor.getSelection().selectDown(); +editor.getSelection().selectRight(); +editor.getSelection().selectRight(); + +editor.toggleCommentLines(); + +assert.equal([" abc", "cde"].join("\n"), session.toString()); +assert.range(editor.getSelectionRange(), 0, 0, 1, 1); + + +editor.moveCursorTo(0, 0); +editor.getSelection().selectDown(); +editor.getSelection().selectDown(); + +editor.toggleCommentLines(); +editor.toggleCommentLines(); + +assert.equal([" abc", "cde", "fg"].join("\n"), session.toString()); + + +editor.moveCursorTo(0, 0); +editor.getSelection().selectDown(); + +editor.toggleCommentLines(); +assert.range(editor.getSelectionRange(), 0, 2, 1, 0); + + + +editor.moveCursorTo(1, 0); +editor.getSelection().selectUp(); + +editor.toggleCommentLines(); +assert.range(editor.getSelectionRange(), 0, 2, 1, 0); + + +editor.moveCursorTo(0, 1); +editor.getSelection().selectDown(); + +editor.moveLinesDown(); +assert.equal(["33", "11", "22", "44"].join("\n"), session.toString()); +assert.position(editor.getCursorPosition(), 1, 0); +assert.position(editor.getSelection().getSelectionAnchor(), 3, 0); +assert.position(editor.getSelection().getSelectionLead(), 1, 0); + +editor.moveLinesDown(); +assert.equal(["33", "44", "11", "22"].join("\n"), session.toString()); +assert.position(editor.getCursorPosition(), 2, 0); +assert.position(editor.getSelection().getSelectionAnchor(), 3, 2); +assert.position(editor.getSelection().getSelectionLead(), 2, 0); + +// moving again should have no effect +editor.moveLinesDown(); +assert.equal(["33", "44", "11", "22"].join("\n"), session.toString()); +assert.position(editor.getCursorPosition(), 2, 0); +assert.position(editor.getSelection().getSelectionAnchor(), 3, 2); +assert.position(editor.getSelection().getSelectionLead(), 2, 0); + + +editor.moveCursorTo(2, 1); +editor.getSelection().selectDown(); + +editor.moveLinesUp(); +assert.equal(session.toString(), ["11", "33", "44", "22"].join("\n")); +assert.position(editor.getCursorPosition(), 1, 0); +assert.position(editor.getSelection().getSelectionAnchor(), 3, 0); +assert.position(editor.getSelection().getSelectionLead(), 1, 0); + +editor.moveLinesUp(); +assert.equal(session.toString(), ["33", "44", "11", "22"].join("\n")); +assert.position(editor.getCursorPosition(), 0, 0); +assert.position(editor.getSelection().getSelectionAnchor(), 2, 0); +assert.position(editor.getSelection().getSelectionLead(), 0, 0); + + +editor.moveCursorTo(1, 1); +editor.clearSelection(); + +editor.moveLinesDown(); +assert.equal(["11", "33", "22", "44"].join("\n"), session.toString()); +assert.position(editor.getCursorPosition(), 2, 1); + +editor.clearSelection(); + +editor.moveLinesUp(); +assert.equal(["11", "22", "33", "44"].join("\n"), session.toString()); +assert.position(editor.getCursorPosition(), 1, 1); + + +editor.moveCursorTo(1, 1); +editor.getSelection().selectDown(); + +editor.copyLinesDown(); +assert.equal(["11", "22", "33", "22", "33", "44"].join("\n"), session.toString()); + +assert.position(editor.getCursorPosition(), 3, 0); +assert.position(editor.getSelection().getSelectionAnchor(), 5, 0); +assert.position(editor.getSelection().getSelectionLead(), 3, 0); + + +editor.moveCursorTo(1, 1); +editor.getSelection().selectDown(); + +editor.copyLinesUp(); +assert.equal(["11", "22", "33", "22", "33", "44"].join("\n"), session.toString()); + +assert.position(editor.getCursorPosition(), 1, 0); +assert.position(editor.getSelection().getSelectionAnchor(), 3, 0); +assert.position(editor.getSelection().getSelectionLead(), 1, 0); + + +session.setTabSize(2); +session.setUseSoftTabs(true); + +editor.onTextInput("\t"); +assert.equal(session.toString(), " "); + +session.setTabSize(5); +editor.onTextInput("\t"); +assert.equal(session.toString(), " "); + + +session.setUseSoftTabs(false); + +editor.onTextInput("\t"); +assert.equal(session.toString(), "\t"); + +editor.removeLines(); +var step1 = session.toString(); +assert.equal(step1, "222\n333"); + +editor.removeLines(); +var step2 = session.toString(); +assert.equal(step2, "333"); + +editor.removeLines(); +var step3 = session.toString(); +assert.equal(step3, ""); + +var undoManager = new AceAjax.UndoManager(); + +undoManager.undo(); +assert.equal(session.toString(), step2); + +undoManager.undo(); +assert.equal(session.toString(), step1); + +undoManager.undo(); +assert.equal(session.toString(), ""); + +undoManager.undo(); +assert.equal(session.toString(), ""); + +editor.moveCursorTo(1, 1); +editor.remove("left"); +assert.equal(session.toString(), "123\n56"); + +editor.moveCursorTo(1, 0); +editor.remove("left"); +assert.equal(session.toString(), "123456"); + +session.setUseSoftTabs(true); +session.setTabSize(4); + +editor.moveCursorTo(1, 8); +editor.remove("left"); +assert.equal(session.toString(), "123\n 456"); + +editor.moveCursorTo(1, 0); +editor.transposeLetters(); + +assert.equal(session.getValue(), ["123", "4567", "89"].join("\n")); + +editor.moveCursorTo(1, 2); +editor.transposeLetters(); + +assert.equal(session.getValue(), ["123", "4657", "89"].join("\n")); + +editor.moveCursorTo(1, 4); +editor.transposeLetters(); + +assert.equal(session.getValue(), ["123", "4576", "89"].join("\n")); + +editor.moveCursorTo(1, 1); +editor.getSelection().selectRight(); +editor.transposeLetters(); + +assert.equal(session.getValue(), ["123", "4567", "89"].join("\n")); + +editor.moveCursorTo(1, 2); +editor.transposeLetters(); +assert.position(editor.getCursorPosition(), 1, 3); + +editor.moveCursorTo(1, 2); +editor.removeToLineEnd(); +assert.equal(session.getValue(), ["123", "45", "89"].join("\n")); + +editor.moveCursorTo(1, 4); +editor.removeToLineEnd(); +assert.position(editor.getCursorPosition(), 1, 4); +assert.equal(session.getValue(), ["123", "456789"].join("\n")); + +editor.moveCursorTo(1, 0); +editor.getSelection().selectLineEnd(); +editor.toUpperCase() +assert.equal(session.getValue(), ["ajax", "DOT", "org"].join("\n")); + +editor.moveCursorTo(1, 0); +editor.toUpperCase() +assert.equal(session.getValue(), ["ajax", "DOT", "org"].join("\n")); +assert.position(editor.getCursorPosition(), 1, 0); + +editor.moveCursorTo(1, 0); +editor.getSelection().selectLineEnd(); +editor.toLowerCase() +assert.equal(session.getValue(), ["AJAX", "dot", "ORG"].join("\n")); + +editor.moveCursorTo(1, 0); +editor.toLowerCase() +assert.equal(session.getValue(), ["AJAX", "dot", "ORG"].join("\n")); +assert.position(editor.getCursorPosition(), 1, 0); diff --git a/ace/tests/ace-document-tests.ts b/ace/tests/ace-document-tests.ts new file mode 100644 index 0000000000..1f3e0a9a24 --- /dev/null +++ b/ace/tests/ace-document-tests.ts @@ -0,0 +1,254 @@ +/// + +exports = { + "test: insert text in line": function() { + var doc = new AceAjax.Document(["12", "34"]); + + var deltas = []; + doc.on("change", function (e) { deltas.push(e.data); }); + + doc.insert({ row: 0, column: 1 }, "juhu"); + assert.equal(doc.getValue(), ["1juhu2", "34"].join("\n")); + + var d = deltas.concat(); + doc.revertDeltas(d); + assert.equal(doc.getValue(), ["12", "34"].join("\n")); + + doc.applyDeltas(d); + assert.equal(doc.getValue(), ["1juhu2", "34"].join("\n")); + } , + + "test: insert new line": function() { + var doc = new AceAjax.Document(["12", "34"]); + + var deltas = []; + doc.on("change", function (e) { deltas.push(e.data); }); + + doc.insertNewLine({ row: 0, column: 1 }); + assert.equal(doc.getValue(), ["1", "2", "34"].join("\n")); + + var d = deltas.concat(); + doc.revertDeltas(d); + assert.equal(doc.getValue(), ["12", "34"].join("\n")); + + doc.applyDeltas(d); + assert.equal(doc.getValue(), ["1", "2", "34"].join("\n")); + } , + + "test: insert lines at the beginning": function() { + var doc = new AceAjax.Document(["12", "34"]); + + var deltas = []; + doc.on("change", function (e) { deltas.push(e.data); }); + + doc.insertLines(0, ["aa", "bb"]); + assert.equal(doc.getValue(), ["aa", "bb", "12", "34"].join("\n")); + + var d = deltas.concat(); + doc.revertDeltas(d); + assert.equal(doc.getValue(), ["12", "34"].join("\n")); + + doc.applyDeltas(d); + assert.equal(doc.getValue(), ["aa", "bb", "12", "34"].join("\n")); + } , + + "test: insert lines at the end": function() { + var doc = new AceAjax.Document(["12", "34"]); + + var deltas = []; + doc.on("change", function (e) { deltas.push(e.data); }); + + doc.insertLines(2, ["aa", "bb"]); + assert.equal(doc.getValue(), ["12", "34", "aa", "bb"].join("\n")); + } , + + "test: insert lines in the middle": function() { + var doc = new AceAjax.Document(["12", "34"]); + + var deltas = []; + doc.on("change", function (e) { deltas.push(e.data); }); + + doc.insertLines(1, ["aa", "bb"]); + assert.equal(doc.getValue(), ["12", "aa", "bb", "34"].join("\n")); + + var d = deltas.concat(); + doc.revertDeltas(d); + assert.equal(doc.getValue(), ["12", "34"].join("\n")); + + doc.applyDeltas(d); + assert.equal(doc.getValue(), ["12", "aa", "bb", "34"].join("\n")); + } , + + "test: insert multi line string at the start": function() { + var doc = new AceAjax.Document(["12", "34"]); + + var deltas = []; + doc.on("change", function (e) { deltas.push(e.data); }); + + doc.insert({ row: 0, column: 0 }, "aa\nbb\ncc"); + assert.equal(doc.getValue(), ["aa", "bb", "cc12", "34"].join("\n")); + + var d = deltas.concat(); + doc.revertDeltas(d); + assert.equal(doc.getValue(), ["12", "34"].join("\n")); + + doc.applyDeltas(d); + assert.equal(doc.getValue(), ["aa", "bb", "cc12", "34"].join("\n")); + } , + + "test: insert multi line string at the end": function() { + var doc = new AceAjax.Document(["12", "34"]); + + var deltas = []; + doc.on("change", function (e) { deltas.push(e.data); }); + + doc.insert({ row: 2, column: 0 }, "aa\nbb\ncc"); + assert.equal(doc.getValue(), ["12", "34aa", "bb", "cc"].join("\n")); + + var d = deltas.concat(); + doc.revertDeltas(d); + assert.equal(doc.getValue(), ["12", "34"].join("\n")); + + doc.applyDeltas(d); + assert.equal(doc.getValue(), ["12", "34aa", "bb", "cc"].join("\n")); + } , + + "test: insert multi line string in the middle": function() { + var doc = new AceAjax.Document(["12", "34"]); + + var deltas = []; + doc.on("change", function (e) { deltas.push(e.data); }); + + doc.insert({ row: 0, column: 1 }, "aa\nbb\ncc"); + assert.equal(doc.getValue(), ["1aa", "bb", "cc2", "34"].join("\n")); + + var d = deltas.concat(); + doc.revertDeltas(d); + assert.equal(doc.getValue(), ["12", "34"].join("\n")); + + doc.applyDeltas(d); + assert.equal(doc.getValue(), ["1aa", "bb", "cc2", "34"].join("\n")); + } , + + "test: delete in line": function() { + var doc = new AceAjax.Document(["1234", "5678"]); + + var deltas = []; + doc.on("change", function (e) { deltas.push(e.data); }); + + doc.remove(new AceAjax.Range(0, 1, 0, 3)); + assert.equal(doc.getValue(), ["14", "5678"].join("\n")); + + var d = deltas.concat(); + doc.revertDeltas(d); + assert.equal(doc.getValue(), ["1234", "5678"].join("\n")); + + doc.applyDeltas(d); + assert.equal(doc.getValue(), ["14", "5678"].join("\n")); + } , + + "test: delete new line": function() { + var doc = new AceAjax.Document(["1234", "5678"]); + + var deltas = []; + doc.on("change", function (e) { deltas.push(e.data); }); + + doc.remove(new AceAjax.Range(0, 4, 1, 0)); + assert.equal(doc.getValue(), ["12345678"].join("\n")); + + var d = deltas.concat(); + doc.revertDeltas(d); + assert.equal(doc.getValue(), ["1234", "5678"].join("\n")); + + doc.applyDeltas(d); + assert.equal(doc.getValue(), ["12345678"].join("\n")); + } , + + "test: delete multi line range line": function() { + var doc = new AceAjax.Document(["1234", "5678", "abcd"]); + + var deltas = []; + doc.on("change", function (e) { deltas.push(e.data); }); + + doc.remove(new AceAjax.Range(0, 2, 2, 2)); + assert.equal(doc.getValue(), ["12cd"].join("\n")); + + var d = deltas.concat(); + doc.revertDeltas(d); + assert.equal(doc.getValue(), ["1234", "5678", "abcd"].join("\n")); + + doc.applyDeltas(d); + assert.equal(doc.getValue(), ["12cd"].join("\n")); + } , + + "test: delete full lines": function() { + var doc = new AceAjax.Document(["1234", "5678", "abcd"]); + + var deltas = []; + doc.on("change", function (e) { deltas.push(e.data); }); + + doc.remove(new AceAjax.Range(1, 0, 3, 0)); + assert.equal(doc.getValue(), ["1234", ""].join("\n")); + } , + + "test: remove lines should return the removed lines": function() { + var doc = new AceAjax.Document(["1234", "5678", "abcd"]); + + var removed = doc.removeLines(1, 2); + assert.equal(removed.join("\n"), ["5678", "abcd"].join("\n")); + } , + + "test: should handle unix style new lines": function() { + var doc = new AceAjax.Document(["1", "2", "3"]); + assert.equal(doc.getValue(), ["1", "2", "3"].join("\n")); + } , + + "test: should handle windows style new lines": function() { + var doc = new AceAjax.Document(["1", "2", "3"].join("\r\n")); + + doc.setNewLineMode("unix"); + assert.equal(doc.getValue(), ["1", "2", "3"].join("\n")); + } , + + "test: set new line mode to 'windows' should use '\\r\\n' as new lines": function() { + var doc = new AceAjax.Document(["1", "2", "3"].join("\n")); + doc.setNewLineMode("windows"); + assert.equal(doc.getValue(), ["1", "2", "3"].join("\r\n")); + } , + + "test: set new line mode to 'unix' should use '\\n' as new lines": function() { + var doc = new AceAjax.Document(["1", "2", "3"].join("\r\n")); + + doc.setNewLineMode("unix"); + assert.equal(doc.getValue(), ["1", "2", "3"].join("\n")); + } , + + "test: set new line mode to 'auto' should detect the incoming nl type": function() { + var doc = new AceAjax.Document(["1", "2", "3"].join("\n")); + + doc.setNewLineMode("auto"); + assert.equal(doc.getValue(), ["1", "2", "3"].join("\n")); + + var doc = new AceAjax.Document(["1", "2", "3"].join("\r\n")); + + doc.setNewLineMode("auto"); + assert.equal(doc.getValue(), ["1", "2", "3"].join("\r\n")); + + doc.replace(new AceAjax.Range(0, 0, 2, 1), ["4", "5", "6"].join("\n")); + assert.equal(["4", "5", "6"].join("\n"), doc.getValue()); + } , + + "test: set value": function() { + var doc = new AceAjax.Document("1"); + assert.equal("1", doc.getValue()); + + doc.setValue(doc.getValue()); + assert.equal("1", doc.getValue()); + + var doc = new AceAjax.Document("1\n2"); + assert.equal("1\n2", doc.getValue()); + + doc.setValue(doc.getValue()); + assert.equal("1\n2", doc.getValue()); + } +}; \ No newline at end of file diff --git a/ace/tests/ace-edit_session-tests.ts b/ace/tests/ace-edit_session-tests.ts new file mode 100644 index 0000000000..12a3ce5bf3 --- /dev/null +++ b/ace/tests/ace-edit_session-tests.ts @@ -0,0 +1,919 @@ +/// + +var lang: any; + +function createFoldTestSession() { + var lines = [ + "function foo(items) {", + " for (var i=0; i>", [1, 2], 1); + } , + + "test get longest line": function() { + var session = new AceAjax.EditSession(["12"]); + session.setTabSize(4); + assert.equal(session.getScreenWidth(), 2); + + session.doc.insertNewLine({ row: 0, column: Infinity }); + session.doc.insertLines(1, ["123"]); + assert.equal(session.getScreenWidth(), 3); + + session.doc.insertNewLine({ row: 0, column: Infinity }); + session.doc.insertLines(1, ["\t\t"]); + + assert.equal(session.getScreenWidth(), 8); + + session.setTabSize(2); + assert.equal(session.getScreenWidth(), 4); + } , + + "test issue 83": function() { + var session = new AceAjax.EditSession(""); + var editor = new AceAjax.Editor(null, session); + var document = session.getDocument(); + + session.setUseWrapMode(true); + + document.insertLines(0, ["a", "b"]); + document.insertLines(2, ["c", "d"]); + document.removeLines(1, 2); + } , + + "test wrapMode init has to create wrapData array": function() { + var session = new AceAjax.EditSession("foo bar\nfoo bar"); + var editor = new AceAjax.Editor(null, session); + var document = session.getDocument(); + + session.setUseWrapMode(true); + session.setWrapLimitRange(3, 3); + session.adjustWrapLimit(80); + } , + + "test first line blank with wrap": function() { + var session = new AceAjax.EditSession("\nfoo"); + session.setUseWrapMode(true); + assert.equal(session.doc.getValue(), ["", "foo"].join("\n")); + } , + + "test first line blank with wrap 2": function() { + var session = new AceAjax.EditSession(""); + session.setUseWrapMode(true); + session.setValue("\nfoo"); + + assert.equal(session.doc.getValue(), ["", "foo"].join("\n")); + } , + + "test fold getFoldDisplayLine": function() { + var session = createFoldTestSession(); + function assertDisplayLine(foldLine, str) { + var line = session.getLine(foldLine.end.row); + var displayLine = + session.getFoldDisplayLine(foldLine, foldLine.end.row, line.length); + assert.equal(displayLine, str); + } + } , + + "test foldLine idxToPosition": function() { + var session = createFoldTestSession(); + + function assertIdx2Pos(foldLineIdx, idx, row, column) { + var foldLine = null; + assert.position(foldLine.idxToPosition(idx), row, column); + } + + // "function foo(items) {", + // " for (var i=0; i + +exports = { + + setUp: function(next) { + this.session1 = new AceAjax.EditSession(["abc", "def"]); + this.session2 = new AceAjax.EditSession(["ghi", "jkl"]); + + + var editor = new AceAjax.Editor(null); + next(); + } , + + "test: change document": function() { + var editor = new AceAjax.Editor(null); + + editor.setSession(this.session1); + assert.equal(editor.getSession(), this.session1); + + editor.setSession(this.session2); + assert.equal(editor.getSession(), this.session2); + } , + + "test: only changes to the new document should have effect": function () { + var editor = new AceAjax.Editor(null); + + var called = false; + editor.onDocumentChange = function () { + called = true; + }; + + editor.setSession(this.session1); + editor.setSession(this.session2); + + this.session1.duplicateLines(0, 0); + assert.notOk(called); + + this.session2.duplicateLines(0, 0); + assert.ok(called); + } , + + "test: should use cursor of new document": function () { + var editor = new AceAjax.Editor(null); + + this.session1.getSelection().moveCursorTo(0, 1); + this.session2.getSelection().moveCursorTo(1, 0); + + editor.setSession(this.session1); + assert.position(editor.getCursorPosition(), 0, 1); + + editor.setSession(this.session2); + assert.position(editor.getCursorPosition(), 1, 0); + } , + + "test: only changing the cursor of the new doc should not have an effect": function () { + var editor = new AceAjax.Editor(null); + + editor.onCursorChange = function () { + called = true; + }; + + editor.setSession(this.session1); + editor.setSession(this.session2); + assert.position(editor.getCursorPosition(), 0, 0); + + var called = false; + this.session1.getSelection().moveCursorTo(0, 1); + assert.position(editor.getCursorPosition(), 0, 0); + assert.notOk(called); + + this.session2.getSelection().moveCursorTo(1, 1); + assert.position(editor.getCursorPosition(), 1, 1); + assert.ok(called); + } , + + "test: should use selection of new document": function () { + var editor = new AceAjax.Editor(null); + + this.session1.getSelection().selectTo(0, 1); + this.session2.getSelection().selectTo(1, 0); + + editor.setSession(this.session1); + assert.position(editor.getSelection().getSelectionLead(), 0, 1); + + editor.setSession(this.session2); + assert.position(editor.getSelection().getSelectionLead(), 1, 0); + } , + + "test: only changing the selection of the new doc should not have an effect": function () { + var editor = new AceAjax.Editor(null); + + editor.onSelectionChange = function () { + called = true; + }; + + editor.setSession(this.session1); + editor.setSession(this.session2); + assert.position(editor.getSelection().getSelectionLead(), 0, 0); + + var called = false; + this.session1.getSelection().selectTo(0, 1); + assert.position(editor.getSelection().getSelectionLead(), 0, 0); + assert.notOk(called); + + this.session2.getSelection().selectTo(1, 1); + assert.position(editor.getSelection().getSelectionLead(), 1, 1); + assert.ok(called); + } , + + "test: should use mode of new document": function () { + var editor = new AceAjax.Editor(null); + + editor.onChangeMode = function () { + called = true; + }; + editor.setSession(this.session1); + editor.setSession(this.session2); + + var called = false; + this.session1.setMode(new Text()); + assert.notOk(called); + + this.session2.setMode(null); + assert.ok(called); + } , + + "test: should use stop worker of old document": function (next) { + var editor = new AceAjax.Editor(null); + + var self = this; + + // 1. Open an editor and set the session to CssMode + self.editor.setSession(self.session1); + self.session1.setMode(null); + + // 2. Add a line or two of valid CSS. + self.session1.setValue("DIV { color: red; }"); + + // 3. Clear the session value. + self.session1.setValue(""); + + // 4. Set the session to HtmlMode + self.session1.setMode(null); + + // 5. Try to type valid HTML + self.session1.insert({ row: 0, column: 0 }, ""); + + setTimeout(function () { + assert.equal(Object.keys(self.session1.getAnnotations()).length, 0); + next(); + }, 600); + } +}; \ No newline at end of file diff --git a/ace/tests/ace-editor_highlight_selected_word-tests.ts b/ace/tests/ace-editor_highlight_selected_word-tests.ts new file mode 100644 index 0000000000..7e06c8c50c --- /dev/null +++ b/ace/tests/ace-editor_highlight_selected_word-tests.ts @@ -0,0 +1,214 @@ +/// + +var lipsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " + + "Mauris at arcu mi, eu lobortis mauris. Quisque ut libero eget " + + "diam congue vehicula. Quisque ut odio ut mi aliquam tincidunt. " + + "Duis lacinia aliquam lorem eget eleifend. Morbi eget felis mi. " + + "Duis quam ligula, consequat vitae convallis volutpat, blandit " + + "nec neque. Nulla facilisi. Etiam suscipit lorem ac justo " + + "sollicitudin tristique. Phasellus ut posuere nunc. Aliquam " + + "scelerisque mollis felis non gravida. Vestibulum lacus sem, " + + "posuere non bibendum id, luctus non dolor. Aenean id metus " + + "lorem, vel dapibus est. Donec gravida feugiat augue nec " + + "accumsan.Lorem ipsum dolor sit amet, consectetur adipiscing " + + "elit. Nulla vulputate, velit vitae tincidunt congue, nunc " + + "augue accumsan velit, eu consequat turpis lectus ac orci. " + + "Pellentesque ornare dolor feugiat dui auctor eu varius nulla " + + "fermentum. Sed aliquam odio at velit lacinia vel fermentum " + + "felis sodales. In dignissim magna eget nunc lobortis non " + + "fringilla nibh ullamcorper. Donec facilisis malesuada elit " + + "at egestas. Etiam bibendum, diam vitae tempor aliquet, dui " + + "libero vehicula odio, eget bibendum mauris velit eu lorem.\n" + + "consectetur"; + +function callHighlighterUpdate(session: AceAjax.IEditSession, firstRow: number, lastRow: number) { + var rangeCount = 0; + var mockMarkerLayer = { drawSingleLineMarker: function () { rangeCount++; } } + return rangeCount; +} + +exports = { + setUp: function(next) { + var session = new AceAjax.EditSession(lipsum); + editor = new AceAjax.Editor(new MockRenderer(), session); + var selection = session.getSelection(); + next(); + } , + + "test: highlight selected words by default": function () { + var selection = session.getSelection(); + var session = new AceAjax.EditSession(lipsum); + var editor = new AceAjax.Editor(new MockRenderer(), session); + + assert.equal(editor.getHighlightSelectedWord(), true); + } , + + "test: highlight a word": function () { + var selection = session.getSelection(); + var session = new AceAjax.EditSession(lipsum); + var editor = new AceAjax.Editor(new MockRenderer(), session); + + editor.moveCursorTo(0, 9); + selection.selectWord(); + + var highlighter = null; + assert.ok(highlighter != null); + + var range = selection.getRange(); + assert.equal(session.getTextRange(range), "ipsum"); + assert.equal(highlighter.cache.length, 0); + assert.equal(callHighlighterUpdate(session, 0, 0), 2); + } , + + "test: highlight a word and clear highlight": function () { + var selection = session.getSelection(); + var session = new AceAjax.EditSession(lipsum); + var editor = new AceAjax.Editor(new MockRenderer(), session); + + editor.moveCursorTo(0, 8); + selection.selectWord(); + + var range = selection.getRange(); + assert.equal(session.getTextRange(range), "ipsum"); + assert.equal(callHighlighterUpdate(session, 0, 0), 2); + + session.highlight(""); + assert.equal(callHighlighterUpdate(session, 0, 0), 0); + } , + + "test: highlight another word": function () { + var selection = session.getSelection(); + var session = new AceAjax.EditSession(lipsum); + var editor = new AceAjax.Editor(new MockRenderer(), session); + + selection.moveCursorTo(0, 14); + selection.selectWord(); + + var range = selection.getRange(); + assert.equal(session.getTextRange(range), "dolor"); + assert.equal(callHighlighterUpdate(session, 0, 0), 4); + } , + + "test: no selection, no highlight": function () { + var selection = session.getSelection(); + var session = new AceAjax.EditSession(lipsum); + var editor = new AceAjax.Editor(new MockRenderer(), session); + + selection.clearSelection(); + assert.equal(callHighlighterUpdate(session, 0, 0), 0); + } , + + "test: select a word, no highlight": function () { + var selection = session.getSelection(); + var session = new AceAjax.EditSession(lipsum); + var editor = new AceAjax.Editor(new MockRenderer(), session); + + selection.moveCursorTo(0, 14); + selection.selectWord(); + + editor.setHighlightSelectedWord(false); + + var range = selection.getRange(); + assert.equal(session.getTextRange(range), "dolor"); + assert.equal(callHighlighterUpdate(session, 0, 0), 0); + } , + + "test: select a word with no matches": function () { + var selection = session.getSelection(); + var session = new AceAjax.EditSession(lipsum); + var editor = new AceAjax.Editor(new MockRenderer(), session); + + editor.setHighlightSelectedWord(true); + + var currentOptions = this.search.getOptions(); + var newOptions = { + wrap: true, + wholeWord: true, + caseSensitive: true, + needle: "Mauris" + }; + this.search.set(newOptions); + + var match = this.search.find(session); + assert.notEqual(match, null, "found a match for 'Mauris'"); + + this.search.set(currentOptions); + + selection.setSelectionRange(match); + + assert.equal(session.getTextRange(match), "Mauris"); + assert.equal(callHighlighterUpdate(session, 0, 0), 1); + } , + + "test: partial word selection 1": function () { + var selection = session.getSelection(); + var session = new AceAjax.EditSession(lipsum); + var editor = new AceAjax.Editor(new MockRenderer(), session); + + selection.moveCursorTo(0, 14); + selection.selectWord(); + selection.selectLeft(); + + var range = selection.getRange(); + assert.equal(session.getTextRange(range), "dolo"); + assert.equal(callHighlighterUpdate(session, 0, 0), 0); + } , + + "test: partial word selection 2": function () { + var selection = session.getSelection(); + var session = new AceAjax.EditSession(lipsum); + var editor = new AceAjax.Editor(new MockRenderer(), session); + + selection.moveCursorTo(0, 13); + selection.selectWord(); + selection.selectRight(); + + var range = selection.getRange(); + assert.equal(session.getTextRange(range), "dolor "); + assert.equal(callHighlighterUpdate(session, 0, 0), 0); + } , + + "test: partial word selection 3": function () { + var selection = session.getSelection(); + var session = new AceAjax.EditSession(lipsum); + var editor = new AceAjax.Editor(new MockRenderer(), session); + + selection.moveCursorTo(0, 14); + selection.selectWord(); + selection.selectLeft(); + selection.shiftSelection(1); + + var range = selection.getRange(); + assert.equal(session.getTextRange(range), "olor"); + assert.equal(callHighlighterUpdate(session, 0, 0), 0); + } , + + "test: select last word": function () { + var selection = session.getSelection(); + var session = new AceAjax.EditSession(lipsum); + var editor = new AceAjax.Editor(new MockRenderer(), session); + + selection.moveCursorTo(0, 1); + + var currentOptions = this.search.getOptions(); + var newOptions = { + wrap: true, + wholeWord: true, + caseSensitive: true, + backwards: true, + needle: "consectetur" + }; + this.search.set(newOptions); + + var match = this.search.find(session); + assert.notEqual(match, null, "found a match for 'consectetur'"); + assert.position(match.start, 1, 0); + + this.search.set(currentOptions); + + selection.setSelectionRange(match); + + assert.equal(session.getTextRange(match), "consectetur"); + assert.equal(callHighlighterUpdate(session, 0, 1), 3); + } +}; diff --git a/ace/tests/ace-editor_navigation-tests.ts b/ace/tests/ace-editor_navigation-tests.ts new file mode 100644 index 0000000000..c97ee0cd21 --- /dev/null +++ b/ace/tests/ace-editor_navigation-tests.ts @@ -0,0 +1,117 @@ +/// + +exports = { + createEditSession: function (rows, cols) { + var line = new Array(cols + 1).join("a"); + var text = new Array(rows).join(line + "\n") + line; + return new AceAjax.EditSession(text); + }, + + "test: navigate to end of file should scroll the last line into view": function () { + var doc = this.createEditSession(200, 10); + var editor = new AceAjax.Editor(new MockRenderer(), doc); + + editor.navigateFileEnd(); + var cursor = editor.getCursorPosition(); + + assert.ok(editor.getFirstVisibleRow() <= cursor.row); + assert.ok(editor.getLastVisibleRow() >= cursor.row); + }, + + "test: navigate to start of file should scroll the first row into view": function () { + var doc = this.createEditSession(200, 10); + var editor = new AceAjax.Editor(new MockRenderer(), doc); + + editor.moveCursorTo(editor.getLastVisibleRow() + 20); + editor.navigateFileStart(); + + assert.equal(editor.getFirstVisibleRow(), 0); + }, + + "test: goto hidden line should scroll the line into the middle of the viewport": function () { + var editor = new AceAjax.Editor(new MockRenderer(), this.createEditSession(200, 5)); + + editor.navigateTo(0, 0); + editor.gotoLine(101); + assert.position(editor.getCursorPosition(), 100, 0); + assert.equal(editor.getFirstVisibleRow(), 89); + + editor.navigateTo(100, 0); + editor.gotoLine(11); + assert.position(editor.getCursorPosition(), 10, 0); + assert.equal(editor.getFirstVisibleRow(), 0); + + editor.navigateTo(100, 0); + editor.gotoLine(6); + assert.position(editor.getCursorPosition(), 5, 0); + assert.equal(0, editor.getFirstVisibleRow(), 0); + + editor.navigateTo(100, 0); + editor.gotoLine(1); + assert.position(editor.getCursorPosition(), 0, 0); + assert.equal(editor.getFirstVisibleRow(), 0); + + editor.navigateTo(0, 0); + editor.gotoLine(191); + assert.position(editor.getCursorPosition(), 190, 0); + assert.equal(editor.getFirstVisibleRow(), 179); + + editor.navigateTo(0, 0); + editor.gotoLine(196); + assert.position(editor.getCursorPosition(), 195, 0); + assert.equal(editor.getFirstVisibleRow(), 180); + }, + + "test: goto visible line should only move the cursor and not scroll": function () { + var editor = new AceAjax.Editor(new MockRenderer(), this.createEditSession(200, 5)); + + editor.navigateTo(0, 0); + editor.gotoLine(12); + assert.position(editor.getCursorPosition(), 11, 0); + assert.equal(editor.getFirstVisibleRow(), 0); + + editor.navigateTo(30, 0); + editor.gotoLine(33); + assert.position(editor.getCursorPosition(), 32, 0); + assert.equal(editor.getFirstVisibleRow(), 30); + }, + + "test: navigate from the end of a long line down to a short line and back should maintain the curser column": function () { + var editor = new AceAjax.Editor(new MockRenderer(), new AceAjax.EditSession(["123456", "1"])); + + editor.navigateTo(0, 6); + assert.position(editor.getCursorPosition(), 0, 6); + + editor.navigateDown(); + assert.position(editor.getCursorPosition(), 1, 1); + + editor.navigateUp(); + assert.position(editor.getCursorPosition(), 0, 6); + }, + + "test: reset desired column on navigate left or right": function () { + var editor = new AceAjax.Editor(new MockRenderer(), new AceAjax.EditSession(["123456", "12"])); + + editor.navigateTo(0, 6); + assert.position(editor.getCursorPosition(), 0, 6); + + editor.navigateDown(); + assert.position(editor.getCursorPosition(), 1, 2); + + editor.navigateLeft(); + assert.position(editor.getCursorPosition(), 1, 1); + + editor.navigateUp(); + assert.position(editor.getCursorPosition(), 0, 1); + }, + + "test: typing text should update the desired column": function () { + var editor = new AceAjax.Editor(new MockRenderer(), new AceAjax.EditSession(["1234", "1234567890"])); + + editor.navigateTo(0, 3); + editor.insert("juhu"); + + editor.navigateDown(); + assert.position(editor.getCursorPosition(), 1, 7); + } +}; \ No newline at end of file diff --git a/ace/tests/ace-editor_text_edit-tests.ts b/ace/tests/ace-editor_text_edit-tests.ts new file mode 100644 index 0000000000..9d618acc67 --- /dev/null +++ b/ace/tests/ace-editor_text_edit-tests.ts @@ -0,0 +1,498 @@ +/// + +exports = { + "test: delete line from the middle": function () { + var session = new AceAjax.EditSession(["a", "b", "c", "d"].join("\n")); + var editor = new AceAjax.Editor(new MockRenderer(), session); + + editor.moveCursorTo(1, 1); + editor.removeLines(); + + assert.equal(session.toString(), "a\nc\nd"); + assert.position(editor.getCursorPosition(), 1, 0); + + editor.removeLines(); + + assert.equal(session.toString(), "a\nd"); + assert.position(editor.getCursorPosition(), 1, 0); + + editor.removeLines(); + + assert.equal(session.toString(), "a"); + assert.position(editor.getCursorPosition(), 0, 1); + + editor.removeLines(); + + assert.equal(session.toString(), ""); + assert.position(editor.getCursorPosition(), 0, 0); + }, + + "test: delete multiple selected lines": function () { + var session = new AceAjax.EditSession(["a", "b", "c", "d"].join("\n")); + var editor = new AceAjax.Editor(new MockRenderer(), session); + + editor.moveCursorTo(1, 1); + editor.getSelection().selectDown(); + + editor.removeLines(); + assert.equal(session.toString(), "a\nd"); + assert.position(editor.getCursorPosition(), 1, 0); + }, + + "test: delete first line": function () { + var session = new AceAjax.EditSession(["a", "b", "c"].join("\n")); + var editor = new AceAjax.Editor(new MockRenderer(), session); + + editor.removeLines(); + + assert.equal(session.toString(), "b\nc"); + assert.position(editor.getCursorPosition(), 0, 0); + }, + + "test: delete last should also delete the new line of the previous line": function () { + var session = new AceAjax.EditSession(["a", "b", "c", ""].join("\n")); + var editor = new AceAjax.Editor(new MockRenderer(), session); + + editor.moveCursorTo(3, 0); + + editor.removeLines(); + assert.equal(session.toString(), "a\nb\nc"); + assert.position(editor.getCursorPosition(), 2, 1); + + editor.removeLines(); + assert.equal(session.toString(), "a\nb"); + assert.position(editor.getCursorPosition(), 1, 1); + }, + + "test: indent block": function () { + var session = new AceAjax.EditSession(["a12345", "b12345", "c12345"].join("\n")); + var editor = new AceAjax.Editor(new MockRenderer(), session); + + editor.moveCursorTo(1, 3); + editor.getSelection().selectDown(); + + editor.indent(); + + assert.equal(["a12345", " b12345", " c12345"].join("\n"), session.toString()); + + assert.position(editor.getCursorPosition(), 2, 7); + + var range = editor.getSelectionRange(); + assert.position(range.start, 1, 7); + assert.position(range.end, 2, 7); + }, + + "test: indent selected lines": function () { + var session = new AceAjax.EditSession(["a12345", "b12345", "c12345"].join("\n")); + var editor = new AceAjax.Editor(new MockRenderer(), session); + + editor.moveCursorTo(1, 0); + editor.getSelection().selectDown(); + + editor.indent(); + assert.equal(["a12345", " b12345", "c12345"].join("\n"), session.toString()); + }, + + "test: no auto indent if cursor is before the {": function () { + var session = new AceAjax.EditSession("{", new JavaScriptMode()); + var editor = new AceAjax.Editor(new MockRenderer(), session); + + editor.moveCursorTo(0, 0); + editor.onTextInput("\n"); + assert.equal(["", "{"].join("\n"), session.toString()); + }, + + "test: outdent block": function () { + var session = new AceAjax.EditSession([" a12345", " b12345", " c12345"].join("\n")); + var editor = new AceAjax.Editor(new MockRenderer(), session); + + editor.moveCursorTo(0, 5); + editor.getSelection().selectDown(); + editor.getSelection().selectDown(); + + editor.blockOutdent(); + assert.equal(session.toString(), [" a12345", "b12345", " c12345"].join("\n")); + + assert.position(editor.getCursorPosition(), 2, 1); + + var range = editor.getSelectionRange(); + assert.position(range.start, 0, 1); + assert.position(range.end, 2, 1); + + editor.blockOutdent(); + assert.equal(session.toString(), ["a12345", "b12345", "c12345"].join("\n")); + + var range = editor.getSelectionRange(); + assert.position(range.start, 0, 0); + assert.position(range.end, 2, 0); + }, + + "test: outent without a selection should update cursor": function () { + var session = new AceAjax.EditSession(" 12"); + var editor = new AceAjax.Editor(new MockRenderer(), session); + + editor.moveCursorTo(0, 3); + editor.blockOutdent(" "); + + assert.equal(session.toString(), " 12"); + assert.position(editor.getCursorPosition(), 0, 0); + }, + + "test: comment lines should perserve selection": function () { + var session = new AceAjax.EditSession([" abc", "cde"].join("\n"), new JavaScriptMode()); + var editor = new AceAjax.Editor(new MockRenderer(), session); + + editor.moveCursorTo(0, 2); + editor.getSelection().selectDown(); + editor.toggleCommentLines(); + + assert.equal(["// abc", "//cde"].join("\n"), session.toString()); + + var selection = editor.getSelectionRange(); + assert.position(selection.start, 0, 4); + assert.position(selection.end, 1, 4); + }, + + "test: uncomment lines should perserve selection": function () { + var session = new AceAjax.EditSession(["// abc", "//cde"].join("\n"), new JavaScriptMode()); + var editor = new AceAjax.Editor(new MockRenderer(), session); + + editor.moveCursorTo(0, 1); + editor.getSelection().selectDown(); + editor.getSelection().selectRight(); + editor.getSelection().selectRight(); + + editor.toggleCommentLines(); + + assert.equal([" abc", "cde"].join("\n"), session.toString()); + assert.range(editor.getSelectionRange(), 0, 0, 1, 1); + }, + + "test: toggle comment lines twice should return the original text": function () { + var session = new AceAjax.EditSession([" abc", "cde", "fg"], new JavaScriptMode()); + var editor = new AceAjax.Editor(new MockRenderer(), session); + + editor.moveCursorTo(0, 0); + editor.getSelection().selectDown(); + editor.getSelection().selectDown(); + + editor.toggleCommentLines(); + editor.toggleCommentLines(); + + assert.equal([" abc", "cde", "fg"].join("\n"), session.toString()); + }, + + + "test: comment lines - if the selection end is at the line start it should stay there": function () { + //select down + var session = new AceAjax.EditSession(["abc", "cde"].join("\n"), new JavaScriptMode()); + var editor = new AceAjax.Editor(new MockRenderer(), session); + + editor.moveCursorTo(0, 0); + editor.getSelection().selectDown(); + + editor.toggleCommentLines(); + assert.range(editor.getSelectionRange(), 0, 2, 1, 0); + + // select up + var session = new AceAjax.EditSession(["abc", "cde"].join("\n"), new JavaScriptMode()); + var editor = new AceAjax.Editor(new MockRenderer(), session); + + editor.moveCursorTo(1, 0); + editor.getSelection().selectUp(); + + editor.toggleCommentLines(); + assert.range(editor.getSelectionRange(), 0, 2, 1, 0); + }, + + "test: move lines down should select moved lines": function () { + var session = new AceAjax.EditSession(["11", "22", "33", "44"].join("\n")); + var editor = new AceAjax.Editor(new MockRenderer(), session); + + editor.moveCursorTo(0, 1); + editor.getSelection().selectDown(); + + editor.moveLinesDown(); + assert.equal(["33", "11", "22", "44"].join("\n"), session.toString()); + assert.position(editor.getCursorPosition(), 1, 0); + assert.position(editor.getSelection().getSelectionAnchor(), 3, 0); + assert.position(editor.getSelection().getSelectionLead(), 1, 0); + + editor.moveLinesDown(); + assert.equal(["33", "44", "11", "22"].join("\n"), session.toString()); + assert.position(editor.getCursorPosition(), 2, 0); + assert.position(editor.getSelection().getSelectionAnchor(), 3, 2); + assert.position(editor.getSelection().getSelectionLead(), 2, 0); + + // moving again should have no effect + editor.moveLinesDown(); + assert.equal(["33", "44", "11", "22"].join("\n"), session.toString()); + assert.position(editor.getCursorPosition(), 2, 0); + assert.position(editor.getSelection().getSelectionAnchor(), 3, 2); + assert.position(editor.getSelection().getSelectionLead(), 2, 0); + }, + + "test: move lines up should select moved lines": function () { + var session = new AceAjax.EditSession(["11", "22", "33", "44"].join("\n")); + var editor = new AceAjax.Editor(new MockRenderer(), session); + + editor.moveCursorTo(2, 1); + editor.getSelection().selectDown(); + + editor.moveLinesUp(); + assert.equal(session.toString(), ["11", "33", "44", "22"].join("\n")); + assert.position(editor.getCursorPosition(), 1, 0); + assert.position(editor.getSelection().getSelectionAnchor(), 3, 0); + assert.position(editor.getSelection().getSelectionLead(), 1, 0); + + editor.moveLinesUp(); + assert.equal(session.toString(), ["33", "44", "11", "22"].join("\n")); + assert.position(editor.getCursorPosition(), 0, 0); + assert.position(editor.getSelection().getSelectionAnchor(), 2, 0); + assert.position(editor.getSelection().getSelectionLead(), 0, 0); + }, + + "test: move line without active selection should not move cursor relative to the moved line": function () { + var session = new AceAjax.EditSession(["11", "22", "33", "44"].join("\n")); + var editor = new AceAjax.Editor(new MockRenderer(), session); + + editor.moveCursorTo(1, 1); + editor.clearSelection(); + + editor.moveLinesDown(); + assert.equal(["11", "33", "22", "44"].join("\n"), session.toString()); + assert.position(editor.getCursorPosition(), 2, 1); + + editor.clearSelection(); + + editor.moveLinesUp(); + assert.equal(["11", "22", "33", "44"].join("\n"), session.toString()); + assert.position(editor.getCursorPosition(), 1, 1); + }, + + "test: copy lines down should select lines and place cursor at the selection start": function () { + var session = new AceAjax.EditSession(["11", "22", "33", "44"].join("\n")); + var editor = new AceAjax.Editor(new MockRenderer(), session); + + editor.moveCursorTo(1, 1); + editor.getSelection().selectDown(); + + editor.copyLinesDown(); + assert.equal(["11", "22", "33", "22", "33", "44"].join("\n"), session.toString()); + + assert.position(editor.getCursorPosition(), 3, 0); + assert.position(editor.getSelection().getSelectionAnchor(), 5, 0); + assert.position(editor.getSelection().getSelectionLead(), 3, 0); + }, + + "test: copy lines up should select lines and place cursor at the selection start": function () { + var session = new AceAjax.EditSession(["11", "22", "33", "44"].join("\n")); + var editor = new AceAjax.Editor(new MockRenderer(), session); + + editor.moveCursorTo(1, 1); + editor.getSelection().selectDown(); + + editor.copyLinesUp(); + assert.equal(["11", "22", "33", "22", "33", "44"].join("\n"), session.toString()); + + assert.position(editor.getCursorPosition(), 1, 0); + assert.position(editor.getSelection().getSelectionAnchor(), 3, 0); + assert.position(editor.getSelection().getSelectionLead(), 1, 0); + }, + + "test: input a tab with soft tab should convert it to spaces": function () { + var session = new AceAjax.EditSession(""); + var editor = new AceAjax.Editor(new MockRenderer(), session); + + session.setTabSize(2); + session.setUseSoftTabs(true); + + editor.onTextInput("\t"); + assert.equal(session.toString(), " "); + + session.setTabSize(5); + editor.onTextInput("\t"); + assert.equal(session.toString(), " "); + }, + + "test: input tab without soft tabs should keep the tab character": function () { + var session = new AceAjax.EditSession(""); + var editor = new AceAjax.Editor(new MockRenderer(), session); + + session.setUseSoftTabs(false); + + editor.onTextInput("\t"); + assert.equal(session.toString(), "\t"); + }, + + "test: undo/redo for delete line": function () { + var session = new AceAjax.EditSession(["111", "222", "333"]); + var undoManager = new AceAjax.UndoManager(); + session.setUndoManager(undoManager); + + var initialText = session.toString(); + var editor = new AceAjax.Editor(new MockRenderer(), session); + + editor.removeLines(); + var step1 = session.toString(); + assert.equal(step1, "222\n333"); + + editor.removeLines(); + var step2 = session.toString(); + assert.equal(step2, "333"); + + editor.removeLines(); + var step3 = session.toString(); + assert.equal(step3, ""); + + undoManager.undo(); + assert.equal(session.toString(), step2); + + undoManager.undo(); + assert.equal(session.toString(), step1); + + undoManager.undo(); + assert.equal(session.toString(), initialText); + + undoManager.undo(); + assert.equal(session.toString(), initialText); + }, + + "test: remove left should remove character left of the cursor": function () { + var session = new AceAjax.EditSession(["123", "456"]); + + var editor = new AceAjax.Editor(new MockRenderer(), session); + editor.moveCursorTo(1, 1); + editor.remove("left"); + assert.equal(session.toString(), "123\n56"); + }, + + "test: remove left should remove line break if cursor is at line start": function () { + var session = new AceAjax.EditSession(["123", "456"]); + + var editor = new AceAjax.Editor(new MockRenderer(), session); + editor.moveCursorTo(1, 0); + editor.remove("left"); + assert.equal(session.toString(), "123456"); + }, + + "test: remove left should remove tabsize spaces if cursor is on a tab stop and preceeded by spaces": function () { + var session = new AceAjax.EditSession(["123", " 456"]); + session.setUseSoftTabs(true); + session.setTabSize(4); + + var editor = new AceAjax.Editor(new MockRenderer(), session); + editor.moveCursorTo(1, 8); + editor.remove("left"); + assert.equal(session.toString(), "123\n 456"); + }, + + "test: transpose at line start should be a noop": function () { + var session = new AceAjax.EditSession(["123", "4567", "89"]); + + var editor = new AceAjax.Editor(new MockRenderer(), session); + editor.moveCursorTo(1, 0); + editor.transposeLetters(); + + assert.equal(session.getValue(), ["123", "4567", "89"].join("\n")); + }, + + "test: transpose in line should swap the charaters before and after the cursor": function () { + var session = new AceAjax.EditSession(["123", "4567", "89"]); + + var editor = new AceAjax.Editor(new MockRenderer(), session); + editor.moveCursorTo(1, 2); + editor.transposeLetters(); + + assert.equal(session.getValue(), ["123", "4657", "89"].join("\n")); + }, + + "test: transpose at line end should swap the last two characters": function () { + var session = new AceAjax.EditSession(["123", "4567", "89"]); + + var editor = new AceAjax.Editor(new MockRenderer(), session); + editor.moveCursorTo(1, 4); + editor.transposeLetters(); + + assert.equal(session.getValue(), ["123", "4576", "89"].join("\n")); + }, + + "test: transpose with non empty selection should be a noop": function () { + var session = new AceAjax.EditSession(["123", "4567", "89"]); + + var editor = new AceAjax.Editor(new MockRenderer(), session); + editor.moveCursorTo(1, 1); + editor.getSelection().selectRight(); + editor.transposeLetters(); + + assert.equal(session.getValue(), ["123", "4567", "89"].join("\n")); + }, + + "test: transpose should move the cursor behind the last swapped character": function () { + var session = new AceAjax.EditSession(["123", "4567", "89"]); + + var editor = new AceAjax.Editor(new MockRenderer(), session); + editor.moveCursorTo(1, 2); + editor.transposeLetters(); + assert.position(editor.getCursorPosition(), 1, 3); + }, + + "test: remove to line end": function () { + var session = new AceAjax.EditSession(["123", "4567", "89"]); + + var editor = new AceAjax.Editor(new MockRenderer(), session); + editor.moveCursorTo(1, 2); + editor.removeToLineEnd(); + assert.equal(session.getValue(), ["123", "45", "89"].join("\n")); + }, + + "test: remove to line end at line end should remove the new line": function () { + var session = new AceAjax.EditSession(["123", "4567", "89"]); + + var editor = new AceAjax.Editor(new MockRenderer(), session); + editor.moveCursorTo(1, 4); + editor.removeToLineEnd(); + assert.position(editor.getCursorPosition(), 1, 4); + assert.equal(session.getValue(), ["123", "456789"].join("\n")); + }, + + "test: transform selection to uppercase": function () { + var session = new AceAjax.EditSession(["ajax", "dot", "org"]); + + var editor = new AceAjax.Editor(new MockRenderer(), session); + editor.moveCursorTo(1, 0); + editor.getSelection().selectLineEnd(); + editor.toUpperCase() + assert.equal(session.getValue(), ["ajax", "DOT", "org"].join("\n")); + }, + + "test: transform word to uppercase": function () { + var session = new AceAjax.EditSession(["ajax", "dot", "org"]); + + var editor = new AceAjax.Editor(new MockRenderer(), session); + editor.moveCursorTo(1, 0); + editor.toUpperCase() + assert.equal(session.getValue(), ["ajax", "DOT", "org"].join("\n")); + assert.position(editor.getCursorPosition(), 1, 0); + }, + + "test: transform selection to lowercase": function () { + var session = new AceAjax.EditSession(["AJAX", "DOT", "ORG"]); + + var editor = new AceAjax.Editor(new MockRenderer(), session); + editor.moveCursorTo(1, 0); + editor.getSelection().selectLineEnd(); + editor.toLowerCase() + assert.equal(session.getValue(), ["AJAX", "dot", "ORG"].join("\n")); + }, + + "test: transform word to lowercase": function () { + var session = new AceAjax.EditSession(["AJAX", "DOT", "ORG"]); + + var editor = new AceAjax.Editor(new MockRenderer(), session); + editor.moveCursorTo(1, 0); + editor.toLowerCase() + assert.equal(session.getValue(), ["AJAX", "dot", "ORG"].join("\n")); + assert.position(editor.getCursorPosition(), 1, 0); + } +}; \ No newline at end of file diff --git a/ace/tests/ace-multi_select-tests.ts b/ace/tests/ace-multi_select-tests.ts new file mode 100644 index 0000000000..ade1493e23 --- /dev/null +++ b/ace/tests/ace-multi_select-tests.ts @@ -0,0 +1,111 @@ +/// + +var exec = function (name?, times?, args?) { + do { + editor.commands.exec(name, editor, args); + } while (times-- > 1) +}; +var testRanges = function (str) { + assert.equal(editor.selection.getAllRanges() + "", str + ""); +} + +exports = { + + name: "ACE multi_select.js", + + "test: multiselect editing": function() { + var doc = new AceAjax.EditSession([ + "w1.w2", + " wtt.w", + " wtt.w" + ]); + editor = new AceAjax.Editor(new MockRenderer(), doc); + + editor.navigateFileEnd(); + exec("selectMoreBefore", 3); + assert.ok(editor.inMultiSelectMode); + assert.equal(editor.selection.getAllRanges().length, 4); + + var newLine = editor.session.getDocument().getNewLineCharacter(); + var copyText = "wwww".split("").join(newLine); + assert.equal(editor.getCopyText(), copyText); + exec("insertstring", 1, "a"); + exec("backspace", 2); + assert.equal(editor.session.getValue(), "w1.w2\ntt\ntt"); + assert.equal(editor.selection.getAllRanges().length, 4); + + exec("selectall"); + assert.ok(!editor.inMultiSelectMode); + //assert.equal(editor.selection.getAllRanges().length, 1); + } , + + "test: multiselect navigation": function() { + var doc = new AceAjax.EditSession([ + "w1.w2", + " wtt.w", + " wtt.we" + ]); + editor = new AceAjax.Editor(new MockRenderer(), doc); + + editor.selectMoreLines(1); + testRanges("Range: [0/0] -> [0/0],Range: [1/0] -> [1/0]"); + assert.ok(editor.inMultiSelectMode); + + exec("golinedown"); + exec("gotolineend"); + testRanges("Range: [1/9] -> [1/9],Range: [2/10] -> [2/10]"); + exec("selectwordleft"); + + testRanges("Range: [1/8] -> [1/9],Range: [2/8] -> [2/10]"); + exec("golinedown", 2); + assert.ok(!editor.inMultiSelectMode); + } , + + "test: multiselect session change": function() { + var doc = new AceAjax.EditSession([ + "w1.w2", + " wtt.w", + " wtt.w" + ]); + editor = new AceAjax.Editor(new MockRenderer(), doc); + + editor.selectMoreLines(1) + testRanges("Range: [0/0] -> [0/0],Range: [1/0] -> [1/0]"); + assert.ok(editor.inMultiSelectMode); + + var doc2 = new AceAjax.EditSession(["w1"]); + editor.setSession(doc2); + assert.ok(!editor.inMultiSelectMode); + + editor.setSession(doc); + assert.ok(editor.inMultiSelectMode); + } , + + "test: multiselect addRange": function() { + var doc = new AceAjax.EditSession([ + "w1.w2", + " wtt.w", + " wtt.w" + ]); + editor = new AceAjax.Editor(new MockRenderer(), doc); + + var selection = editor.selection; + + var range1 = new AceAjax.Range(0, 2, 0, 4); + editor.selection.fromOrientedRange(range1); + + var range2 = new AceAjax.Range(0, 3, 0, 4); + selection.addRange(range2); + assert.ok(!editor.inMultiSelectMode); + assert.ok(range2.isEqual(editor.selection.getRange())); + + var range3 = new AceAjax.Range(0, 1, 0, 1); + selection.addRange(range3); + assert.ok(editor.inMultiSelectMode); + testRanges([range3, range2]); + + var range4 = new AceAjax.Range(0, 0, 4, 0); + selection.addRange(range4); + assert.ok(!editor.inMultiSelectMode); + } +}; diff --git a/ace/tests/ace-placeholder-tests.ts b/ace/tests/ace-placeholder-tests.ts new file mode 100644 index 0000000000..124554cf7d --- /dev/null +++ b/ace/tests/ace-placeholder-tests.ts @@ -0,0 +1,106 @@ +/// + +exports = { + + "test: simple at the end appending of text": function () { + var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);", new JavaScriptMode()); + var editor = new AceAjax.Editor(new MockRenderer(), session); + + new AceAjax.PlaceHolder(session, 1, { row: 0, column: 4 }, [{ row: 1, column: 12 }, { row: 1, column: 15 }]); + + editor.moveCursorTo(0, 5); + editor.insert('b'); + assert.equal(session.doc.getValue(), "var ab = 10;\nconsole.log(ab, ab);"); + editor.insert('cd'); + assert.equal(session.doc.getValue(), "var abcd = 10;\nconsole.log(abcd, abcd);"); + editor.remove('left'); + editor.remove('left'); + editor.remove('left'); + assert.equal(session.doc.getValue(), "var a = 10;\nconsole.log(a, a);"); + }, + + "test: inserting text outside placeholder": function () { + var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);\n", new JavaScriptMode()); + var editor = new AceAjax.Editor(new MockRenderer(), session); + + new AceAjax.PlaceHolder(session, 1, { row: 0, column: 4 }, [{ row: 1, column: 12 }, { row: 1, column: 15 }]); + + editor.moveCursorTo(2, 0); + editor.insert('b'); + assert.equal(session.doc.getValue(), "var a = 10;\nconsole.log(a, a);\nb"); + }, + + "test: insertion at the beginning": function (next) { + var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);", new JavaScriptMode()); + var editor = new AceAjax.Editor(new MockRenderer(), session); + + var p = new AceAjax.PlaceHolder(session, 1, { row: 0, column: 4 }, [{ row: 1, column: 12 }, { row: 1, column: 15 }]); + + editor.moveCursorTo(0, 4); + editor.insert('$'); + assert.equal(session.doc.getValue(), "var $a = 10;\nconsole.log($a, $a);"); + editor.moveCursorTo(0, 4); + // Have to put this in a setTimeout because the anchor is only fixed later. + setTimeout(function () { + editor.insert('v'); + assert.equal(session.doc.getValue(), "var v$a = 10;\nconsole.log(v$a, v$a);"); + next(); + }, 10); + }, + + "test: detaching placeholder": function () { + var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);", new JavaScriptMode()); + var editor = new AceAjax.Editor(new MockRenderer(), session); + + var p = new AceAjax.PlaceHolder(session, 1, { row: 0, column: 4 }, [{ row: 1, column: 12 }, { row: 1, column: 15 }]); + + editor.moveCursorTo(0, 5); + editor.insert('b'); + assert.equal(session.doc.getValue(), "var ab = 10;\nconsole.log(ab, ab);"); + p.detach(); + editor.insert('cd'); + assert.equal(session.doc.getValue(), "var abcd = 10;\nconsole.log(ab, ab);"); + }, + + "test: events": function () { + var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);", new JavaScriptMode()); + var editor = new AceAjax.Editor(new MockRenderer(), session); + + var p = new AceAjax.PlaceHolder(session, 1, { row: 0, column: 4 }, [{ row: 1, column: 12 }, { row: 1, column: 15 }]); + var entered = false; + var left = false; + p.on("cursorEnter", function () { + entered = true; + }); + p.on("cursorLeave", function () { + left = true; + }); + + editor.moveCursorTo(0, 0); + editor.moveCursorTo(0, 4); + p.onCursorChange(); // Have to do this by hand because moveCursorTo doesn't trigger the event + assert.ok(entered); + editor.moveCursorTo(1, 0); + p.onCursorChange(); // Have to do this by hand because moveCursorTo doesn't trigger the event + assert.ok(left); + }, + + "test: cancel": function (next) { + var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);", new JavaScriptMode()); + session.setUndoManager(new AceAjax.UndoManager()); + var editor = new AceAjax.Editor(new MockRenderer(), session); + var p = new AceAjax.PlaceHolder(session, 1, { row: 0, column: 4 }, [{ row: 1, column: 12 }, { row: 1, column: 15 }]); + + editor.moveCursorTo(0, 5); + editor.insert('b'); + editor.insert('cd'); + editor.remove('left'); + assert.equal(session.doc.getValue(), "var abc = 10;\nconsole.log(abc, abc);"); + // Wait a little for the changes to enter the undo stack + setTimeout(function () { + p.cancel(); + assert.equal(session.doc.getValue(), "var a = 10;\nconsole.log(a, a);"); + next(); + }, 80); + } +}; diff --git a/ace/tests/ace-range-tests.ts b/ace/tests/ace-range-tests.ts new file mode 100644 index 0000000000..8a1b1ccc65 --- /dev/null +++ b/ace/tests/ace-range-tests.ts @@ -0,0 +1,146 @@ +/// + +exports = { + + name: "ACE range.js", + + "test: create range": function () { + var range = new AceAjax.Range(1, 2, 3, 4); + + assert.equal(range.start.row, 1); + assert.equal(range.start.column, 2); + assert.equal(range.end.row, 3); + assert.equal(range.end.column, 4); + }, + + "test: create from points": function () { + var range = AceAjax.Range.fromPoints({ row: 1, column: 2 }, { row: 3, column: 4 }); + + assert.equal(range.start.row, 1); + assert.equal(range.start.column, 2); + assert.equal(range.end.row, 3); + assert.equal(range.end.column, 4); + }, + + "test: clip to rows": function () { + assert.range(new AceAjax.Range(0, 20, 100, 30).clipRows(10, 30), 10, 0, 31, 0); + assert.range(new AceAjax.Range(0, 20, 30, 10).clipRows(10, 30), 10, 0, 30, 10); + + var range = new AceAjax.Range(0, 20, 3, 10); + var range = range.clipRows(10, 30); + + assert.ok(range.isEmpty()); + assert.range(range, 10, 0, 10, 0); + }, + + "test: isEmpty": function () { + var range = new AceAjax.Range(1, 2, 1, 2); + assert.ok(range.isEmpty()); + + var range = new AceAjax.Range(1, 2, 1, 6); + assert.notOk(range.isEmpty()); + }, + + "test: is multi line": function () { + var range = new AceAjax.Range(1, 2, 1, 6); + assert.notOk(range.isMultiLine()); + + var range = new AceAjax.Range(1, 2, 2, 6); + assert.ok(range.isMultiLine()); + }, + + "test: clone": function () { + var range = new AceAjax.Range(1, 2, 3, 4); + var clone = range.clone(); + + assert.position(clone.start, 1, 2); + assert.position(clone.end, 3, 4); + + clone.start.column = 20; + assert.position(range.start, 1, 2); + + clone.end.column = 20; + assert.position(range.end, 3, 4); + }, + + "test: contains for multi line ranges": function () { + var range = new AceAjax.Range(1, 10, 5, 20); + + assert.ok(range.contains(1, 10)); + assert.ok(range.contains(2, 0)); + assert.ok(range.contains(3, 100)); + assert.ok(range.contains(5, 19)); + assert.ok(range.contains(5, 20)); + + assert.notOk(range.contains(1, 9)); + assert.notOk(range.contains(0, 0)); + assert.notOk(range.contains(5, 21)); + }, + + "test: contains for single line ranges": function () { + var range = new AceAjax.Range(1, 10, 1, 20); + + assert.ok(range.contains(1, 10)); + assert.ok(range.contains(1, 15)); + assert.ok(range.contains(1, 20)); + + assert.notOk(range.contains(0, 9)); + assert.notOk(range.contains(2, 9)); + assert.notOk(range.contains(1, 9)); + assert.notOk(range.contains(1, 21)); + }, + + "test: extend range": function () { + var range = new AceAjax.Range(2, 10, 2, 30); + + var range = range.extend(2, 5); + assert.range(range, 2, 5, 2, 30); + + var range = range.extend(2, 35); + assert.range(range, 2, 5, 2, 35); + + var range = range.extend(2, 15); + assert.range(range, 2, 5, 2, 35); + + var range = range.extend(1, 4); + assert.range(range, 1, 4, 2, 35); + + var range = range.extend(6, 10); + assert.range(range, 1, 4, 6, 10); + }, + + "test: collapse rows": function () { + var range = new AceAjax.Range(0, 2, 1, 2); + assert.range(range.collapseRows(), 0, 0, 1, 0); + + var range = new AceAjax.Range(2, 2, 3, 1); + assert.range(range.collapseRows(), 2, 0, 3, 0); + + var range = new AceAjax.Range(2, 2, 3, 0); + assert.range(range.collapseRows(), 2, 0, 2, 0); + + var range = new AceAjax.Range(2, 0, 2, 0); + assert.range(range.collapseRows(), 2, 0, 2, 0); + }, + + "test: to screen range": function () { + var session = new AceAjax.EditSession([ + "juhu", + "12\t\t34", + "ぁぁa", + "\t\t34", + ]); + + var range = new AceAjax.Range(0, 0, 0, 3); + assert.range(range.toScreenRange(session), 0, 0, 0, 3); + + var range = new AceAjax.Range(1, 1, 1, 3); + assert.range(range.toScreenRange(session), 1, 1, 1, 4); + + var range = new AceAjax.Range(2, 1, 2, 2); + assert.range(range.toScreenRange(session), 2, 2, 2, 4); + + var range = new AceAjax.Range(3, 0, 3, 4); + assert.range(range.toScreenRange(session), 3, 0, 3, 10); + } +}; diff --git a/ace/tests/ace-range_list-tests.ts b/ace/tests/ace-range_list-tests.ts new file mode 100644 index 0000000000..83f3c8a91c --- /dev/null +++ b/ace/tests/ace-range_list-tests.ts @@ -0,0 +1,117 @@ +/// + +function flatten(rangeList) { + var points = []; + rangeList.ranges.forEach(function (r) { + points.push(r.start.row, r.start.column, r.end.row, r.end.column) + }) + return points; +} +function testRangeList(rangeList, points) { + assert.equal("" + flatten(rangeList), "" + points); +} + +exports = { + + name: "ACE range_list.js", + + "test: rangeList pointIndex": function() { + var rangeList = new AceAjax.RangeList(); + rangeList.ranges = [ + new AceAjax.Range(1, 2, 3, 4), + new AceAjax.Range(4, 2, 5, 4), + new AceAjax.Range(8, 8, 9, 9) + ]; + + assert.equal(rangeList.pointIndex({ row: 0, column: 1 }), -1); + assert.equal(rangeList.pointIndex({ row: 1, column: 2 }), 0); + assert.equal(rangeList.pointIndex({ row: 1, column: 3 }), 0); + assert.equal(rangeList.pointIndex({ row: 3, column: 4 }), 0); + assert.equal(rangeList.pointIndex({ row: 4, column: 1 }), -2); + assert.equal(rangeList.pointIndex({ row: 5, column: 1 }), 1); + assert.equal(rangeList.pointIndex({ row: 8, column: 9 }), 2); + assert.equal(rangeList.pointIndex({ row: 18, column: 9 }), -4); + } , + + "test: rangeList add": function() { + var rangeList = new AceAjax.RangeList(); + rangeList.addList([ + new AceAjax.Range(9, 0, 9, 1), + new AceAjax.Range(1, 2, 3, 4), + new AceAjax.Range(8, 8, 9, 9), + new AceAjax.Range(4, 2, 5, 4), + new AceAjax.Range(3, 20, 3, 24), + new AceAjax.Range(6, 6, 7, 7) + ]); + assert.equal(rangeList.ranges.length, 5); + + rangeList.add(new AceAjax.Range(1, 2, 3, 5)); + assert.range(rangeList.ranges[0], 1, 2, 3, 5); + assert.equal(rangeList.ranges.length, 5); + + rangeList.add(new AceAjax.Range(7, 7, 7, 7)); + assert.range(rangeList.ranges[3], 7, 7, 7, 7); + rangeList.add(new AceAjax.Range(7, 8, 7, 8)); + assert.range(rangeList.ranges[4], 7, 8, 7, 8); + } , + + "test: rangeList add empty": function() { + var rangeList = new AceAjax.RangeList(); + rangeList.addList([ + new AceAjax.Range(7, 10, 7, 10), + new AceAjax.Range(9, 10, 9, 10), + new AceAjax.Range(8, 10, 8, 10) + ]); + assert.equal(rangeList.ranges.length, 3); + + rangeList.add(new AceAjax.Range(9, 10, 9, 10)); + testRangeList(rangeList, [7, 10, 7, 10, 8, 10, 8, 10, 9, 10, 9, 10]); + } , + + "test: rangeList merge": function() { + var rangeList = new AceAjax.RangeList(); + rangeList.addList([ + new AceAjax.Range(1, 2, 3, 4), + new AceAjax.Range(4, 2, 5, 4), + new AceAjax.Range(6, 6, 7, 7), + new AceAjax.Range(8, 8, 9, 9) + ]); + var removed = []; + + assert.equal(rangeList.ranges.length, 4); + + rangeList.ranges[1].end.row = 7; + removed = rangeList.merge(); + assert.equal(removed.length, 1); + assert.range(rangeList.ranges[1], 4, 2, 7, 7); + assert.equal(rangeList.ranges.length, 3); + + rangeList.ranges[0].end.row = 10; + removed = rangeList.merge(); + assert.range(rangeList.ranges[0], 1, 2, 10, 4); + assert.equal(removed.length, 2); + assert.equal(rangeList.ranges.length, 1); + + rangeList.ranges.push(new AceAjax.Range(10, 10, 10, 10)); + rangeList.ranges.push(new AceAjax.Range(10, 10, 10, 10)); + removed = rangeList.merge(); + assert.equal(rangeList.ranges.length, 2); + } , + + "test: rangeList remove": function() { + var rangeList = new AceAjax.RangeList(); + var list = [ + new AceAjax.Range(1, 2, 3, 4), + new AceAjax.Range(4, 2, 5, 4), + new AceAjax.Range(6, 6, 7, 7), + new AceAjax.Range(8, 8, 9, 9) + ]; + rangeList.addList(list); + assert.equal(rangeList.ranges.length, 4); + rangeList.substractPoint({ row: 1, column: 2 }); + assert.equal(rangeList.ranges.length, 3); + rangeList.substractPoint({ row: 6, column: 7 }); + assert.equal(rangeList.ranges.length, 2); + } + +}; diff --git a/ace/tests/ace-search-tests.ts b/ace/tests/ace-search-tests.ts new file mode 100644 index 0000000000..c30139d656 --- /dev/null +++ b/ace/tests/ace-search-tests.ts @@ -0,0 +1,416 @@ +/// + +exports = { + "test: configure the search object": function () { + var search = new AceAjax.Search(); + search.set({ + needle: "juhu" + }); + }, + + "test: find simple text in document": function () { + var session = new AceAjax.EditSession(["juhu kinners 123", "456"]); + var search = new AceAjax.Search().set({ + needle: "kinners" + }); + + var range = search.find(session); + assert.position(range.start, 0, 5); + assert.position(range.end, 0, 12); + }, + + "test: find simple text in next line": function () { + var session = new AceAjax.EditSession(["abc", "juhu kinners 123", "456"]); + var search = new AceAjax.Search().set({ + needle: "kinners" + }); + + var range = search.find(session); + assert.position(range.start, 1, 5); + assert.position(range.end, 1, 12); + }, + + "test: find text starting at cursor position": function () { + var session = new AceAjax.EditSession(["juhu kinners", "juhu kinners 123"]); + session.getSelection().moveCursorTo(0, 6); + var search = new AceAjax.Search().set({ + needle: "kinners" + }); + + var range = search.find(session); + assert.position(range.start, 1, 5); + assert.position(range.end, 1, 12); + }, + + "test: wrap search is on by default": function () { + var session = new AceAjax.EditSession(["abc", "juhu kinners 123", "456"]); + session.getSelection().moveCursorTo(2, 1); + + var search = new AceAjax.Search().set({ + needle: "kinners" + }); + + assert.notEqual(search.find(session), null); + }, + + "test: wrap search should wrap at file end": function () { + var session = new AceAjax.EditSession(["abc", "juhu kinners 123", "456"]); + session.getSelection().moveCursorTo(2, 1); + + var search = new AceAjax.Search().set({ + needle: "kinners", + wrap: true + }); + + var range = search.find(session); + assert.position(range.start, 1, 5); + assert.position(range.end, 1, 12); + }, + + "test: wrap search should find needle even if it starts inside it": function () { + var session = new AceAjax.EditSession(["abc", "juhu kinners 123", "456"]); + session.getSelection().moveCursorTo(6, 1); + + var search = new AceAjax.Search().set({ + needle: "kinners", + wrap: true + }); + + var range = search.find(session); + assert.position(range.start, 1, 5); + assert.position(range.end, 1, 12); + }, + + "test: wrap search with no match should return 'null'": function () { + var session = new AceAjax.EditSession(["abc", "juhu kinners 123", "456"]); + session.getSelection().moveCursorTo(2, 1); + + var search = new AceAjax.Search().set({ + needle: "xyz", + wrap: true + }); + + assert.equal(search.find(session), null); + }, + + "test: case sensitive is by default off": function () { + var session = new AceAjax.EditSession(["abc", "juhu kinners 123", "456"]); + + var search = new AceAjax.Search().set({ + needle: "JUHU" + }); + + assert.range(search.find(session), 1, 0, 1, 4); + }, + + "test: case sensitive search": function () { + var session = new AceAjax.EditSession(["abc", "juhu kinners 123", "456"]); + + var search = new AceAjax.Search().set({ + needle: "KINNERS", + caseSensitive: true + }); + + var range = search.find(session); + assert.equal(range, null); + }, + + "test: whole word search should not match inside of words": function () { + var session = new AceAjax.EditSession(["juhukinners", "juhu kinners 123", "456"]); + + var search = new AceAjax.Search().set({ + needle: "kinners", + wholeWord: true + }); + + var range = search.find(session); + assert.position(range.start, 1, 5); + assert.position(range.end, 1, 12); + }, + + "test: find backwards": function () { + var session = new AceAjax.EditSession(["juhu juhu juhu juhu"]); + session.getSelection().moveCursorTo(0, 10); + var search = new AceAjax.Search().set({ + needle: "juhu", + backwards: true + }); + + var range = search.find(session); + assert.position(range.start, 0, 5); + assert.position(range.end, 0, 9); + }, + + "test: find in selection": function () { + var session = new AceAjax.EditSession(["juhu", "juhu", "juhu", "juhu"]); + session.getSelection().setSelectionAnchor(1, 0); + session.getSelection().selectTo(3, 5); + + var search = new AceAjax.Search().set({ + needle: "juhu", + wrap: true, + range: session.getSelection().getRange() + }); + + var range = search.find(session); + assert.position(range.start, 1, 0); + assert.position(range.end, 1, 4); + + search = new AceAjax.Search().set({ + needle: "juhu", + wrap: true, + range: session.getSelection().getRange() + }); + + session.getSelection().setSelectionAnchor(0, 2); + session.getSelection().selectTo(3, 2); + + var range = search.find(session); + assert.position(range.start, 1, 0); + assert.position(range.end, 1, 4); + }, + + "test: find backwards in selection": function () { + var session = new AceAjax.EditSession(["juhu", "juhu", "juhu", "juhu"]); + + session.getSelection().setSelectionAnchor(0, 2); + session.getSelection().selectTo(3, 2); + + var search = new AceAjax.Search().set({ + needle: "juhu", + wrap: true, + backwards: true, + range: session.getSelection().getRange() + }); + + var range = search.find(session); + assert.position(range.start, 2, 0); + assert.position(range.end, 2, 4); + + search = new AceAjax.Search().set({ + needle: "juhu", + wrap: true, + range: session.getSelection().getRange() + }); + + session.getSelection().setSelectionAnchor(0, 2); + session.getSelection().selectTo(1, 2); + + var range = search.find(session); + assert.position(range.start, 1, 0); + assert.position(range.end, 1, 4); + }, + + "test: edge case - match directly before the cursor": function () { + var session = new AceAjax.EditSession(["123", "123", "juhu"]); + + var search = new AceAjax.Search().set({ + needle: "juhu", + wrap: true + }); + + session.getSelection().moveCursorTo(2, 5); + + var range = search.find(session); + assert.position(range.start, 2, 0); + assert.position(range.end, 2, 4); + }, + + "test: edge case - match backwards directly after the cursor": function () { + var session = new AceAjax.EditSession(["123", "123", "juhu"]); + + var search = new AceAjax.Search().set({ + needle: "juhu", + wrap: true, + backwards: true + }); + + session.getSelection().moveCursorTo(2, 0); + + var range = search.find(session); + assert.position(range.start, 2, 0); + assert.position(range.end, 2, 4); + }, + + "test: find using a regular expression": function () { + var session = new AceAjax.EditSession(["abc123 123 cd", "abc"]); + + var search = new AceAjax.Search().set({ + needle: "\\d+", + regExp: true + }); + + var range = search.find(session); + assert.position(range.start, 0, 3); + assert.position(range.end, 0, 6); + }, + + "test: find using a regular expression and whole word": function () { + var session = new AceAjax.EditSession(["abc123 123 cd", "abc"]); + + var search = new AceAjax.Search().set({ + needle: "\\d+\\b", + regExp: true, + wholeWord: true + }); + + var range = search.find(session); + assert.position(range.start, 0, 7); + assert.position(range.end, 0, 10); + }, + + "test: use regular expressions with capture groups": function () { + var session = new AceAjax.EditSession([" ab: 12px", "

+ +exports = { + createSession: function (rows, cols) { + var line = new Array(cols + 1).join("a"); + var text = new Array(rows).join(line + "\n") + line; + return new AceAjax.EditSession(text); + }, + + "test: move cursor to end of file should place the cursor on last row and column": function () { + var session = this.createSession(200, 10); + var selection = session.getSelection(); + + selection.moveCursorFileEnd(); + assert.position(selection.getCursor(), 199, 10); + }, + + "test: moveCursor to start of file should place the cursor on the first row and column": function () { + var session = this.createSession(200, 10); + var selection = session.getSelection(); + + selection.moveCursorFileStart(); + assert.position(selection.getCursor(), 0, 0); + }, + + "test: move selection lead to end of file": function () { + var session = this.createSession(200, 10); + var selection = session.getSelection(); + + selection.moveCursorTo(100, 5); + selection.selectFileEnd(); + + var range = selection.getRange(); + + assert.position(range.start, 100, 5); + assert.position(range.end, 199, 10); + }, + + "test: move selection lead to start of file": function () { + var session = this.createSession(200, 10); + var selection = session.getSelection(); + + selection.moveCursorTo(100, 5); + selection.selectFileStart(); + + var range = selection.getRange(); + + assert.position(range.start, 0, 0); + assert.position(range.end, 100, 5); + }, + + "test: move cursor word right": function () { + var session = new AceAjax.EditSession([ + "ab", + " Juhu Kinners (abc, 12)", + " cde" + ].join("\n")); + + var selection = session.getSelection(); + + selection.moveCursorDown(); + assert.position(selection.getCursor(), 1, 0); + + selection.moveCursorWordRight(); + assert.position(selection.getCursor(), 1, 5); + + selection.moveCursorWordRight(); + assert.position(selection.getCursor(), 1, 13); + + selection.moveCursorWordRight(); + assert.position(selection.getCursor(), 1, 18); + + selection.moveCursorWordRight(); + assert.position(selection.getCursor(), 1, 22); + + // wrap line + selection.moveCursorWordRight(); + assert.position(selection.getCursor(), 2, 4); + + selection.moveCursorWordRight(); + assert.position(selection.getCursor(), 2, 4); + }, + + "test: select word right if cursor in word": function () { + var session = new AceAjax.EditSession("Juhu Kinners"); + var selection = session.getSelection(); + + selection.moveCursorTo(0, 2); + selection.moveCursorWordRight(); + + assert.position(selection.getCursor(), 0, 4); + }, + + "test: moveCursor word left": function () { + var session = new AceAjax.EditSession([ + "ab", + " Juhu Kinners (abc, 12)", + " cde" + ].join("\n")); + + var selection = session.getSelection(); + + selection.moveCursorDown(); + selection.moveCursorLineEnd(); + assert.position(selection.getCursor(), 1, 23); + + selection.moveCursorWordLeft(); + assert.position(selection.getCursor(), 1, 20); + + selection.moveCursorWordLeft(); + assert.position(selection.getCursor(), 1, 15); + + selection.moveCursorWordLeft(); + assert.position(selection.getCursor(), 1, 6); + + selection.moveCursorWordLeft(); + assert.position(selection.getCursor(), 1, 1); + + // wrap line + selection.moveCursorWordLeft(); + assert.position(selection.getCursor(), 0, 0); + + selection.moveCursorWordLeft(); + assert.position(selection.getCursor(), 0, 0); + }, + + "test: moveCursor word left with umlauts": function () { + var session = new AceAjax.EditSession(" Fu Fe"); + + var selection = session.getSelection(); + selection.moveCursorTo(0, 9) + selection.moveCursorWordLeft(); + assert.position(selection.getCursor(), 0, 5); + + selection.moveCursorWordLeft(); + assert.position(selection.getCursor(), 0, 1); + }, + + "test: select word left if cursor in word": function () { + var session = new AceAjax.EditSession("Juhu Kinners"); + var selection = session.getSelection(); + + selection.moveCursorTo(0, 8); + + selection.moveCursorWordLeft(); + assert.position(selection.getCursor(), 0, 5); + }, + + "test: select word right and select": function () { + var session = new AceAjax.EditSession("Juhu Kinners"); + var selection = session.getSelection(); + + selection.moveCursorTo(0, 0); + selection.selectWordRight(); + + var range = selection.getRange(); + + assert.position(range.start, 0, 0); + assert.position(range.end, 0, 4); + }, + + "test: select word left and select": function () { + var session = new AceAjax.EditSession("Juhu Kinners"); + var selection = session.getSelection(); + + selection.moveCursorTo(0, 3); + selection.selectWordLeft(); + + var range = selection.getRange(); + + assert.position(range.start, 0, 0); + assert.position(range.end, 0, 3); + }, + + "test: select word with cursor in word should select the word": function () { + var session = new AceAjax.EditSession("Juhu Kinners 123"); + var selection = session.getSelection(); + + selection.moveCursorTo(0, 8); + selection.selectWord(); + + var range = selection.getRange(); + assert.position(range.start, 0, 5); + assert.position(range.end, 0, 12); + }, + + "test: select word with cursor in word including right whitespace should select the word": function () { + var session = new AceAjax.EditSession("Juhu Kinners 123"); + var selection = session.getSelection(); + + selection.moveCursorTo(0, 8); + selection.selectAWord(); + + var range = selection.getRange(); + assert.position(range.start, 0, 5); + assert.position(range.end, 0, 18); + }, + + "test: select word with cursor betwen white space and word should select the word": function () { + var session = new AceAjax.EditSession("Juhu Kinners"); + var selection = session.getSelection(); + + selection.moveCursorTo(0, 4); + selection.selectWord(); + + var range = selection.getRange(); + assert.position(range.start, 0, 0); + assert.position(range.end, 0, 4); + + selection.moveCursorTo(0, 5); + selection.selectWord(); + + var range = selection.getRange(); + assert.position(range.start, 0, 5); + assert.position(range.end, 0, 12); + }, + + "test: select word with cursor in white space should select white space": function () { + var session = new AceAjax.EditSession("Juhu Kinners"); + var selection = session.getSelection(); + + selection.moveCursorTo(0, 5); + selection.selectWord(); + + var range = selection.getRange(); + assert.position(range.start, 0, 4); + assert.position(range.end, 0, 6); + }, + + "test: moving cursor should fire a 'changeCursor' event": function () { + var session = new AceAjax.EditSession("Juhu Kinners"); + var selection = session.getSelection(); + + selection.moveCursorTo(0, 5); + + var called = false; + selection.addEventListener("changeCursor", function () { + called = true; + }); + + selection.moveCursorTo(0, 6); + assert.ok(called); + }, + + "test: calling setCursor with the same position should not fire an event": function () { + var session = new AceAjax.EditSession("Juhu Kinners"); + var selection = session.getSelection(); + + selection.moveCursorTo(0, 5); + + var called = false; + selection.addEventListener("changeCursor", function () { + called = true; + }); + + selection.moveCursorTo(0, 5); + assert.notOk(called); + }, + + "test: moveWordright should move past || and [": function () { + var session = new AceAjax.EditSession("||foo["); + var selection = session.getSelection(); + + // Move behind ||foo + selection.moveCursorWordRight(); + assert.position(selection.getCursor(), 0, 5); + + // Move behind [ + selection.moveCursorWordRight(); + assert.position(selection.getCursor(), 0, 6); + }, + + "test: moveWordLeft should move past || and [": function () { + var session = new AceAjax.EditSession("||foo["); + var selection = session.getSelection(); + + selection.moveCursorTo(0, 6); + + // Move behind [foo + selection.moveCursorWordLeft(); + assert.position(selection.getCursor(), 0, 2); + + // Move behind || + selection.moveCursorWordLeft(); + assert.position(selection.getCursor(), 0, 0); + }, + + "test: move cursor to line start should move cursor to end of the indentation first": function () { + var session = new AceAjax.EditSession("12\n Juhu\n12"); + var selection = session.getSelection(); + + selection.moveCursorTo(1, 6); + selection.moveCursorLineStart(); + + assert.position(selection.getCursor(), 1, 4); + }, + + "test: move cursor to line start when the cursor is at the end of the indentation should move cursor to column 0": function () { + var session = new AceAjax.EditSession("12\n Juhu\n12"); + var selection = session.getSelection(); + + selection.moveCursorTo(1, 4); + selection.moveCursorLineStart(); + + assert.position(selection.getCursor(), 1, 0); + }, + + "test: move cursor to line start when the cursor is at column 0 should move cursor to the end of the indentation": function () { + var session = new AceAjax.EditSession("12\n Juhu\n12"); + var selection = session.getSelection(); + + selection.moveCursorTo(1, 0); + selection.moveCursorLineStart(); + + assert.position(selection.getCursor(), 1, 4); + }, + + // Eclipse style + "test: move cursor to line start when the cursor is before the initial indentation should move cursor to the end of the indentation": function () { + var session = new AceAjax.EditSession("12\n Juhu\n12"); + var selection = session.getSelection(); + + selection.moveCursorTo(1, 2); + selection.moveCursorLineStart(); + + assert.position(selection.getCursor(), 1, 4); + }, + + "test go line up when in the middle of the first line should go to document start": function () { + var session = new AceAjax.EditSession("juhu kinners"); + var selection = session.getSelection(); + + selection.moveCursorTo(0, 4); + selection.moveCursorUp(); + + assert.position(selection.getCursor(), 0, 0); + }, + + "test: (wrap) go line up when in the middle of the first line should go to document start": function () { + var session = new AceAjax.EditSession("juhu kinners"); + session.setWrapLimitRange(5, 5); + session.adjustWrapLimit(80); + + var selection = session.getSelection(); + + selection.moveCursorTo(0, 4); + selection.moveCursorUp(); + + assert.position(selection.getCursor(), 0, 0); + }, + + + "test go line down when in the middle of the last line should go to document end": function () { + var session = new AceAjax.EditSession("juhu kinners"); + var selection = session.getSelection(); + + selection.moveCursorTo(0, 4); + selection.moveCursorDown(); + + assert.position(selection.getCursor(), 0, 12); + }, + + "test (wrap) go line down when in the middle of the last line should go to document end": function () { + var session = new AceAjax.EditSession("juhu kinners"); + session.setWrapLimitRange(8, 8); + session.adjustWrapLimit(80); + + var selection = session.getSelection(); + + selection.moveCursorTo(0, 10); + selection.moveCursorDown(); + + assert.position(selection.getCursor(), 0, 12); + }, + + "test go line up twice and then once down when in the second should go back to the previous column": function () { + var session = new AceAjax.EditSession("juhu\nkinners"); + var selection = session.getSelection(); + + selection.moveCursorTo(1, 4); + selection.moveCursorUp(); + selection.moveCursorUp(); + selection.moveCursorDown(); + + assert.position(selection.getCursor(), 1, 4); + }, + + "test (keyboard navigation) when curLine is not EOL and targetLine is all whitespace new column should be current column": function () { + var session = new AceAjax.EditSession("function (a) {\n\ + \n\ +}"); + var selection = session.getSelection(); + + selection.moveCursorTo(2, 0); + selection.moveCursorUp(); + + assert.position(selection.getCursor(), 1, 0); + }, + + "test (keyboard navigation) when curLine is EOL and targetLine is shorter dan current column, new column should be targetLine's EOL": function () { + var session = new AceAjax.EditSession("function (a) {\n\ + \n\ +}"); + var selection = session.getSelection(); + + selection.moveCursorTo(0, 14); + selection.moveCursorDown(); + + assert.position(selection.getCursor(), 1, 4); + } +}; diff --git a/ace/tests/ace-token_iterator-tests.ts b/ace/tests/ace-token_iterator-tests.ts new file mode 100644 index 0000000000..75260e95a6 --- /dev/null +++ b/ace/tests/ace-token_iterator-tests.ts @@ -0,0 +1,166 @@ +/// + +exports = { + "test: token iterator initialization in JavaScript document": function () { + var lines = [ + "function foo(items) {", + " for (var i=0; i= 0; i--) + assert.equal(iterator.stepBackward(), tokens[i]); + assert.equal(iterator.stepBackward(), null); + assert.equal(iterator.getCurrentToken(), null); + }, + + "test: token iterator reports correct row and column": function () { + var lines = [ + "function foo(items) {", + " for (var i=0; i + +exports = { + "test: screen2text the column should be rounded to the next character edge": function () { + var el = document.createElement("div"); + + if (!el.getBoundingClientRect) { + console.log("Skipping test: This test only runs in the browser"); + return; + } + + el.style.left = "20px"; + el.style.top = "30px"; + el.style.width = "300px"; + el.style.height = "100px"; + document.body.appendChild(el); + + var renderer = new AceAjax.VirtualRenderer(el); + renderer.setPadding(0); + renderer.setSession(new AceAjax.EditSession("1234")); + + var r = renderer.scroller.getBoundingClientRect(); + function testPixelToText(x, y, row, column) { + assert.position(renderer.screenToTextCoordinates(x + r.left, y + r.top), row, column); + } + + renderer.characterWidth = 10; + renderer.lineHeight = 15; + + testPixelToText(4, 0, 0, 0); + testPixelToText(5, 0, 0, 1); + testPixelToText(9, 0, 0, 1); + testPixelToText(10, 0, 0, 1); + testPixelToText(14, 0, 0, 1); + testPixelToText(15, 0, 0, 2); + document.body.removeChild(el); + } + + // change tab size after setDocument (for text layer) +}; diff --git a/amcharts/AmCharts.d.ts b/amcharts/AmCharts.d.ts new file mode 100644 index 0000000000..ca677da7a8 --- /dev/null +++ b/amcharts/AmCharts.d.ts @@ -0,0 +1,2346 @@ +/// AmCharts object (it's not a class) is create automatically when amcharts.js or amstock.js file is included in a web page. +declare module AmChartsStatic { + + /** Set it to true if you have base href set for your page. This will fix rendering problems in Firefox caused by base href. */ + var baseHref: bool; + + /** Array of day names, used when formatting dates (if categoryAxis.parseDates is set to true) ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] */ + var dayNames: string[]; + + /** Array of month names, used when formatting dates (if categoryAxis.parseDates is set to true) ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] */ + var monthNames: string[]; + + /** Array of short versions of day names, used when formatting dates (if categoryAxis.parseDates is set to true) ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] */ + var shortDayNames: string[]; + + /** Array of short versions of month names, used when formatting dates (if categoryAxis.parseDates is set to true) ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] */ + var shortMonthNames: string[]; + + /** Set it to true if you want UTC time to be used instead of local time. */ + var useUTC: bool; + + /** Clears all the charts on page, removes listeners and intervals. */ + function clear(); + + /** AmPieChart class creates pie/donut chart. In order to display pie chart you need to set at least three properties - dataProvider, titleField and valueField. + @example + var chartData = [{title:"Pie I have eaten",value:70},{title:"Pie I haven\'t eaten",value:30}]; + var chart = new AmCharts.AmPieChart(); + chart.valueField = "value"; + chart.titleField = "title"; + chart.dataProvider = chartData; + chart.write("chartdiv"); + */ + declare class AmPieChart { + /** Name of the field in chart's dataProvider which holds slice's alpha. */ + alphaField: string; + /** Pie lean angle (for 3D effect). Valid range is 0 - 90. */ + angle: number; + /** Balloon text. The following tags can be used: [[value]], [[title]], [[percents]], [[description]]. [[title]]: [[percents]]% ([[value]])\n[[description]] */ + balloonText: string; + /** Read-only. Array of Slice objects. */ + chartData: any[]; + /** Name of the field in chart's dataProvider which holds slice's color. */ + colorField: string; + /** Specifies the colors of the slices, if the slice color is not set. If there are more slices than colors in this array, the chart picks random color. ["#FF0F00", "#FF6600", "#FF9E01", "#FCD202", "#F8FF01", "#B0DE09", "#04D215", "#0D8ECF", "#0D52D1", "#2A0CD0", "#8A0CCF", "#CD0D74", "#754DEB", "#DDDDDD", "#999999", "#333333", "#000000", "#57032A", "#CA9726", "#990000", "#4B0C25"] */ + colors: any[]; + /** Depth of the pie (for 3D effect). */ + depth3D: number; + /** Name of the field in chart's dataProvider which holds a string with description. */ + descriptionField: string; + /** Example: [-0.2,0.2]. Will make slices to be filled with color gradients. */ + gradientRatio: number[]; + /** Opacity of the group slice. Value range is 0 - 1. + @default 1 + */ + groupedAlpha: number; + /** Color of the group slice. The default value is not set - this means the next available color from "colors" array will be used. */ + groupedColor: string; + /** Description of the group slice. */ + groupedDescription: string; + /** If this is set to true, the group slice will be pulled out when the chart loads. */ + groupedPulled: bool; + /** Title of the group slice. Other */ + groupedTitle: string; + /** If there is more than one slice whose percentage of the pie is less than this number, those slices will be grouped together into one slice. This is the "other" slice. It will always be the last slice in a pie. */ + groupPercent: number; + /** Slices with percent less then hideLabelsPercent won't display labels This is useful to avoid cluttering up the chart, if you have a lot of small slices. 0 means all labels will be shown. */ + hideLabelsPercent: number; + /** Opacity of a hovered slice. Value range is 0 - 1. + @default 1 + */ + hoverAlpha: number; + /** Inner radius of the pie, in pixels or percents. */ + innerRadius: any; + /** The distance between the label and the slice, in pixels. You can use negative values to put the label on the slice. + @default 30 + */ + labelRadius: number; + /** Name of the field in dataProvider which specifies the length of a tick. Note, the chart will not try to arrange labels automatically if this property is set. */ + labelRadiusField: string; + /** Specifies whether data labels are visible. + @default true + */ + labelsEnabled: bool; + /** Label text. The following tags can be used: [[value]], [[title]], [[percents]], [[description]]. [[title]]: [[percents]]% */ + labelText: string; + /** Label tick opacity. Value range is 0 - 1. 0.2 */ + labelTickAlpha: number; + /** Label tick color. #000000 */ + labelTickColor: string; + /** Bottom margin of the chart. + @default 5 + */ + marginBottom: number; + /** Left margin of the chart. */ + marginLeft: number; + /** Right margin of the chart. */ + marginRight: number; + /** Top margin of the chart. + @default 5 + */ + marginTop: number; + /** Minimum radius of the pie, in pixels. + @default 10 + */ + minRadius: number; + /** Pie outline opacity. Value range is 0 - 1. */ + outlineAlpha: number; + /** Pie outline color. #FFFFFF */ + outlineColor: string; + /** Pie outline thickness. + @default 1 + */ + outlineThickness: number; + /** Opacity of the slices. You can set the opacity of individual slice too. + @default 1 + */ + pieAlpha: number; + /** Color of the first slice. All the other will be colored with darker or brighter colors. */ + pieBaseColor: string; + /** Lightness increase of each subsequent slice. This is only useful if pieBaseColor is set. Use negative values for darker colors. Value range is from -255 to 255. + @default 30*/ + pieBrightnessStep: number; + /** You can set fixed position of a pie center, in pixels or in percents. */ + pieX: any; + /** You can set fixed position of a pie center, in pixels or in percents. */ + pieY: any; + /** Name of the field in chart's dataProvider which holds a boolean value telling the chart whether this slice must be pulled or not. */ + pulledField: string; + /** Pull out duration, in seconds. + @default 1 + */ + pullOutDuration: number; + /** Pull out effect. Possible values are ">", "<", elastic" and "bounce". bounce */ + pullOutEffect: string; + /** If this is set to true, only one slice can be pulled out at a time. If the viewer clicks on a slice, any other pulled-out slice will be pulled in. */ + pullOutOnlyOne: bool; + /** Pull out radius, in pixels or percents 0.2 */ + pullOutRadius: any; + /** Radius of a pie, in pixels or percents. By default, radius is calculated automatically. */ + radius: any; + /** Specifies whether the animation should be sequenced or all slices should appear at once. */ + sequencedAnimation: bool; + /** Initial opacity of all slices. If you set startDuration higher than 0, slices will fade in from startAlpha. + @default 1 + */ + startAlpha: number; + /** Angle of the first slice, in degrees. This will work properly only if "depth3D" is set to 0. If "depth3D" is greater than 0, then there can be two angles only: 90 and 270. Value range is 0-360. + @default 90 + */ + startAngle: number; + /** Duration of the animation, in seconds. + @default 1 + */ + startDuration: number; + /** Animation effect. Possible values are ">", "<", "elastic" and "bounce". bounce */ + startEffect: string; + /** Radius of the positions from which the slices will fly in. + default 5 + */ + startRadius: any; + /** Name of the field in chart's dataProvider which holds slice's title. */ + titleField: string; + /** Name of the field in chart's dataProvider which holds url which would be accessed if the user clicks on a slice. */ + urlField: string; + /** If url is specified for a slice, it will be opened when user clicks on it. urlTarget specifies target of this url. Use _blank if you want url to be opened in a new window. _self */ + urlTarget: string; + /** Name of the field in chart's dataProvider which holds slice's value. */ + valueField: string; + /** Name of the field in chart's dataProvider which holds boolean variable defining whether this data item should have an entry in the legend. */ + visibleInLegendField: string; + + /** You can trigger the animation of the pie chart. */ + animateAgain(); + /** You can trigger the click on a slice from outside. index - the number of a slice or Slice object. */ + clickSlice(index); + /** Hides slice. index - the number of a slice or Slice object. */ + hideSlice(index); + /** You can simulate roll-out of a slice from outside. index - the number of a slice or Slice object. */ + rollOutSlice(index); + /** You can simulate roll-over a slice from outside. index - the number of a slice or Slice object. */ + rollOverSlice(index); + /** Shows slice. index - the number of a slice or Slice object. */ + showSlice(index); + + /** Adds event listener of the type "clickSlice" or "pullInSlice" or "pullOutSlice" to the object. + @param type Always "clickSlice" or "pullInSlice" or "pullOutSlice". + @param handler + If the type is "clickSlice", dispatched when user clicks on a slice. + If the type is "pullInSlice", dispatched when user clicks on a slice and the slice is pulled-in. + If the type is "pullOutSlice", dispatched when user clicks on a slice and the slice is pulled-out. + If the type is "rollOutSlice", dispatched when user rolls-out of the slice. + If the type is "rollOverSlice", dispatched when user rolls-over the slice. + */ + addListener(type: string, handler: (e: {/** Always "rollOverSlice". */ + type: string; dataItem: Slice; + }) => void ); + } + + /** AmRadarChart is the class you have to use for radar and polar chart types. + @example + var chart; + var chartData = [ + {country:"Czech Republic",litres:156.90}, + {country:"Ireland",litres:131.10}, + {country:"Germany",litres:115.80}, + {country:"Australia",litres:109.90}, + {country:"Austria",litres:108.30}, + {country:"UK",litres:99.00} + ]; + + window.onload = function() { + chart = new AmCharts.AmRadarChart(); + chart.dataProvider = chartData; + chart.categoryField = "country"; + chart.startDuration = 2; + + var valueAxis = new AmCharts.ValueAxis(); + valueAxis.axisAlpha = 0.15; + valueAxis.minimum = 0; + valueAxis.dashLength = 3; + valueAxis.axisTitleOffset = 20; + valueAxis.gridCount = 5; + chart.addValueAxis(valueAxis); + + var graph = new AmCharts.AmGraph(); + graph.valueField = "litres"; + graph.bullet = "round"; + graph.balloonText = "[[value]] litres of beer per year" + chart.addGraph(graph); + + chart.write("chartdiv"); + } + */ + declare class AmRadarChart extends AmCoordinateChart { + /** Bottom margin of the chart. */ + marginBottom: number; + /** Left margin of the chart. */ + marginLeft: number; + /** Right margin of the chart. */ + marginRight: number; + /** Top margin of the chart. */ + marginTop: number; + /** Radius of a radar. 0.35 */ + radius: any; + } + + /** AmXYChart is the class you have to use for XY/Bubble/Scatter chart types. The chart supports simple and logarithmic scales, it can have multiple value axes. + @example + var chartData = [ + {x:10, y:14, value:59}, + {x:5, y:3, value:50}, + {x:-10, y:-3, value:19}, + {x:-6, y:5, value:65}, + {x:15, y:-4, value:92}, + {x:13, y:1, value:8}, + {x:1, y:6, value:35} + ]; + + var chart = new AmCharts.AmXYChart(); + chart.pathToImages = "../../amcharts/javascript/images/"; + chart.dataProvider = chartData; + chart.marginLeft = 35; + chart.startDuration = 1.5; + + var xAxis = new AmCharts.ValueAxis(); + xAxis.position = "left"; + xAxis.autoGridCount = true; + chart.addValueAxis(xAxis); + + var yAxis = new AmCharts.ValueAxis(); + yAxis.position = "bottom"; + yAxis.autoGridCount = true; + chart.addValueAxis(yAxis); + + var graph = new AmCharts.AmGraph(); + graph.valueField = "value"; + graph.xField = "x"; + graph.yField = "y"; + graph.lineAlpha = 0; + graph.bullet = "round"; + chart.addGraph(graph); + + var chartCursor = new AmCharts.ChartCursor(); + chart.addChartCursor(chartCursor); + + var chartScrollbar = new AmCharts.ChartScrollbar(); + chartScrollbar.hideResizeGrips = false; + chart.addChartScrollbar(chartScrollbar); + + chart.write("chartdiv); + */ + declare class AmXYChart extends AmRectangularChart { + /** Specifies if Scrollbar of X axis (horizontal) should be hidden. */ + hideXScrollbar: bool; + /** Specifies if Scrollbar of Y axis (vertical) should be hidden. */ + hideYScrollbar: bool; + /** Maximum zoom factor of the chart. + @default 20 + */ + maxZoomFactor: number; + /** Zooms out, charts shows all available data.*/ + zoomOut(); + } + /** Guides are straight vertical or horizontal lines or areas supported by AmSerialChart, AmXYChart and AmRadarChart. You can have guides both on value and category axes. To add/remove a guide to an axis, use axis.addGuide(guide)/axis.removeGuide(guide) methods. + +If you do not set properties such as dashLength, lineAlpha, lineColor, etc - values of the axis are used.*/ + declare class Guide { + /** Radar chart only. Specifies angle at which guide should start. Affects only fills, not lines. */ + angle: number; + /** Baloon fill color. */ + balloonColor: string; + /** The text which will be displayed if the user rolls-over the guide. */ + balloonText: string; + /** Category of the guide (in case the guide is for category axis). */ + category: string; + /** Dash length. */ + dashLength: number; + /** Date of the guide (in case the guide is for category axis and parseDates is set to true). */ + date: Date; + /** Fill opacity. Value range is 0 - 1. */ + fillAlpha: number; + /** Fill color. */ + fillColor: string; + /** Specifies whether label should be placed inside or outside plot area. */ + inside: bool; + /** The label which will be displayed near the guide. */ + label: string; + /** Rotation angle of a guide label. */ + labelRotation: number; + /** Line opacity. */ + lineAlpha: number; + /** Line color. */ + lineColor: string; + /** Line thickness. */ + lineThickness: number; + /** Tick length. */ + tickLength: number; + /** Radar chart only. Specifies angle at which guide should end. Affects only fills, not lines. */ + toAngle: number; + /** To category of the guide (in case the guide is for category axis). */ + toCategory: string; + /** To date of the guide (in case the guide is for category axis and parseDates is set to true) If you have both date and toDate, the space between these two dates can be filled with color. */ + toDate: Date; + /** To value of the guide (in case the guide is for value axis). */ + toValue: number; + /** Value of the guide (in case the guide is for value axis). */ + value: number; + } + /** ImagesSettings is a class which holds common settings of all MapImage objects. */ + declare class ImagesSettings { + /** Opacity of the image. + @default 1 + */ + alpha: number; + /** Text which is displayed in a roll-over balloon. You can use the following tags: [[title]], [[description]], [[value]] and [[percent]]. [[title]] */ + balloonText: string; + /** Specifies if the image's center should be placed in the provided coordinates. If false, top-left corner will be at provided coordinates. + @default true + */ + centered: bool; + /** Color of image. This will affect only predefined images (with "type" property set) and images with svgPath set. This property won't affect bitmap images and loaded SVG images. #000000 */ + color: string; + /** Height of a description window. */ + descriptionWindowHeight: number; + /** Width of a description window. + @default 250 + */ + descriptionWindowWidth: number; + /** X position of a description window. */ + descriptionWindowX: number; + /** Y position of a description window. */ + descriptionWindowY: number; + /** Label color. #000000 */ + labelColor: string; + /** Font size of a label. + @default 11 + */ + labelFontSize: number; + /** Position of the label. Allowed values are: left, right, top, bottom and middle. right */ + labelPosition: string; + /** Label roll-over color. #00CC00 */ + labelRollOverColor: string; + /** Opacity of image outline. This will affect only predefined images (with "type" property set) and images with svgPath set. This property won't affect bitmap images and loaded SVG images. */ + outlineAlpha: number; + /** Color of image outline. This will affect only predefined images (with "type" property set) and images with svgPath set. This property won't affect bitmap images and loaded SVG images. */ + outlineColor: string; + /** Thickness of image outline. This will affect only predefined images (with "type" property set) and images with svgPath set. This property won't affect bitmap images and loaded SVG images. + @default 1 + */ + outlineThickness: number; + /** Color of image when hovered. This will affect only predefined images (with "type" property set) and images with svgPath set. This property won't affect bitmap images and loaded SVG images. */ + rollOverColor: string; + /** Scale of the image when hovered. Use value like 1.5 - 2 to enlarge image when user rolls-over it. + @default 1 + */ + rollOverScale: number; + /** Scale of the image if it is selected. Use value like 1.5 - 2 to enlarge selected image. + @default 1 + */ + selectedScale: number; + } + + /** AreasSettings is a class which holds common settings of all MapArea objects. */ + declare class AreasSettings { + /** Opacity of areas. + @default 1 + */ + alpha: number; + /** Specifies if the areas should be zoomed-in when user clicks on them, event if zoom properties are not set. */ + autoZoom: bool; + /** Text which is displayed in a roll-over balloon. You can use the following tags: [[title]], [[description]], [[value]] and [[percent]] [[title]] */ + balloonText: string; + /** Color of the areas. #FFCC00 */ + color: string; + /** Color of area with highest value. Colors for areas with values less then highest will be colored with intermediate colors between color and colorSolid. Use colorSteps property of AmMap to change the number of intermediate colors. #990000 */ + colorSolid: string; + /** Height of a description window. */ + descriptionWindowHeight: number; + /** Width of a description window. + @default 250 + */ + descriptionWindowWidth: number; + /** X position of a description window. */ + descriptionWindowX: number; + /** Y position of a description window. */ + descriptionWindowY: number; + /** Opacity of area's outline. + @default 1 + */ + outlineAlpha: number; + /** Color of area's outline. #FFFFFF */ + outlineColor: string; + /** Thickness of area's outline. 0.5 */ + outlineThickness: number; + /** Color of area when user rolls-over it. undefined */ + rollOverColor: string; + /** Color of area's outline when user rolls-over it. #CC0000 */ + rollOverOutlineColor: string; + /** Color of area which is currently selected. #CC0000 */ + selectedColor: string; + /** Opacity of all areas which are in the map svg file, but not listed as areas in DataSet. + @default 1 + */ + unlistedAreasAlpha: number; + /** Color of all areas which are in the map svg file, but not listed as areas in DataSet. #DDDDDD */ + unlistedAreasColor: string; + /** Opacity of all areas' outline which are in the map svg file, but not listed as areas in DataSet. + @default 1 + */ + unlistedAreasOutlineAlpha: number; + /** Color of all areas' outline which are in the map svg file, but not listed as areas in DataSet. #FFFFFF */ + unlistedAreasOutlineColor: string; + } + + /** Slice is an item of AmPieChart's chartData Array and holds all the information about the slice. When working with a pie chart, you do not create slices or change it's properties directly, instead you set array of data using dataProvider property. Consider properties of a Slice read-only - change values in chart's data provider if you need to. */ + declare class Slice { + /** Opacity of a slice. */ + alpha: number; + /** Color of a slice. */ + color: string; + /** Original object from data provider. */ + dataContext: Object; + /** Slice description. */ + description: string; + /** Specifies whether the slice is hidden */ + hidden: bool; + /** Percent value of a slice. */ + percents: number; + /** Specifies whether the slice is pulled or not. */ + pulled: bool; + /** Slice title */ + title: string; + /** Url of a slice */ + url: string; + /** Value of a slice */ + value: number; + /** specifies whether this slice has a legend entry */ + visibleInLegend: bool; + } + + + /** AmStockChart is a main class Stock chart. */ + declare class AmStockChart { + /** Specifies if animation was already played. Animation is only played once, when chart is rendered for the first time. If you want the animation to be repeated, set this property to false. */ + animationPlayed: bool; + /** Balloon object. */ + balloon: AmBalloon; + /** Settings for category axes. */ + categoryAxesSettings: CategoryAxesSettings; + /** Indicates if the chart is created. */ + chartCreated: bool; + /** Chart cursor settings. */ + chartCursorSettings: ChartCursorSettings; + /** Chart scrollbar settings. */ + chartScrollbarSettings: ChartScrollbarSettings; + /** Array of colors used by data sets if no color was set explicitly on data set itself. #FF6600, "#FCD202", "#B0DE09", "#0D8ECF", "#2A0CD0", "#CD0D74", "#CC0000", "#00CC00", "#0000CC", "#DDDDDD", "#999999", "#333333", "#990000" */ + colors: any[]; + /** Array of data sets selected for comparing. */ + comparedDataSets: any[]; + /** Array of DataSets. */ + dataSets: any[]; + /** DataSetSelector object. You can add it if you have more than one data set and want users to be able to select/compare them. */ + dataSetSelector: DataSetSelector; + /** Current end date of the selected period, get only. To set start/end dates, use stockChart.zoom(startDate, endDate) method. */ + endDate: Date; + /** Defines on which day week starts. 0 - Sunday, 1 - Monday.. + @default 1 */ + firstDayOfWeek: number; + /** If set to true the scope of the data view will be set to the end after data update. */ + glueToTheEnd: bool; + /** Legend settings. */ + legendSettings: LegendSettings; + /** Data set selected as main. */ + mainDataSet: DataSet; + /** Array of StockPanels (charts). */ + panels: any[]; + /** Settings for stock panels. */ + panelsSettings: PanelsSettings; + /** Period selector object. You can add it if you want user's to be able to enter date ranges or zoom chart with predefined period buttons. */ + periodSelector: PeriodSelector; + /** Scrollbar's chart object, get only. */ + scrollbarChart: AmSerialChart; + /** Current start date of the selected period, get only. To set start/end dates, use stockChart.zoom(startDate, endDate) method. */ + startDate: Date; + /** Settings for stock events. */ + stockEventsSettings: any; + /** Settings for value axes. */ + valueAxesSettings: ValueAxesSettings; + /** read-only. Indicates current version of a script. */ + version: string; + /** Specifies whether the chart should zoom-out when main data set is changed. */ + zoomOutOnDataSetChange: bool; + + /** Adds panel to the stock chart. Requires stockChart.validateNow() method to be called after this action. */ + addPanel(panel: StockPanel); + /** Adds panel to the stock chart at a specified index. Requires stockChart.validateNow() method to be called after this action. */ + addPanelAt(panel: StockPanel, index: number); + /** Destroys chart, all timeouts and listeners. */ + clear(); + /** Hides event bullets. */ + hideStockEvents(); + /** Removes event listener from the object. */ + removeListener(obj, type, handler); + /** Removes panel from the stock chart. Requires stockChart.validateNow() method to be called after this action. */ + removePanel(panel: StockPanel); + /** Shows event bullets. */ + showStockEvents(); + /** Method which should be called after data was changed. */ + validateData(); + /** Method which forces the stock chart to rebuild. Should be called after properties are changed. */ + validateNow(); + /** Zooms chart to specified dates. startDate, endDate - Date objects. */ + zoom(startDate, endDate); + /** Zooms out the chart. */ + zoomOut(); + + /** Adds event listener of the type "dataUpdated" or "init" or "rendered" to the object. + @param type Always "dataUpdated" or "init" or "rendered". + @param handler + If the type is "dataUpdated", dispatched when the chart was updated with new data. + If the type is "init", dispatched when the chart is initialized for the first time. In case you want it to fire again after validateNow() method is called, set chart.chartCreated = false. + If the type is "rendered", dispatched each when chart is rendered. + */ + addListener(type: string, handler: (e: { + /** Either "dataUpdated" or "init". */ + type: string; + chart: AmStockChart; + }) => void ); + + /** Adds event listener of the type "rollOutStockEvent" or "rollOverStockEvent" or "clickStockEvent" to the object. + @param type // Either "rollOutStockEvent" or "rollOverStockEvent" or "clickStockEvent". + @param handler + If the type is "rollOutStockEvent", dispatched when the user rolls-out of the Stock event (bullet). + If the type is "rollOverStockEvent", dispatched when the user rolls-over of the Stock event (bullet). + If the type is "clickStockEvent", dispatched when the user clicks on the Stock event (bullet). + */ + + addListener(type: string, handler: (e: { + /** Always "rollOverStockEvent". */ + type: string; + eventObject: any; + graph: AmGraph; + date: Date; + chart: AmStockChart; + }) => void ); + + /** Adds event listener of the type "zoomed" to the object. + @param type Always "zoomed". + @param handler Dispatched when the chart is zoomed (even for the first time, when chart is initialized).*/ + addListener(type: string, handler: (e: { + /** Always "zoomed". */ + type: string; + startDate: Date; + endDate: Date; + period: string; + chart: AmStockChart; + }) => void ); + + /** Adds event listener of the type "panelRemoved" to the object. + @param type Always "panelRemoved". + @param handler Dispatched when the StockPanel is removed.*/ + addListener(type: string, handler: (e: { + /** Always "panelRemoved". */ + + type: string; + panel: StockPanel; + chart: AmStockChart; + }) => void ); + + /** Removes event listener from chart object. */ + removeListener(chart: AmChart, type: string, handler: any); + } + + /** ValueAxesSettings settings set 's settings for all ValueAxes. If you change a property after the chart is initialized, you should call stockChart.validateNow() method in order for it to work. If there is no default value specified, default value of ValueAxis class will be used. */ + declare class ValueAxesSettings { + /** Specifies whether number for gridCount is specified automatically, according to the axis size. + @default true + */ + autoGridCount: bool; + /** Axis opacity. */ + axisAlpha: number; + /** Axis color. */ + axisColor: string; + /** Thickness of the axis. */ + axisThickness: number; + /** Label color. */ + color: string; + /** Length of a dash. By default, the grid line is not dashed. */ + dashLength: number; + /** Fill opacity. Every second space between grid lines can be filled with color. */ + fillAlpha: number; + /** Fill color. Every second space between grid lines can be filled with color. Set fillAlpha to a value greater than 0 to see the fills. */ + fillColor: string; + /** Opacity of grid lines. */ + gridAlpha: number; + /** Color of grid lines. */ + gridColor: string; + /** Approximate number of grid lines. autoGridCount should be set to false, otherwise this property will be ignored. */ + gridCount: number; + /** Thickness of grid lines. */ + gridThickness: number; + /** Specifies whether guide values should be included when calculating min and max of the axis. */ + includeGuidesInMinMax: bool; + /** If true, the axis will include hidden graphs when calculating min and max values. */ + includeHidden: bool; + /** Specifies whether values should be placed inside or outside plot area. In case you set this to false, you'll have to adjust marginLeft or marginRight in [[PanelsSettings]] in order labels to be visible. + @default true + */ + inside: bool; + /** Specifies whether values on axis can only be integers or both integers and doubles. */ + integersOnly: bool; + /** Frequency at which labels should be placed. */ + labelFrequency: number; + /** Specifies whether value labels are displayed. */ + labelsEnabled: bool; + /** Set to true if value axis is logarithmic, false otherwise. */ + logarithmic: bool; + /** The distance of the axis to the plot area, in pixels. Useful if you have more then one axis on the same side. */ + offset: number; + /** Position of the value axis. Possible values are "left" and "right". */ + position: string; + /** Set to true if value axis is reversed (smaller values on top), false otherwise. */ + reversed: bool; + /** Specifies if first label of value axis should be displayed. */ + showFirstLabel: bool; + /** Specifies if last label of value axis should be displayed. */ + showLastLabel: bool; + /** Stacking mode of the axis. Possible values are: "none", "regular", "100%", "3d". */ + stackType: string; + /** Tick length. */ + tickLength: number; + /** Unit which will be added to the value label. */ + unit: string; + /** Position of the unit. Possible values are "left" or "right". */ + unitPosition: string; + + } + + + /** AmLegend is the class that displays legend of the chart. Legend to the chart should be added using chart.addLegend(legend) method. + @example + var chart = new AmCharts.AmSerialChart(); + var legend = new AmCharts.AmLegend(); + chart.addLegend(legend); + */ + declare class AmLegend { + + /** Alignment of legend entries. Possible values are: "left", "center", "right". left */ + align: string; + /** Used if chart is Serial or XY. In case true, margins of the legend are adjusted and made equal to chart's margins. + @default true + */ + autoMargins: bool; + /** Opacity of legend's background. Value range is 0 - 1 */ + backgroundAlpha: number; + /** Background color. You should set backgroundAlpha to >0 vallue in order background to be visible. #FFFFFF */ + backgroundColor: string; + /** Opacity of chart's border. Value range is 0 - 1. */ + borderAlpha: number; + /** Color of legend's border. You should set borderAlpha >0 in order border to be visible. #000000 */ + borderColor: string; + /** In case legend position is set to "absolute", you can set distance from bottom of the chart, in pixels. */ + bottom: number; + /** Text color. Will use chart's color if not set. */ + color: string; + /** This can be used by AmMap only. You can pass array of objects with title, color, markerType values, for example: [{title: "One", color: "#3366CC"},{title: "Two", color: "#FFCC33"}] */ + data: any[]; + /** Specifies if each of legend entry should be equal to the most wide entry. Won't look good if legend has more than one line. + @default true + */ + equalWidths: bool; + /** Font size. Will use chart's font size if not set. */ + fontSize: number; + /** Horizontal space between legend item and left/right border. */ + horizontalGap: number; + /** The text which will be displayed in the legend. Tag [[title]] will be replaced with the title of the graph. [[title]] */ + labelText: string; + /** In case legend position is set to "absolute", you can set distance from left side of the chart, in pixels. */ + left: number; + /** Bottom margin. */ + marginBottom: number; + /** Left margin. This property will be ignored if chart is Serial or XY and autoMargins property of the legend is true (default). + @default 20 + */ + marginLeft: number; + /** Right margin. This property will be ignored if chart is Serial or XY and autoMargins property of the legend is true (default). + @default 20 + */ + marginRight: number; + /** Top margin. */ + marginTop: number; + /** Marker border opacity 1. */ + markerBorderAlpha: number; + /** Marker border color. If not set, will use the same color as marker. */ + markerBorderColor: string; + /** Thickness of the legend border. The default value (0) means the line will be a "hairline" (1 px). In case marker type is line, this style will be used for line thickness. + @default 1 + */ + markerBorderThickness: number; + /** The color of the disabled marker (when the graph is hidden). #AAB3B3 */ + markerDisabledColor: string; + /** Space between legend marker and legend text, in pixels. + @default 5 + */ + markerLabelGap: number; + /** Size of the legend marker (key). + @default 16 + */ + markerSize: number; + /** Shape of the legend marker (key). Possible values are: "square", "circle", "line", "dashedLine", "triangleUp", "triangleDown", "bubble", "none". square */ + markerType: string; + /** Maximum number of columns in the legend. If Legend's position is set to "right" or "left", maxColumns is automatically set to 1. */ + maxColumns: number; + /** Position of a legend. Possible values are: "bottom", "top", "left", "right" and "absolute". In case "absolute", you should set left and top properties too. (this setting is ignored in Stock charts). In case legend is used with AmMap, position is set to "absolute" automatically. bottom */ + position: string; + /** Specifies whether legend entries should be placed in reversed order. */ + reversedOrder: bool; + /** In case legend position is set to "absolute", you can set distance from right side of the chart, in pixels. */ + right: number; + /** Legend item text color on roll-over. #CC0000 */ + rollOverColor: string; + /** When you roll-over the legend entry, all other graphs can reduce their opacity, so that the graph you rolled-over would be distinguished. This style specifies the opacity of the graphs. + @default 1 + */ + rollOverGraphAlpha: number; + /** You can use this property to turn all the legend entries off. + @default true + */ + showEntries: bool; + /** Horizontal space between legend items, in pixels. + @default 10 + */ + spacing: number; + /** Whether showing/hiding of graphs by clicking on the legend marker is enabled or not. In case legend is used with AmMap, this is set to false automatically. + @default true + */ + switchable: bool; + /** Legend switch color. #FFFFFF */ + switchColor: string; + /** Legend switch type (in case the legend is switchable). Possible values are "x" and "v". x */ + switchType: string; + /** If true, clicking on the text will show/hide balloon of the graph. Otherwise it will show/hide graph/slice, if switchable is set to true. */ + textClickEnabled: bool; + /** In case legend position is set to "absolute", you can set distance from top of the chart, in pixels. */ + top: number; + /** Specifies if legend labels should be use same color as corresponding markers. */ + useMarkerColorForLabels: bool; + /** Alignment of the value text. Possible values are "left" and "right". right */ + valueAlign: string; + /** The text which will be displayed in the value portion of the legend. You can use tags like [[value]], [[open]], [[high]], [[low]], [[close]], [[percents]], [[description]]. [[value]] */ + valueText: string; + /** Width of the value text. + @default 80 + */ + valueWidth: number; + /** Vertical space between legend items also between legend border and first and last legend row. 10 */ + verticalGap: number; + /** Adds event listener of the type "clickLabel" or "clickMarker" or "hideItem" to the object. + @param type Either "clickLabel" or "clickMarker" or "hideItem". + @param handler + If the type is "clickLabel", dispatched when legend label is clicked. + If the type is "clickMarker", dispatched when legend marker is clicked. + If the type is "hideItem", dispatched when user clicks on a legend item marker and hides corresponding object. + If the type is "rollOutItem", dispatched when user rolls-out of the legend item label (or whole item, if switchable is set to false). + If the type if "rollOverItem", dispatched when user rolls-over the legend item label (or whole item, if switchable is set to false). + If the type is "rollOutMarker", dispatched when user clicks out of a legend item marker and shows corresponding object. + If the type if "rollOverMarker", dispatched when user clicks on a legend item marker and shows corresponding object. + */ + + /** Adds event listener of the type "showItem" to the object. + @param type Always "showItem". + @param handler + */ + addListener(type: string, handler: (e: {/** Always "showItem". */ + type: string; dataItem: Object; chart: AmChart; + }) => void ); + + /** Removes event listener from chart object. */ + removeListener(chart: AmChart, type: string, handler: any); + } + + /** StockLegend is a legend of StockPanel. */ + + declare class StockLegend extends AmLegend { + /** The text which will be displayed in the value portion of the legend when graph is comparable and at least one dataSet is selected for comparing. You can use tags like [[value]], [[open]], [[high]], [[low]], [[close]], [[percents.value/open/close/low/high]], [[description]]. [[percents.value]]% */ + + valueTextComparing: string; + /** The text which will be displayed in the value portion of the legend. You can use tags like [[value]], [[open]], [[high]], [[low]], [[close]], [[percents]], [[description]]. [[value]] */ + + valueTextRegular: string; + } + + /** StockPanel class creates stock panels (charts). AmStockChart can have multiple Stock panels. */ + + declare class StockPanel extends AmSerialChart { + /** Specifies whether x button will be displayed near the panel. This button allows turning panel off. */ + allowTurningOff: bool; + /** If true, drawing icons will be displayed in top-right corner. */ + drawingIconsEnabled: bool; + /** Specifies on which value axis user can draw trend lines. Set drawingIconsEnabled to true if you want drawing icons to be visible. First value axis will be used if not set here. */ + drawOnAxis: ValueAxis; + /** Specifies if all trend lines should be erased when erase button is clicked. If false, trend lines can be erased one by one. */ + eraseAll: bool; + /** Size of trend line drawing icons. If you change this size, you should update icon images if you want them to look properly. + @default 18 + */ + iconSize: number; + /** Relative height of panel. Possible values 0 - 100. */ + percentHeight: number; + /** Specifies when values should be recalculated to percents. Possible values are: "never", "always", "whenComparing". whenComparing */ + recalculateToPercents: string; + /** Specifies whether this panel will show category axis. + @default true + */ + showCategoryAxis: bool; + /** */ + stockGraphs: StockGraph[]; + /** Stock chart legend. */ + stockLegend: StockLegend; + /** Title of a panel. Note, StockLegend should be added in order title to be displayed. */ + title: string; + /** Trend line opacity. + @default 1 + */ + trendLineAlpha: number; + /** Trend line color. #00CC00 */ + trendLineColor: string; + /** Trend line dash length. */ + trendLineDashLength: number; + /** Trend line thickness. + @default 2 + */ + trendLineThickness: number; + /** Adds a graph to the panel. */ + addStockGraph(graph: StockGraph); + /** Removes graph from the panel. */ + removeStockGraph(graph: StockGraph); + } + + /** AmChart is a base class of all charts. It can not be instantiated explicitly. AmCoordinateChart, AmPieChart and AmMap extend AmChart class. */ + declare class AmChart { + /** Background color. You should set backgroundAlpha to >0 value in order background to be visible. We recommend setting background color directly on a chart's DIV instead of using this property. #FFFFFF */ + backgroundColor: string; + /** The chart creates AmBalloon class itself. If you want to customize balloon, get balloon instance using this property, and then change balloon's properties. AmBalloon */ + balloon: AmBalloon; + /** Opacity of chart's border. Value range is 0 - 1. */ + borderAlpha: number; + /** Color of chart's border. You should set borderAlpha >0 in order border to be visible. We recommend setting border color directly on a chart's DIV instead of using this property. #000000 */ + borderColor: string; + /** Text color. #000000 */ + color: string; + /** Array of data objects, for example: [{country:"US", value:524},{country:"UK", value:624},{country:"Lithuania", value:824}]. You can have any number of fields and use any field names. In case of AmMap, data provider should be MapData object. */ + dataProvider: any[]; + /** Font family. Verdana */ + fontFamily: string; + /** Font size. + @default 11 + */ + fontSize: number; + /** Height of a chart. "100%" means the chart's height will be equal to it's container's (DIV) height and will resize if height of the container changes. Set a number instead of percents if your chart's size needs to be fixed. + @default 1 + */ + height: any; + /** Reference to the div of the legend. */ + legendDiv: HTMLElement; + /** Object with precision, decimalSeparator and thousandsSeparator set which will be used for number formatting. Precision set to -1 means that values won't be rounded. {precision:-1, decimalSeparator:'.', thousandsSeparator:','} */ + numberFormatter: Object; + /** This setting affects touch-screen devices only. If a chart is on a page, and panEventsEnabled are set to true, the page won't move if the user touches the chart first. If a chart is big enough and occupies all the screen of your touch device, the user won’t be able to move the page at all. That's why the default value is "false". If you think that selecting/panning the chart or moving/pinching the map is a primary purpose of your users, you should set panEventsEnabled to true. */ + panEventsEnabled: bool; + /** Object with precision, decimalSeparator and thousandsSeparator set which will be used for formatting percent values. {precision:2, decimalSeparator:'.', thousandsSeparator:','} */ + percentFormatter: Object; + /** Prefixes which are used to make big numbers shorter: 2M instead of 2000000, etc. Prefixes are used on value axes and in the legend. To enable prefixes, set usePrefixes property to true. [{number:1e+3,prefix:"k"},{number:1e+6,prefix:"M"},{number:1e+9,prefix:"G"},{number:1e+12,prefix:"T"},{number:1e+15,prefix:"P"},{number:1e+18,prefix:"E"},{number:1e+21,prefix:"Z"},{number:1e+24,prefix:"Y"}] */ + prefixesOfBigNumbers: any[]; + /** Prefixes which are used to make small numbers shorter: 2μ instead of 0.000002, etc. Prefixes are used on value axes and in the legend. To enable prefixes, set usePrefixes property to true. [{number:1e-24, prefix:"y"},{number:1e-21, prefix:"z"},{number:1e-18, prefix:"a"},{number:1e-15, prefix:"f"},{number:1e-12, prefix:"p"},{number:1e-9, prefix:"n"},{number:1e-6, prefix:"μ"},{number:1e-3, prefix:"m"}] */ + prefixesOfSmallNumbers: any[]; + /** If true, prefixes will be used for big and small numbers. You can set arrays of prefixes via prefixesOfSmallNumbers and prefixesOfBigNumbers properties. */ + usePrefixes: bool; + /** Read-only. Indicates current version of a script. */ + version: string; + /** Adds a label on a chart. + You can use it for labeling axes, adding chart title, etc. x and y coordinates can be set in number, percent, or a number with ! in front of it - coordinate will be calculated from right or bottom instead of left or top. + x - horizontal coordinate + y - vertical coordinate + text - label's text + align - alignment (left/right/center) + size - text size + color - text color + rotation - angle of rotation + alpha - label alpha + bold - specifies if text is bold (true/false), + url - url + */ + addLabel(x: number, y: number, text: string, align: string, size, color: string, rotation, alpha: number, bold: bool, url: string); + /** Adds a legend to the chart. + By default, you don't need to create div for your legend, however if you want it to be positioned in some different way, you can create div anywhere you want and pass id or reference to your div as a second parameter. + (NOTE: This method will not work on StockPanel.) + @param legend + @param legendDivId - Id of the legend div (optional). + */ + addLegend(legend: AmLegend, legendDivId: string); + /** Adds a legend to the chart. + By default, you don't need to create div for your legend, however if you want it to be positioned in some different way, you can create div anywhere you want and pass id or reference to your div as a second parameter. + (NOTE: This method will not work on StockPanel.) + @param legend + @param legendDiv - Legend div (optional). + */ + addLegend(legend: AmLegend, legendDiv: HTMLElement); + + /** Adds title to the top of the chart. Pie, Radar positions are updated so that they won't overlap. Plot area of Serial/XY chart is also updated unless autoMargins property is set to false. You can add any number of titles - each of them will be placed in a new line. To remove titles, simply clear titles array: chart.titles = []; and call chart.validateNow() method. text - text of a title size - font size color - title color alpha - title opacity bold - boolean value indicating if title should be bold. */ + addTitle(text, size, color, alpha, bold); + /** Clears the chart area, intervals, etc. */ + clear(); + /** Removes all labels added to the chart. */ + clearLabels(); + /** Use this method to force the chart to resize to it's current container size. */ + invalidateSize(); + /** Removes chart's legend. */ + removeLegend(); + /** This method should be called after data in your data provider changed or a new array was set to dataProvider. After calling this method the chart will parse data and redraw. */ + validateData(); + /** This method should be called after you changed one or more properties of any class. The chart will redraw after this method is called. */ + validateNow(); + + /** Adds chart to the specified DIV. + @param container DIV object which will hold the chart. */ + write(container: HTMLElement): void; + /** Adds chart to the specified DIV. + @param container Id of a DIV which will hold the chart. */ + write(container: string): void; + + /** Adds event listener of the type "dataUpdated" or "init" to the object. + @param type "dataUpdated" or "init". + @param handler + If the type is "dataUpdated". + Dispatched when chart is build for the first time or after validateData() method was called. + If the type is "init". + Dispatched when chart is build for the first time. + */ + addListener(type: string, handler: (e: { + /** Either "dataUpdated" or "init". */ + type: string; + chart: AmChart; + }) => void ); + /** Removes event listener from chart object. */ + removeListener(chart: AmChart, type: string, handler: any); + } + + /** AmCoordinateChart is a base class of AmRectangularChart. It can not be instantiated explicitly. */ + + declare class AmCoordinateChart extends AmChart { + /** Specifies the colors of the graphs if the lineColor of a graph is not set. + It there are more graphs then colors in this array, the chart picks random color. + @default ['#FF6600', '#FCD202', '#B0DE09', '#0D8ECF', '#2A0CD0', '#CD0D74', '#CC0000', '#00CC00', '#0000CC', '#DDDDDD', '#999999', '#333333', '#990000'] */ + colors: any[]; + /** The array of graphs belonging to this chart. + To add/remove graph use addGraph/removeGraph methods instead of adding/removing graphs directly to array. + */ + graphs: any[]; + /** The opacity of plot area's border. + Value range is 0 - 1. + */ + plotAreaBorderAlpha: number; + /** The color of the plot area's border. + Note, the it is invisible by default, as plotAreaBorderAlpha default value is 0. + Set it to a value higher than 0 to make it visible. + @default #000000 + */ + plotAreaBorderColor: string; + /** Opacity of plot area. + Plural form is used to keep the same property names as our Flex charts'. + Flex charts can accept array of numbers to generate gradients. + Although you can set array here, only first value of this array will be used. + */ + plotAreaFillAlphas: number; + /** You can set both one color if you need a solid color or array of colors to generate gradients, for example: ["#000000", "#0000CC"] + @default #FFFFFF + */ + plotAreaFillColors: any; + /** Specifies whether the animation should be sequenced or all objects should appear at once. + @default true + */ + sequencedAnimation: bool; + /** The initial opacity of the column/line. + If you set startDuration to a value higher than 0, the columns/lines will fade in from startAlpha. + Value range is 0 - 1. + @default 1 + */ + startAlpha: number; + /** Duration of the animation, in seconds. */ + startDuration: number; + /** Animation effect. + Possible values are ">", "<", elastic" and "bounce". + @default "elastic" + */ + startEffect: string; + /** Target of url. + @default this + */ + urlTarget: any; + /** The array of value axes. + To add/remove value axis use addValueAxis/removeValueAxis methods instead of adding/removing axes directly to array. + Chart creates one value axis automatically, so if you need only one value axis, you don't need to create it. + */ + valueAxes: any[]; + /** Adds a graph to the chart. + */ + addGraph(graph: AmGraph); + /** Adds value axis to the chart. + One value axis is created automatically, so if you don't want to change anything or add more value axes, you don't need to add it. + */ + addValueAxis(axis: ValueAxis); + /** You can trigger the animation of the chart. */ + animateAgain(); + + /** AmGraph Returns graph by id. */ + getGraphById(graphId: string): AmGraph; + + /** Returns value axis by id.*/ + getValueAxisById(axisId: string): ValueAxis; + + /** Hide the graph (if it is visible). Usually this method is called from the Legend, when you click on the legend marker. + */ + hideGraph(graph: AmGraph); + + /** Hide value balloon of a graph. Usually this method is called from the Legend, when you click on the legend text.*/ + hideGraphsBalloon(graph: AmGraph); + + /** Highlight the graph. Usually this method is called from the Legend, when you roll-over the legend entry.*/ + highlightGraph(graph: AmGraph); + + /** Removes graph from the chart.*/ + removeGraph(graph: AmGraph); + + /** Removes value axis from the chart. When you remove value axis, all graphs assigned to this axis are also removed. */ + removeValueAxis(axis: ValueAxis); + + /** Show the graph (if it is hidden). Usually this method is called from the Legend, when you click on the legend marker.*/ + showGraph(graph: AmGraph); + + /** Show value balloon of a graph. Usually this method is called from the Legend, when you click on the legend text.*/ + showGraphsBalloon(graph: AmGraph); + + /** UnhighlightGraph the graph. Usually this method is called from the Legend, when you roll-out the legend entry.*/ + unhighlightGraph(graph: AmGraph); + /** Adds event listener of the type "clickGraphItem" or "doubleClickGraphItem" or "rightClickGraphItem" or "rollOutGraphItem" or "rollOverGraphItem" to the object. + @param type Either "clickGraphItem" or "doubleClickGraphItem" or "rightClickGraphItem" or "rollOutGraphItem" or "rollOverGraphItem". + @param handler Dispatched when user clicks on the data item (column/bullet) + */ + addListener(type: string, handler: (e: { + /** Either "clickGraphItem" or "doubleClickGraphItem" or "rightClickGraphItem" or "rollOutGraphItem" or "rollOverGraphItem". */ + type: string; + graph: AmGraph; + item: GraphDataItem; + index: number; + chart: AmChart; + }) => void ); + } + + /** GraphDataItem holds all the information about the graph's data item. When working with a chart, you do not create GraphDataItem objects or change it's properties directly. GraphDataItem is passed to you by events when user interacts with data item on the chart. The list of properties below will help you to extract data item's value/coordinate/etc. */ + declare class GraphDataItem { + /** Opacity of the data item. */ + alpha: number; + /** Bullet type. */ + bullet: string; + /** Bullet size. */ + bulletSize: number; + /** Category value. */ + category: string; + /** Color of the data item. */ + color: string; + /** Custom bullet (path to file name). */ + customBullet: string; + /** Original object from data provider. */ + dataContext: Object; + /** Description. */ + description: string; + /** Array of colors of the data item, used by column and candlestick chart only. */ + fillColors: any[]; + /** Object which holds percents when recalculateToPercents is set to true. */ + percents: Object; + /** SerialDataItem of this graphDataItem */ + serialDataItem: SerialDataItem; + /** url */ + url: string; + /** Object which holds values of the data item (value, open, close, low, high). */ + values: Object; + /** x coordinate of the data item. */ + x: number; + /** y coordinate of the data item. */ + y: number; + } + + /** SerialDataItem holds all the information about each series. When working with a chart, you do not create SerialDataItem objects or change it's properties directly. Consider properties of a SerialDataItem read-only - change values in chart's data provider if you need to. When serial chart parses dataProvider, it generates "chartData" array. Objects of this array are SerialDataItem objects. */ + declare class SerialDataItem { + + /** You can access each GraphDataItem using this object. The data structure is: graphDataItem = serialDataItem.axes[axisId].graphs[graphId]. */ + axes: Object; + + /** category value. String if parseDates is false, Date if true. */ + category: any; + + /** Timestamp of a series date. Avalable only if parseDates property of CategoryAxis is set to true. */ + time: number; + + /** Coordinate (horizontal or vertical, depends on chart's rotate property) of the series. */ + x: number; + } + + declare class CategoryAxis extends AxisBase { + + /** When parse dates is on for the category axis, the chart will try to highlight the beginning of the periods, like month, in bold. Set this to false to disable the functionality. + @default true + */ + boldPeriodBeginning: bool; + + /** Date formats of different periods. Possible period values: fff - milliseconds, ss - seconds, mm - minutes, hh - hours, DD - days, MM - months, WW - weeks, YYYY - years. Check this page for date formatting strings. [{period:'fff',format:'JJ:NN:SS'},{period:'ss',format:'JJ:NN:SS'},{period:'mm',format:'JJ:NN'},{period:'hh',format:'JJ:NN'},{period:'DD',format:'MMM DD'},{period:'WW',format:'MMM DD'},{period:'MM',format:'MMM'},{period:'YYYY',format:'YYYY'}] */ + dateFormats: any[]; + + /** In case your category axis values are Date objects and parseDates is set to true, the chart will parse dates and will place your data points at irregular intervals. However if you want dates to be parsed (displayed on the axis, baloons, etc), but data points to be placed at equal intervals (omiting dates with no data), set equalSpacing to true. */ + equalSpacing: bool; + + /** Field in data provider which specifies if the category value should always be shown. For example: categoryAxis.forceShowField = "forceShow"; Field in data provider which specifies if the category value should always be shown. For example: categoryAxis.forceShowField = "forceShow"; + And in data: + {category:"one", forceShow:true, value:100} + Note, this works only when parseDates is set to false.*/ + forceShowField: string; + + /** Specifies if a grid line is placed on the center of a cell or on the beginning of a cell. Possible values are: "start" and "middle" This setting doesn't work if parseDates is set to true. middle */ + gridPosition: string; + + /** Specifies the shortest period of your data. This should be set only if parseDates is set to "true". Possible period values: fff - milliseconds, ss - seconds, mm - minutes, hh - hours, DD - days, MM - months, YYYY - years. DD */ + minPeriod: string; + + /** In case your category axis values are Date objects, set this to true. In this case the chart will parse dates and will place your data points at irregular intervals. If you want dates to be parsed, but data points to be placed at equal intervals, set both parseDates and equalSpacing to true. */ + parseDates: bool; + + /** Specifies whether the graph should start on axis or not. In case you display columns, it is recommended to set this to false. If parseDates is set to true, startOnAxis will allways be false, unless equalSpacing is set to true. */ + startOnAxis: bool; + + /** Number returns coordinate of a category. Works only if parseDates is false. If parseDates is true, use dateToCoordinate method. category - String */ + categoryToCoordinate(category); + + /** date - Date object Returns Date of the coordinate, in case parseDates is set to true and equalSpacing is set to false. coordinate - Number */ + coordinateToDate(coordinate); + + /** Number Returns coordinate of the date, in case parseDates is set to true. if parseDates is false, use categoryToCoordinate method. date - Date object */ + dateToCoordinate(date); + + /** Number Returns index of the category which is most close to specified coordinate. x - coordinate */ + xToIndex(x); + } + + /** ChartScrollbar class displays chart scrollbar. Supported by AmSerialChart and AmXYChart. + @example + var chart = new AmCharts.AmSerialChart(); + var chartScrollbar = new AmCharts.ChartScrollbar(); + chart.addChartScrollbar(chartScrollbar); + */ + declare class ChartScrollbar { + /** Specifies whether number of gridCount is specified automatically, acoarding to the axis size. */ + autoGridCount: bool; + /** Background opacity. + @default 1 + */ + backgroundAlpha: number; + /** Background color of the scrollbar. + @default #D4D4D4 + */ + backgroundColor: string; + /** Read-only. Category axis of the scrollbar. */ + categoryAxis: CategoryAxis; + /** Text color. Will use chart's color if not set. */ + color: string; + /** Specifies which graph will be displayed in the scrollbar. Only Serial chart's scrollbar can display a graph. */ + graph: AmGraph; + /** Graph fill opacity. Value range is 0 - 1. 0.1 */ + graphFillAlpha: number; + /** Graph fill color. #000000 */ + graphFillColor: string; + /** Graph line opacity. Value range is 0 - 1. */ + graphLineAlpha: number; + /** Graph line color. #000000 */ + graphLineColor: string; + /** by default the graph type is the same as the original graph's type, however in case of candlestick or ohlc you might want to show line graph in the scrollbar. Possible values are: "line", "column", "step", "smoothedLine", "candlestick", "ohlc". */ + graphType: string; + /** Grid opacity. Value range is 0 - 1. 0.7 */ + gridAlpha: number; + /** Grid color. #FFFFFF */ + gridColor: string; + /** The number of grid lines. */ + gridCount: number; + /** Specifies whether resize grips are hidden when mouse is away from the scrollbar. */ + hideResizeGrips: bool; + /** Specifies whether scrollbar has a resize feature. + @default true + */ + resizeEnabled: bool; + /** Height (width, if chart is rotated) of a scrollbar. 20 */ + scrollbarHeight: number; + /** Duration of scrolling, when the user clicks on scrollbar's background, in seconds. + @default 2 + 3*/ + scrollDuration: number; + /** Selected backround opacity. + @default 1 + */ + selectedBackgroundAlpha: number; + /** Selected background color. #EFEFEF */ + selectedBackgroundColor: string; + /** Selected graph's fill opacity. Value range is 0 - 1. 0.5 */ + selectedGraphFillAlpha: number; + /** Selected graph's fill color. #000000 */ + selectedGraphFillColor: string; + /** Selected graph's line opacity. Value range is 0 - 1. */ + selectedGraphLineAlpha: number; + /** Selected graph's line color. #000000 */ + selectedGraphLineColor: string; + /** Specifies if the chart should be updated while dragging/resizing the scrollbar or only at the moment when user releases mouse button. */ + updateOnReleaseOnly: bool; + } + + /** AmRectangularChart is a base class of AmSerialChart and AmXYChart. It can not be instantiated explicitly.*/ + declare class AmRectangularChart extends AmCoordinateChart { + /** The angle of the 3D part of plot area. This creates a 3D effect (if the "depth3D" is > 0). */ + angle: number; + /** Space left from axis labels/title to the chart's outside border, if autoMargins set to true. + @default 10 + */ + autoMarginOffset: number; + /** Specifies if margins of a chart should be calculated automatically so that labels of axes would fit. The chart will adjust only margins with axes. Other margins will use values set with marginRight, marginTop, marginLeft and marginBottom properties. + @default true + */ + autoMargins: bool; + /** Chart cursor. */ + chartCursor: ChartCursor; + /** Chart scrollbar. */ + chartScrollbar: ChartScrollbar; + /** The depth of the 3D part of plot area. This creates a 3D effect (if the "angle" is > 0). */ + depth3D: number; + /** Number of pixels between the container's bottom border and plot area. This space can be used for bottom axis' values. If autoMargin is true and bottom side has axis, this property is ignored. + @default 20 + */ + marginBottom: number; + /** Number of pixels between the container's left border and plot area. This space can be used for left axis' values. If autoMargin is true and left side has axis, this property is ignored. + @default 20 + */ + marginLeft: number; + /** Number of pixels between the container's right border and plot area. This space can be used for Right axis' values. If autoMargin is true and right side has axis, this property is ignored. + @default 20 + */ + marginRight: number; + /** Flag which should be set to false if you need margins to be recalculated on next chart.validateNow() call. */ + marginsUpdated: bool; + /** Number of pixels between the container's top border and plot area. This space can be used for top axis' values. If autoMargin is true and top side has axis, this property is ignored. + @default 20 + */ + marginTop: number; + /** Array of trend lines added to a chart. You can add trend lines to a chart using this array or access already existing trend lines */ + trendLines: any[]; + /** It's a simple object containing information about zoom-out button. Other available properties of this object are fontSize and color. color specifies text color of a button. {backgroundColor:'#b2e1ff',backgroundAlpha:1} */ + zoomOutButton: Object; + /** Text in the zoom-out button. Show all */ + zoomOutText: string; + /** Adds a TrendLine to a chart. + You should call chart.validateNow() after this method is called in order the trend line to be visible. */ + addTrendLine(trendLine: TrendLine); + /** Removes cursor from the chart */ + removeChartCursor(); + /** Removes scrollbar from the chart */ + removeChartScrollbar(); + /** Removes a trend line from a chart. + You should call chart.validateNow() in order the changes to be visible. */ + removeTrendLine; + } + + /* Trend lines are straight lines indicating trends, might also be used for some different purposes. Can be used by Serial and XY charts. To add/remove trend line, use chart.addTrendLine(trendLine)/chart.removeTrendLine(trendLine) methods or simply pass array of trend lines: chart.trendLines = [trendLine1, trendLine2]. + @example + var trendLine = new AmCharts.TrendLine(); + trendLine.initialDate = new Date(2012, 0, 2, 12); // 12 is hour - to start trend line in the middle of the day + trendLine.finalDate = new Date(2012, 0, 11, 12); + trendLine.initialValue = 10; + trendLine.finalValue = 19; + trendLine.lineColor = "#CC0000"; + chart.addTrendLine(trendLine); + */ + declare class TrendLine { + + } + + /** ChartCursor is a class which displays a cursor which follows the mouse. In case of Serial chart it also shows value and category balloons. + @example + var chart = new AmCharts.AmSerialChart(); + var chartCursor = new AmCharts.ChartCursor(); + chart.addChartCursor(chartCursor); + */ + declare class ChartCursor { + /** Specifies if bullet for each graph will follow the cursor. */ + bulletsEnabled: bool; + /** Size of bullets, following the cursor. + @default 8 + */ + bulletSize: number; + /** Opacity of the category balloon. + @default 1 + */ + categoryBalloonAlpha: number; + /** Color of the category balloon. cursorColor is used if not set. */ + categoryBalloonColor: string; + /** Category balloon date format (used only if category axis parses dates). Check this page for instructions on how to format dates. MMM DD, YYYY */ + categoryBalloonDateFormat: string; + /** Specifies whether category balloon is enabled. + @default true + */ + categoryBalloonEnabled: bool; + /** Text color. #FFFFFF */ + color: string; + /** Opacity of the cursor line. 1 */ + cursorAlpha: number; + /** Color of the cursor line. #CC0000 */ + cursorColor: string; + /** Specifies where the cursor line should be placed - on the beginning of the period (day, hour, etc) or in the middle (only when parseDates property of categoryAxis is set to true). If you want the cursor to follow mouse and not to glue to the nearest data point, set "mouse" here. Possible values are: "start", "middle", "mouse". */ + cursorPosition: string; + /** Specifies whether cursor is enabled. + @default true + */ + enabled: bool; + /** If this is set to true, only one balloon at a time will be displayed. Note, this is quite CPU consuming. */ + oneBalloonOnly: bool; + /** If this is set to true, the user will be able to pan the chart (Serial only) instead of zooming. */ + pan: bool; + /** Opacity of the selection. */ + selectionAlpha: number; + /** Specifies if cursor should only mark selected area but not zoom-in after user releases mouse button. */ + selectWithoutZooming: bool; + /** Specifies whether value balloons are enabled. In case they are not, the balloons might be displayed anyway, when the user rolls-over the column or bullet. + @default true + */ + valueBalloonsEnabled: bool; + /** Specifies if the user can zoom-in the chart. If pan is set to true, zoomable is switched to false automatically. + @default true + */ + zoomable: bool; + /** Indicates if currently user is selecting some chart area to zoom-in. */ + zooming: bool; + + + /** Hides cursor. */ + hideCursor(); + /** You can force cursor to appear at specified cateogry or date. */ + showCursorAt(category); + /** Adds event listener of the type "changed" to the object. + @param type Always "changed". + @param handler Dispatched when cursor position is changed. "index" is a series index over which chart cursors currently is. "zooming" specifies if user is currently zooming (is selecting) the chart. mostCloseGraph property is set only when oneBalloonOnly is set to true.*/ + addListener(type: string, handler: (e: {/** Always "changed". */ + type: string; index: number; zooming: bool; mostCloseGraph: AmGraph; chart: AmChart; + }) => void ); + /** Adds event listener of the type "onHideCursor" to the object. + @param type Always "onHideCursor". + @param handler Dispatched when cursor is hidden.*/ + addListener(type: string, handler: (e: {/** Always "onHideCursor". */ + type: string; chart: AmChart; + }) => void ); + /** Adds event listener of the type "selected" or "zoomed" to the object. + @param type "selected" or "zoomed". + @param handler + If the type is "selected". Dispatched if selectWithoutZooming is set to true and when user selects some period. start and end are indices or timestamp (when categoryAxis.parseDates is true) of selection start/end. + If the type is "zoomed". Dispatched when user zooms to some period. start and end are indices or timestamp (when categoryAxis.parseDates is true) of selection start/end. + */ + addListener(type: string, handler: (e: {/** Always "zoomed". */ + type: string; index: number; zooming: bool; chart: AmChart; + }) => void ); + + /** Removes event listener from chart object. */ + removeListener(chart: AmChart, type: string, handler: any); + } + + /** AmSerialChart is the class you have to use for majority of chart types. The supported chart types are: line, area, column, bar, step line, smoothed line, candlestick and OHLC. The chart can be rotated by 90 degrees so the column chart becomes bar chart. The chart supports simple and logarithmic scales, it can have multiple value axes. The chart can place data points at equal intervals or can parse dates and place data points at irregular intervals. + @example + var chartData = [{title:"sample 1",value:130},{title:"sample 2",value:26}]; + + var chart = new AmCharts.AmSerialChart(); + chart.categoryField = "title"; + chart.dataProvider = chartData; + + var graph = new AmCharts.AmGraph(); + graph.valueField = "value"; + graph.type = "column"; + graph.fillAlphas = 1; + chart.addGraph(graph); + + chart.write("chartdiv"); + */ + declare class AmSerialChart extends AmRectangularChart { + /** Read-only. Chart creates category axis itself. If you want to change some properties, you should get this axis from the chart and set properties to this object. */ + categoryAxis: CategoryAxis; + /** Category field name tells the chart the name of the field in your dataProvider object which will be used for category axis values. */ + categoryField: string; + /** Read-only. Array of SerialDataItem objects generated from dataProvider. */ + chartData: any[]; + /** The gap in pixels between two columns of the same category. + @default 5 + */ + columnSpacing: number; + /** Relative width of columns. Value range is 0 - 1. 0.8 */ + columnWidth: number; + /** Array holding chart's data. */ + dataProvider: any[]; + /** Read-only. If category axis parses dates endDate indicates date to which the chart is currently displayed. */ + endDate: Date; + /** Read-only. Category index to which the chart is currently displayed. */ + endIndex: number; + /** Maximum number of series allowed to select. */ + maxSelectedSeries: number; + /** The longest time span allowed to select (in milliseconds) for example, 259200000 will limit selection to 3 days. */ + maxSelectedTime: number; + /** The shortest time span allowed to select (in milliseconds) for example, 1000 will limit selection to 1 second. */ + minSelectedTime: number; + /** If you set this to true, the chart will be rotated by 90 degrees (the columns will become bars). */ + rotate: bool; + /** Read-only. If category axis parses dates startDate indicates date from which the chart is currently displayed. */ + startDate: Date; + /** Read-only. Category index from which the chart is currently displayed. */ + startIndex: number; + /** Specifies if chart should zoom-out when data is updated. + @default true + */ + zoomOutOnDataUpdate: bool; + + /** Number Returns index of the specified category value. value - series (category value) which index you want to find. */ + getCategoryIndexByValue(value); + /** Zooms out, charts shows all available data. */ + zoomOut(); + /** Zooms the chart by the value of the category axis. start - category value, String \\ end - category value, String */ + zoomToCategoryValues(start, end); + /** Zooms the chart from one date to another. start - start date, Date object \\ end - end date, Date object */ + zoomToDates(start, end); + /** Zooms the chart by the index of the category. start - start index, Number \\ end - end index, Number */ + zoomToIndexes(start, end); + } + + declare class PeriodSelector { + /** Date format of date input fields. Check [[http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/formatters/DateFormatter.html DD-MM-YYYY */ + dateFormat: string; + /** Text displayed next to "from" date input field. From: */ + fromText: string; + /** Specifies if period buttons with date range bigger than available data should be hidden. + @default true + */ + hideOutOfScopePeriods: bool; + /** Specifies whether period selector displays "from" and "to" date input fields. + @default true + */ + inputFieldsEnabled: bool; + /** Width of date input fields, in pixels. Works only if period selector is horizontal. + @default 100 + */ + inputFieldWidth: number; + /** Array of predefined period objects. Period object has 4 properties - period, count, label and selected. Possible period values are: "ss" - seconds, "mm" - minutes, "hh" - hours, "DD" - days, "MM" - months and "YYYY" - years. property "count" specifies how many periods this button will select. "label" will be displayed on a button and "selected" is a boolean which specifies if this button is selected when chart is initialized or not. Example: {period:"DD", count:10, label:"10 days", selected:false}. */ + periods: any[]; + /** Text displayed next to predefined period buttons. Zoom: */ + periodsText: string; + /** Possible values: "right", "left", "top", "bottom". bottom */ + position: string; + /** Specifies whether predefined period buttons should select a period from the beginning or the end of the data. */ + selectFromStart: bool; + /** Text displayed next to "to" date input field. To: */ + toText: string; + /** Width of a period selector, when position is "left" or "right". + @default 180 + */ + width: number; + + /** Adds event listener to the object. + . +@param handler - Dispatched when dates in period selector input fields are changed or user clicks on one of the predefined period buttons. */ + + addListener(type, handler: (e: { + /** Always: "changed" */ + + type: string; + startDate: Date; + endDate: Date; + predefinedPeriod: string; + count: number; + }) => void ); + + /** Removes event listener from chart object. */ + removeListener(chart: AmChart, type: string, handler: any); + } + + /** PanelsSettings settings set's settings for all StockPanels. If you change a property after the chart is initialized, you should call stockChart.validateNow() method in order for it to work. If there is no default value specified, default value of StockPanel class will be used. */ + + declare class PanelsSettings { + /** The angle of the 3D part of plot area. This creates a 3D effect (if the "depth3D" is > 0). */ + angle: number; + /** Opacity of panel background. Possible values are 1 and 0. Values like 0.5 will not make it half-transparent. */ + backgroundAlpha: number; + /** Background color of panels. Set backgroundAlpha to > 0 value in order to make background visible. #FFFFFF */ + backgroundColor: string; + /** The gap in pixels between two columns of the same category. */ + columnSpacing: number; + /** Relative width of columns. Valid values 0 - 1. */ + columnWidth: number; + /** The depth of the 3D part of plot area. This creates a 3D effect (if the "angle" is > 0). */ + depth3D: number; + /** Font family. */ + fontFamily: string; + /** Font size. */ + fontSize: string; + /** Number of pixels between the container's bottom border and plot area. + @default 1 + */ + marginBottom: number; + /** Number of pixels between the container's left border and plot area. If your left valueAxis values ar not placed inside the plot area, you should set marginLeft to 80 or some close value. */ + marginLeft: number; + /** Number of pixels between the container's left border and plot area. If your right valueAxis values ar not placed inside the plot area, you should set marginRight to 80 or some close value. */ + marginRight: number; + /** Number of pixels between the container's top border and plot area. */ + marginTop: number; + /** Gap between panels. + @default 8 + */ + panelSpacing: number; + /** This setting affects touch-screen devices only. If a chart is on a page, and panEventsEnabled are set to true, the page won't move if the user touches the chart first. If a chart is big enough and occupies all the screen of your touch device, the user won’t be able to move the page at all. That's why the default value is "false". If you think that selecting or or panning the chart is a primary purpose of your chart users, you should set panEventsEnabled to true. */ + panEventsEnabled: bool; + /** The opacity of plot area's border. */ + plotAreaBorderAlpha: number; + /** The color of the plot area's border. */ + plotAreaBorderColor: string; + /** Opacity of plot area fill. */ + plotAreaFillAlphas: number; + /** Specifies the colors used to tint the background gradient fill of the plot area. String or Array of Strings */ + plotAreaFillColors: any; + /** Prefixes which are used to make big numbers shorter: 2M instead of 2000000, etc. Prefixes are used on value axes and in the legend. To enable prefixes, set usePrefixes property to true. [{number:1e+3,prefix:"k"},{number:1e+6,prefix:"M"},{number:1e+9,prefix:"G"},{number:1e+12,prefix:"T"},{number:1e+15,prefix:"P"},{number:1e+18,prefix:"E"},{number:1e+21,prefix:"Z"},{number:1e+24,prefix:"Y"}] */ + prefixesOfBigNumbers: any[]; + /** Prefixes which are used to make small numbers shorter: 2μ instead of 0.000002, etc. Prefixes are used on value axes and in the legend. To enable prefixes, set usePrefixes property to true. [{number:1e-24, prefix:"y"},{number:1e-21, prefix:"z"},{number:1e-18, prefix:"a"},{number:1e-15, prefix:"f"},{number:1e-12, prefix:"p"},{number:1e-9, prefix:"n"},{number:1e-6, prefix:"μ"},{number:1e-3, prefix:"m"}] */ + prefixesOfSmallNumbers: any[]; + /** Specifies whether the animation should be sequenced or all objects should appear at once. */ + sequencedAnimation: bool; + /** The initial opacity of the column/line. If you set startDuration to a value higher than 0, the columns/lines will fade in from startAlpha. */ + startAlpha: number; + /** Duration of the animation, in seconds. */ + startDuration: number; + /** Possible values are: "linear", "<", ">" "<>", "elastic", "bounce". */ + startEffect: string; + /** If true, prefixes will be used for big and small numbers. */ + usePrefixes: bool; + } + + /** DataSet is objects which holds all information about data. */ + + declare class DataSet { + /** Category field name in your dataProvider. */ + categoryField: string; + /** Color of the data set. One of colors from AmStockChart.colors array will be used if not set. */ + color: string; + /** Whether this data set is selected for comparing. If you change this property, you should call stockChart.validateData() method in order the changes to be applied. */ + compared: bool; + /** Data provider of the data set. */ + dataProvider: any[]; + /** Array of field mappings. Field mapping is an object with fromField and toField properties. fromField is a name of your value field in dataProvider. toField might be chosen freely, it will be used to set value/open/close/high/low fields for the StockGraph. Example: {fromField:"val1", toField:"value"}. */ + fieldMappings: any[]; + /** Specifies whether this data set should be visible in "compare to" list. + @default true + */ + showInCompare: bool; + /** Specifies whether this data set should be visible in "select" dropdown. + @default true + */ + showInSelect: bool; + /** Array of StockEvent objects. */ + stockEvents: StockEvent[]; + /** DataSet title. */ + title: string; + } + + declare class StockGraph extends AmGraph { + /** Specifies whether this graph will be compared if some data set is selected for comparing. */ + comparable: bool; + /** Specifies a field to be used to generate comparing graph. Note, this field is not the one used in your dataProvider, but toField from FieldMapping object. */ + compareField: string; + /** Balloon color of comparing graph. */ + compareGraphBalloonColor: string; + /** Balloon text of comparing graph. */ + compareGraphBalloonText: string; + /** Bullet of comparing graph. Possible values are: "square", "round", "line", "triangleUp", "triangleDown", "dashedLine", "bubble". */ + compareGraphBullet: string; + /** Bullet size of comparing graph. */ + compareGraphBulletSize: number; + /** Corner radius of comparing graph (if type is "column"). */ + compareGraphCornerRadiusTop: number; + /** Dash length of compare graph. */ + compareGraphDashLength: number; + /** Fill alpha of comparing graph. */ + compareGraphFillAlphas: number; + /** Fill color of comparing graph. */ + compareGraphFillColors: string; + /** Opacity of comparing graph line. */ + compareGraphLineAlpha: number; + /** Thickness of compare graph. */ + compareGraphLineThickness: number; + /** Type of comparing graph. Possible values are: "line", "column", "step", "smoothedLine." line */ + compareGraphType: string; + /** Specifies if compare graph is visible in legend. + @default true + */ + compareGraphVisibleInLegend: bool; + /** When data is grouped to periods, the graph must know which period value should be used. Possible values are: "Open", "Low", "High", "Close", "Average" and "Sum". Close */ + periodValue: string; + /** Specifies whether data set color should be used as this graph's lineColor. + @default true + */ + useDataSetColors: bool; + } + + /** StockEvent is object which holds information about event(bullet).Values from StockEventsSettings will be used if not set.Stock event bullet's size depends on it's graphs fontSize.When user rolls - over, clicks or rolls - out of the event bullet, AmStockChart dispatches events.*/ + declare class StockEvent { + /** Opacity of bullet background. + @default 1 + */ + backgroundAlpha: number; + /** Color of bullet background. #DADADA */ + backgroundColor: string; + /** Opacity of bullet border. + @default 1 + */ + borderAlpha: number; + /** Bullet border color. #888888 */ + borderColor: string; + /** The color of the event text. #000000 */ + color: string; + /** Date of an event. Must be Date object, not a string. */ + date: Date; + /** graph on which event will be displayed. */ + graph: StockGraph; + /** Roll-over background color. #CC0000 */ + rollOverColor: string; + /** Specifies if the event should be displayed on category axis */ + showOnAxis: bool; + /** Letter which will be displayed on the event. Not all types can display letters. "text" type can display longer texts. */ + text: string; + /** Type of bullet. Possible values are: "flag", "sign", "pin", "triangleUp", "triangleDown", "triangleLeft", "triangleRight", "text", "arrowUp", "arrowDown". sign */ + type: string; + /** A URL to go to when user clicks the event. */ + url: string; + /** target of url, "_blank" for example. */ + urlTarget: string; + } + + /** Common settings of legends. If you change a property after the chart is initialized, you should call stockChart.validateNow() method in order for it to work. If there is no default value specified, default value of StockLegend class will be used. */ + declare class LegendSettings { + /** Alignment of legend entries. Possible values are: "left", "right" and "center". */ + align: string; + /** Specifies if each legend entry should take the same space as the longest legend entry. */ + equalWidths: bool; + /** Horizontal space between legend item and left/right border. */ + horizontalGap: number; + /** The text which will be displayed in the legend. Tag [[title]] will be replaced with the title of the graph. */ + labelText: string; + /** Space below the last row of the legend, in pixels. */ + marginBottom: number; + /** Space above the first row of the legend, in pixels. */ + marginTop: number; + /** Opacity of marker border. */ + markerBorderAlpha: number; + /** Marker border color. */ + markerBorderColor: string; + /** Thickness of the legend border. */ + markerBorderThickness: number; + /** The color of the disabled marker (when the graph is hidden). */ + markerDisabledColor: string; + /** Space between legend marker and legend text, in pixels. */ + markerLabelGap: number; + /** Size of the legend marker (key). */ + markerSize: number; + /** Shape of the legend marker (key). Possible values are: "square", "circle", "line", "dashedLine", "triangleUp", "triangleDown", "bubble", "none". */ + markerType: string; + /** Specifies whether legend entries should be placed in reversed order. */ + reversedOrder: bool; + /** Legend item text color on roll-over. */ + rollOverColor: string; + /** When you roll-over the legend entry, all other graphs can reduce their opacity, so that the graph you rolled-over would be distinguished. This property specifies the opacity of the graphs. */ + rollOverGraphAlpha: number; + /** Whether showing/hiding of graphs by clicking on the legend marker is enabled or not. */ + switchable: bool; + /** Legend switch color. */ + switchColor: string; + /** Legend switch type (in case the legend is switchable). Possible values are: "x" and "v". */ + switchType: string; + /** Specifies whether the legend text is clickable or not. Clicking on legend text can show/hide value balloons if they are enabled. */ + textClickEnabled: bool; + /** Specifies if legend labels should be use same color as corresponding markers. */ + useMarkerColorForLabels: bool; + /** The text which will be displayed in the value portion of the legend when graph is comparable and at least one dataSet is selected for comparing. You can use tags like [[value]], [[open]], [[high]], [[low]], [[close]], [[percents]], [[description]]. */ + valueTextComparing: string; + /** The text which will be displayed in the value portion of the legend. You can use tags like [[value]], [[open]], [[high]], [[low]], [[close]], [[percents]], [[description]]. */ + valueTextRegular: string; + /** Width of the value text. Increase this value if your values do not fit in the allocated space. */ + valueWidth: number; + /** Vertical space between legend items, in pixels. */ + verticalGap: number; + + } + + /** DataSetSelector is a tool for selecting data set's as main and for comparing with main data set. */ + declare class DataSetSelector { + /** Text displayed in the "compare to" combobox (when position is "top" or "bottom"). Select... */ + comboBoxSelectText: string; + /** Text displayed near "compare to" list. Compare to: */ + compareText: string; + /** The maximum height of the Compare to field in pixels. + @default 150 + */ + listHeight: number; + /** Possible values: "right", "left", "top", "bottom". "top" and "bottom" positions has a limitation - only one data set can be selected for comparing. left */ + position: string; + /** Text displayed near "Select" dropDown. Select: */ + selectText: string; + /** Width of a Data set selector, when position is "left" or "right". + @default 180 + */ + width: number; + } + + /** AmBalloon is the class which generates balloons (datatips). Balloon follows the mouse when you roll-over the pie slice/line bullet/column/etc, chart indicator of serial charts displays value balloons and category balloon. Balloon instance is created by the chart automatically and can be accessed via "balloon" property of AmChart. Chart shows/hides and sets position for every balloon automatically, so all you need to do is to change balloon appearance, if you want to. + @example + var chart = new AmCharts.AmSerialChart(); + // get balloon intance + var balloon = chart.balloon; + // set properties + balloon.adjustBorderColor = true; + balloon.color = "#000000"; + balloon.cornerRadius = 5; + balloon.fillColor = "#FFFFFF"; + */ + declare class AmBalloon { + /** If this is set to true, border color instead of background color will be changed when user rolls-over the slice, graph, etc. */ + adjustBorderColor: bool; + /** Balloon border opacity. Value range is 0 - 1. + @default 1 + */ + borderAlpha: number; + /** Balloon border color. #FFFFFF */ + borderColor: string; + /** Balloon border thickness. + @default 2 + */ + borderThickness: number; + /** Color of text in the balloon. #FFFFFF */ + color: string; + /** Balloon corner radius. + @default 6 + */ + cornerRadius: number; + /** Balloon background opacity. + @default 1 + */ + fillAlpha: number; + /** Balloon background color. Usually balloon background color is set by the chart. Only if "adjustBorderColor" is "true" this color will be used. #CC0000 */ + fillColor: string; + /** Size of text in the balloon. Chart's fontSize is used by default. */ + fontSize: number; + /** Horizontal padding of the balloon. + @default 8 + 3*/ + horizontalPadding: number; + /** The width of the pointer (arrow) "root". Only used if cornerRadius is 0. + @default 10 + */ + pointerWidth: number; + /** If cornerRadius of a balloon is >0, showBullet is set to true for value balloons when ChartCursor is used. If you don't want the bullet near the balloon, set it to false: chart.balloon.showBullet = false */ + showBullet: bool; + /** Text alignment, possible values "left", "middle" and "right" middle */ + textAlign: string; + /** Color of the text shadow. #000000 */ + textShadowColor: string; + /** Vertical padding of the balloon. + @default 5 + */ + verticalPadding: number; + /** Hides balloon. */ + hide(); + /** Defines a square within which the balloon should appear. Bounds are set by chart class, you don't need to call this method yourself. */ + setBounds(left: number, top: number, right: number, bottom: number); + /** Sets coordinates the balloon should point to. */ + setPosition(x: number, y: number); + /** Specifies the text which should be displayed. */ + show(value: string); + } + + /** CategoryAxesSettings settings set's settings common for all CategoryAxes of StockPanels. If you change a property after the chart is initialized, you should call stockChart.validateNow() method in order for it to work. If there is no default value specified, default value of CategoryAxis class will be used. */ + declare class CategoryAxesSettings { + /** Specifies whether number of gridCount is specified automatically, according to the axis size. + @default true + */ + autoGridCount: bool; + /** Axis opacity. */ + axisAlpha: number; + /** Axis color. */ + axisColor: string; + /** Height of category axes. Set it to 0 if you set inside property to true. + @default 28 + */ + axisHeight: number; + /** Thickness of the axis. */ + axisThickness: number; + /** Text color. */ + color: string; + /** Length of a dash. */ + dashLength: number; + /** Date formats of different periods. Possible period values: fff - milliseconds, ss - seconds, mm - minutes, hh - hours, DD - days, MM - months, WW - weeks, YYYY - years. Check this page for date formatting strings. */ + dateFormats: any[]; + /** If you want data points to be placed at equal intervals (omiting dates with no data), set equalSpacing to true. */ + equalSpacing: bool; + /** Fill opacity. Every second space between grid lines can be filled with fillColor. */ + fillAlpha: number; + /** Fill color. Every second space between grid lines can be filled with color. Set fillAlpha to a value greater than 0 to see the fills. */ + fillColor: string; + /** Text size. */ + fontSize: number; + /** Opacity of grid lines. */ + gridAlpha: number; + /** Color of grid lines. */ + gridColor: string; + /** Approximate number of grid lines. You should set autoGridCount to false in order this property not to be ignored. + @default 10 + */ + gridCount: number; + /** Thickness of grid lines. */ + gridThickness: number; + /** Periods to which data will be gruoped in case there are more data items in the selected period than specified in maxSeries property. ["ss", "10ss", "30ss", "mm", "10mm", "30mm", "hh", "DD", "WW", "MM", "YYYY"] */ + groupToPeriods: any[]; + /** Specifies whether values should be placed inside or outside of plot area. */ + inside: bool; + /** Rotation angle of a label. */ + labelRotation: number; + /** Maximum series shown at a time. In case there are more data points in the selection than maxSeries, the chart will group data to longer periods, for example - you have 250 days in the selection, and maxSeries is 150 - the chart will group data to weeks. + @default 150 + */ + maxSeries: number; + /** Specifies the shortest period of your data. fff - millisecond, ss - second, mm - minute, hh - hour, DD - day, MM - month, YYYY - year. DD */ + minPeriod: string; + /** top or "bottom". */ + position: string; + /** Specifies whether the graph should start on axis or not. In case you display columns, it is recommended to set this to false. startOnAxis can be set to true only if equalSpacing is set to true. */ + startOnAxis: bool; + /** Tick length. */ + tickLength: number; + } + + /** ChartCursorSettings settings set's settings for chart cursor. If you change a property after the chart is initialized, you should call stockChart.validateNow() method in order for it to work. If there is no default value specified, default value of ChartCursor class will be used. */ + declare class ChartCursorSettings { + /** Specifies if bullet for each graph will follow the cursor. */ + bulletsEnabled: bool; + /** Size of bullets, following the cursor. */ + bulletSize: number; + /** Opacity of the category balloon. */ + categoryBalloonAlpha: number; + /** Color of the category balloon. */ + categoryBalloonColor: string; + /** Array of date format objects. Date format object must have "period" and "format" items. Available periods are: fff - millisecond, ss - second, mm - minute, hh - hour, DD - date, WW - week, MM - month, YYYY - year. [{period:"YYYY", format:"YYYY"}, {period:"MM", format:"MMM, YYYY"}, {period:"WW", format:"MMM DD, YYYY"}, {period:"DD", format:"MMM DD, YYYY"}, {period:"hh", format:"JJ:NN"}, {period:"mm", format:"JJ:NN"}, {period:"ss", format:"JJ:NN:SS"}, {period:"fff", format:"JJ:NN:SS"}] */ + categoryBalloonDateFormats: any[]; + /** Specifies whether category balloon is enabled. */ + categoryBalloonEnabled: bool; + /** Opacity of the cursor line. */ + cursorAlpha: number; + /** Color of the cursor line. */ + cursorColor: string; + /** Possible values: "start", "middle" and "mouse". */ + cursorPosition: string; + /** Set this to "false" if you don't want chart cursor to appear in your charts. + @default true + */ + enabled: bool; + /** If this is set to true, the user will be able to pan the chart instead of zooming. */ + pan: bool; + /** Specifies whether value balloons are enabled. In case they are not, the balloons might be displayed anyway, when the user rolls-over the column or bullet. */ + valueBalloonsEnabled: bool; + /** Specifies if the user can zoom-in the chart. If pan is set to true, zoomable is switched to false automatically. */ + zoomable: bool; + } + + /* ChartScrollbarSettings settings set's settings for chart scrollbar. If you change a property after the chart is initialized, you should call stockChart.validateNow() method in order for it to work. If there is no default value specified, default value of ChartScrollbar class will be used.*/ + declare class ChartScrollbarSettings { + /** Specifies whether number of gridCount is specified automatically, according to the axis size. + @default true + */ + autoGridCount: bool; + /** Background opacity. */ + backgroundAlpha: number; + /** Background color of the scrollbar. */ + backgroundColor: string; + /** Text color. */ + color: string; + /** Set false if you don't need scrollbar. + @default true + */ + enabled: bool; + /** Font size. */ + fontSize: number; + /** Specifies which graph will be displayed in the scrollbar. */ + graph: AmGraph; + /** Graph fill opacity. */ + graphFillAlpha: number; + /** Graph fill color. */ + graphFillColor: string; + /** Graph line opacity. */ + graphLineAlpha: number; + /** Graph line color. */ + graphLineColor: string; + /** Type of chart scrollbar's graph. By default the graph type is the same as the original graph's type, however in case of candlestick or ohlc you might want to show line graph in the scrollbar. Possible values are: line, column, step, smoothedLine, candlestick, ohlc. */ + graphType: string; + /** Grid opacity. */ + gridAlpha: number; + /** Grid color. */ + gridColor: string; + /** Grid count. You should set autoGridCount to false in order this property to work. */ + gridCount: number; + /** Height of scrollbar, in pixels. + @default 40 + */ + height: number; + /** Specifies whether resize grips are hidden when mouse is away from the scrollbar. */ + hideResizeGrips: bool; + /** Duration of scrolling, when the user clicks on scrollbar's background, in seconds. */ + scrollDuration: number; + /** Selected background opacity. */ + selectedBackgroundAlpha: number; + /** Selected background color. */ + selectedBackgroundColor: string; + /** Selected graph'sfill opacity. */ + selectedGraphFillAlpha: number; + /** Selected graph'sfill color. */ + selectedGraphFillColor: string; + /** Selected graph'sline opacity. */ + selectedGraphLineAlpha: number; + /** Selected graph's line color. */ + selectedGraphLineColor: string; + /** Specifies if the chart should be updated while dragging/resizing the scrollbar or only at the moment when user releases mouse button. Usefull when working with large data sets. + @default true + */ + updateOnReleaseOnly: bool; + } + + /** AmGraph class displays all types of graphs - line, column, step line, smoothed line, ohlc and candlestick. + @example + var chart = new AmCharts.AmSerialChart(); + var graph = new AmCharts.AmGraph(); + graph.valueField = 'value'; + graph.type = 'column'; + graph.fillAlphas = 1; + chart.addGraph(graph); + */ + declare class AmGraph { + /** Name of the alpha field in your dataProvider. */ + alphaField: string; + /** Value balloon color. Will use graph or data item color if not set. */ + balloonColor: string; + /** Balloon text. You can use tags like [[value]], [[description]], [[percents]], [[open]], [[category]] [[value]] */ + balloonText: string; + /** Specifies if the line graph should be placed behind column graphs */ + behindColumns: bool; + /** Type of the bullets. Possible values are: "none", "round", "square", "triangleUp", "triangleDown", "bubble", "custom". none */ + bullet: string; + /** Opacity of bullets. Value range is 0 - 1. + @default 1 + */ + bulletAlpha: number; + /** Bullet border opacity. + @default 1 + */ + bulletBorderAlpha: number; + /** Bullet border color. Will use lineColor if not set. */ + bulletBorderColor: string; + /** Bullet border thickness. + @default 2 + */ + bulletBorderThickness: number; + /** Bullet color. Will use lineColor if not set. */ + bulletColor: string; + /** Name of the bullet field in your dataProvider. */ + bulletField: string; + /** Bullet offset. Distance from the actual data point to the bullet. Can be used to place custom bullets above the columns. */ + bulletOffset: number; + /** Bullet size. + @default 8 + */ + bulletSize: number; + /** Name of the bullet size field in your dataProvider. */ + bulletSizeField: string; + /** Name of the close field (used by candlesticks and ohlc) in your dataProvider. */ + closeField: string; + /** Color of value labels. Will use chart's color if not set. */ + color: string; + /** Name of the color field in your dataProvider. */ + colorField: string; + /** Specifies whether to connect data points if data is missing. The default value is true. + @default true + */ + connect: bool; + /** Corner radius of column. It can be set both in pixels or in percents. The chart's depth and angle styles must be set to 0. The default value is 0. Note, cornerRadiusTop will be applied for all corners of the column, JavaScript charts do not have a possibility to set separate corner radius for top and bottom. As we want all the property names to be the same both on JS and Flex, we didn't change this too. */ + cornerRadiusTop: number; + /** If bulletsEnabled of ChartCurosor is true, a bullet on each graph follows the cursor. You can set opacity of each graphs bullet. In case you want to disable these bullets for a certain graph, set opacity to 0. + @default 1 + */ + cursorBulletAlpha: number; + /** Path to the image of custom bullet. */ + customBullet: string; + /** Name of the custom bullet field in your dataProvider. */ + customBulletField: string; + /** Dash length. If you set it to a value greater than 0, the graph line will be dashed. */ + dashLength: number; + /** Name of the description field in your dataProvider. */ + descriptionField: string; + /** Opacity of fill. Plural form is used to keep the same property names as our Flex charts'. Flex charts can accept array of numbers to generate gradients. Although you can set array here, only first value of this array will be used. */ + fillAlphas: number; + /** Fill color. Will use lineColor if not set. */ + fillColors: any; + /** Name of the fill colors field in your dataProvider. */ + fillColorsField: string; + /** You can set another graph here and if fillAlpha is >0, the area from this graph to fillToGraph will be filled (instead of filling the area to the X axis). */ + fillToGraph: AmGraph; + /** Size of value labels text. Will use chart's fontSize if not set. */ + fontSize: number; + /** Orientation of the gradient fills (only for "column" graph type). Possible values are "vertical" and "horizontal". vertical */ + gradientOrientation: string; + /** Specifies whether the graph is hidden. Do not use this to show/hide the graph, use hideGraph(graph) and showGraph(graph) methods instead. */ + hidden: bool; + /** If there are more data points than hideBulletsCount, the bullets will not be shown. 0 means the bullets will always be visible. */ + hideBulletsCount: number; + /** Name of the high field (used by candlesticks and ohlc) in your dataProvider. */ + highField: string; + /** Whether to include this graph when calculating min and max value of the axis. + @default true + */ + includeInMinMax: bool; + /** Name of label color field in data provider. */ + labelColorField: string; + /** Position of value label. Possible values are: "bottom", "top", "right", "left", "inside", "middle". Sometimes position is changed by the chart, depending on a graph type, rotation, etc. top */ + labelPosition: string; + /** Value label text. You can use tags like [[value]], [[description]], [[percents]], [[open]], [[category]]. */ + labelText: string; + /** Legend marker opacity. Will use lineAlpha if not set. Value range is 0 - 1. */ + legendAlpha: number; + /** Legend marker color. Will use lineColor if not set. */ + legendColor: string; + /** Legend value text. You can use tags like [[value]], [[description]], [[percents]], [[open]], [[category]] You can also use custom fields from your dataProvider. If not set, uses Legend's valueText. */ + legendValueText: string; + /** Opacity of the line (or column border). Value range is 0 - 1. + @default 1 + */ + lineAlpha: number; + /** Color of the line (or column border). If you do not set any, the color from [[AmCoordinateChart */ + lineColor: string; + /** Name of the line color field (used by columns and candlesticks only) in your dataProvider. */ + lineColorField: string; + /** Specifies thickness of the graph line (or column border). + @default 1 + */ + lineThickness: number; + /** Name of the low field (used by candlesticks and ohlc) in your dataProvider. */ + lowField: string; + /** Legend marker type. You can set legend marker (key) type for individual graphs. Possible values are: "square", "circle", "line", "dashedLine", "triangleUp", "triangleDown", "bubble". */ + markerType: string; + /** Specifies size of the bullet which value is the biggest (XY chart). + @default 50 + */ + maxBulletSize: number; + /** Specifies minimum size of the bullet (XY chart). */ + minBulletSize: number; + /** If you use different colors for your negative values, a graph below zero line is filled with negativeColor. With this property you can define a different base value at which colors should be changed to negative colors. */ + negativeBase: number; + /** Fill opacity of negative part of the graph. Will use fillAlphas if not set. */ + negativeFillAlphas: number; + /** Fill color of negative part of the graph. Will use fillColors if not set. */ + negativeFillColors: any; //String /Array; + /** Color of the line (or column) when the values are negative. In case the graph type is candlestick or ohlc, negativeLineColor is used when close value is less then open value. */ + negativeLineColor: string; + /** Example: {precision:-1, decimalSeparator:'.', thousandsSeparator:','}. The graph uses this object's values to format the numbers. Uses chart's numberFormatter if not defined. */ + numberFormatter: Object; + /** Name of the open field (used by floating columns, candlesticks and ohlc) in your dataProvider. */ + openField: string; + /** Specifies where data points should be placed - on the beginning of the period (day, hour, etc) or in the middle (only when parseDates property of categoryAxis is set to true). This setting affects Serial chart only. Possible values are "start" and "middle". middle */ + pointPosition: string; + /** If graph's type is column and labelText is set, graph hides labels which do not fit into the column's space. If you don't want these labels to be hidden, set this to true. */ + showAllValueLabels: bool; + /** Specifies whether the value balloon of this graph is shown when mouse is over data item or chart's indicator is over some series. + @default true + */ + showBalloon: bool; + /** Specifies graphs value at which cursor is showed. This is only important for candlestick and ohlc charts, also if column chart has "open" value. Possible values are: "open", "close", "high", "low". close */ + showBalloonAt: string; + /** If the value axis of this graph has stack types like "regular" or "100%" You can exclude this graph from stacking. + @default true + */ + stackable: bool; + /** Graph title. */ + title: string; + /** Type of the graph. Possible values are: "line", "column", "step", "smoothedLine", "candlestick", "ohlc". XY and Radar charts can only display "line" type graphs. line */ + type: string; + /** Name of the url field in your dataProvider. */ + urlField: string; + /** Target to open URLs in, i.e. _blank, _top, etc. */ + urlTarget: string; + /** Specifies which value axis the graph will use. Will use the first value axis if not set. */ + valueAxis: ValueAxis; + /** Name of the value field in your dataProvider. */ + valueField: string; + /** Specifies whether this graph should be shown in the Legend. + @default true + */ + visibleInLegend: bool; + /** XY chart only. A horizontal value axis object to attach graph to. */ + xAxis: ValueAxis; + /** XY chart only. Name of the x field in your dataProvider. */ + xField: string; + /** XY chart only. A vertical value axis object to attach graph to. */ + yAxis: ValueAxis; + /** XY chart only. Name of the y field in your dataProvider. */ + yField: string; + } + + /** AxisBase is the base class for ValueAxis and CategoryAxis. It can not be instantiated explicitly. */ + declare class AxisBase { + /** Specifies whether number of gridCount is specified automatically, acoarding to the axis size. + @default true + */ + autoGridCount: bool; + /** Axis opacity. Value range is 0 - 1. + @default 1 + */ + axisAlpha: number; + /** Axis color. #000000 */ + axisColor: string; + /** Thickness of the axis. + @default 1 + */ + axisThickness: number; + /** Color of axis value labels. Will use chart's color if not set. */ + color: string; + /** Length of a dash. 0 means line is not dashed. */ + dashLength: number; + /** Fill opacity. Every second space between grid lines can be filled with color. Set fillAlpha to a value greater than 0 to see the fills. */ + fillAlpha: number; + /** Fill color. Every second space between grid lines can be filled with color. Set fillAlpha to a value greater than 0 to see the fills. #FFFFFF */ + fillColor: string; + /** Size of value labels text. Will use chart's fontSize if not set. */ + fontSize: number; + /** Opacity of grid lines. 0.2 */ + gridAlpha: number; + /** Color of grid lines. #000000 */ + gridColor: string; + /** Number of grid lines. In case this is value axis, or your categoryAxis parses dates, the number is approximate. The default value is 5. If you set autoGridCount to true, this property is ignored. + @default 5 + */ + gridCount: number; + /** Thickness of grid lines. + @default 1 + */ + gridThickness: number; + /** The array of guides belonging to this axis. */ + guides: any[]; + /** If autoMargins of a chart is set to true, but you want this axis not to be measured when calculating margin, set ignoreAxisWidth to true. */ + ignoreAxisWidth: bool; + /** Specifies whether values should be placed inside or outside plot area. */ + inside: bool; + /** Frequency at which labels should be placed. Doesn't work for CategoryAxis if parseDates is set to true. + @default 1 + */ + labelFrequency: number; + /** Rotation angle of a label. Only horizontal axis' values can be rotated. If you set this for vertical axis, the setting will be ignored. */ + labelRotation: number; + /** Specifies whether axis displays category axis' labels and value axis' values. + @default true + */ + labelsEnabled: bool; + /** The distance of the axis to the plot area, in pixels. Negative values can also be used. */ + offset: number; + /** Possible values are: "top", "bottom", "left", "right". If axis is vertical, default position is "left". If axis is horizontal, default position is "bottom". */ + position: string; + /** Whether to show first axis label or not. + @default true + */ + showFirstLabel: bool; + /** Whether to show last axis label or not. + @default true + */ + showLastLabel: bool; + /** Length of the tick marks. + @default 5 + */ + tickLength: number; + /** Title of the axis. */ + title: string; + /** Specifies if title should be bold or not. + @default true + */ + titleBold: bool; + /** Color of axis title. Will use text color of chart if not set any. */ + titleColor: string; + /** Font size of axis title. Will use font size of chart plus two pixels if not set any. */ + titleFontSize: number; + + /** Adds guide to the axis. */ + addGuide(guide:Guide); + /** Removes guide from the axis. */ + removeGuide(guide:Guide); + } + + /** ValueAxis is the class which displays value axis for the chart. The chart can have any number of value axes. For Serial chart one value axis is created automatically. For XY Chart two value axes (horizontal and vertical) are created automatically. */ + declare class ValueAxis extends AxisBase { + /** Radar chart only. Specifies distance from axis to the axis title (category) 10 */ + axisTitleOffset: number; + /** Read-only. Coordinate of the base value. */ + baseCoord: number; + /** Specifies base value of the axis. */ + baseValue: number; + /** If your values represents time units, and you want value axis labels to be formatted as duration, you have to set the duration unit. Possible values are: "ss", "mm", "hh" and "DD". */ + duration: string; + /** If duration property is set, you can specify what string should be displayed next to day, hour, minute and second. {DD:"d. ", hh:":", mm:":",ss:""} */ + durationUnits: Object; + /** Radar chart only. Possible values are: "polygons" and "circles". Set "circles" for polar charts. polygons */ + gridType: string; + /** Specifies whether guide values should be included when calculating min and max of the axis. */ + includeGuidesInMinMax: bool; + /** If true, the axis will include hidden graphs when calculating min and max values. */ + includeHidden: bool; + /** Specifies whether values on axis can only be integers or both integers and doubles. */ + integersOnly: bool; + /** Specifies if this value axis' scale should be logarithmic. */ + logarithmic: bool; + /** Read-only. Maximum value of the axis. */ + max: number; + /** If you don't want max value to be calculated by the chart, set it using this property. This value might still be adjusted so that it would be possible to draw grid at rounded intervals. */ + maximum: number; + /** Read-only. Minimum value of the axis. */ + min: number; + /** If you don't want min value to be calculated by the chart, set it using this property. This value might still be adjusted so that it would be possible to draw grid at rounded intervals. */ + minimum: number; + /** If set value axis scale (min and max numbers) will be multiplied by it. I.e. if set to 1.2 the scope of values will increase by 20%. */ + minMaxMultiplier: number; + /** Precision (number of decimals) of values. */ + precision: number; + /** Radar chart only. Specifies if categories (axes' titles) should be displayed near axes) + @default true + */ + radarCategoriesEnabled: bool; + /** pecifies if graphs's values should be recalculated to percents. */ + recalculateToPercents: bool; + /** Specifies if value axis should be reversed (smaller values on top). */ + reversed: bool; + /** Stacking mode of the axis. Possible values are: "none", "regular", "100%", "3d". none Note, only graphs of one type will be stacked. */ + stackType: string; + /** Read-only. Value difference between two grid lines. */ + step: number; + /** In case you synchronize one value axis with another, you need to set the synchronization multiplier. Use synchronizeWithAxis method to set with which axis it should be synced. */ + synchronizationMultiplier: number; + /** If this value axis is stacked and has columns, setting valueAxis.totalText = "[[total]]" will make it to display total value above the most-top column. */ + totalText: string; + /** Unit which will be added to the value label. */ + unit: string; + /** Position of the unit. Possible values are "left" and "right". right */ + unitPosition: string; + /** If true, prefixes will be used for big and small numbers. You can set arrays of prefixes directly to the chart object via prefixesOfSmallNumbers and prefixesOfBigNumbers. */ + usePrefixes: bool; + /** If true, values will always be formatted using scientific notation (5e+8, 5e-8...) Otherwise only values bigger then 1e+21 and smaller then 1e-7 will be displayed in scientific notation. */ + useScientificNotation: bool; + + /** Adds event listener to the object. type - string like 'axisChanged' (should be listed in 'events' section of this class or classes which extend this class). handler - function which is called when event happens */ + addListener(type, handler); + /** Number, - value of coordinate. Returns value of the coordinate. coordinate - y or x coordinate, in pixels. */ + coordinateToValue(coordinate); + /** Number - coordinate Returns coordinate of the value in pixels. value - Number */ + getCoordinate(value); + + /** Removes event listener from the object. */ + removeListener(obj, type, handler); + + /** One value axis can be synchronized with another value axis. You should set synchronizationMultiplyer in order for this to work. */ + synchronizeWithAxis(axis:ValueAxis); + /** XY Chart only. Zooms-in the axis to the provided values. */ + zoomToValues(startValue, endValue); + + /** Adds event listener of the type "axisZoomed" to the object. + @param type Always "axisZoomed". + @param handler XY chart only. Dispatched when axis is zoomed.*/ + addListener(type: string, handler: (e: { + /** Always "axisZoomed". */ + type: string; startValue: Date; endValue: Date; chart: AmChart; + }) => void ); + /** Adds event listener of the type "logarithmicAxisFailed" to the object. + @param type Always "logarithmicAxisFailed". + @param handler Dispatched when valueAxis is logarithmic and values equal or less then zero were found in data.*/ + addListener(type: string, handler: (e: { + /** Always "logarithmicAxisFailed". */ + type: string; chart: AmChart; + }) => void ); + + /** Removes event listener from chart object. */ + removeListener(chart: AmChart, type: string, handler: any); + } +} + +/** AmCharts object (it's not a class) is create automatically when amcharts.js or amstock.js file is included in a web page. */ +var AmCharts: AmChartsStatic; \ No newline at end of file diff --git a/angularjs/angular-mocks.d.ts b/angularjs/angular-mocks.d.ts index 33dfaa303b..72f6454f0a 100644 --- a/angularjs/angular-mocks.d.ts +++ b/angularjs/angular-mocks.d.ts @@ -24,7 +24,7 @@ module ng { debug(obj: any): string; // see http://docs.angularjs.org/api/angular.mock.inject - inject(...fns: Function[]): void; + inject(...fns: Function[]): any; // see http://docs.angularjs.org/api/angular.mock.module module(...modules: any[]): any; @@ -71,7 +71,7 @@ module ng { // see http://docs.angularjs.org/api/ngMock.$httpBackend /////////////////////////////////////////////////////////////////////////// interface IHttpBackendService { - flush(count: number): void; + flush(count?: number): void; resetExpectations(): void; verifyNoOutstandingExpectation(): void; verifyNoOutstandingRequest(): void; diff --git a/angularjs/angular-resource.d.ts b/angularjs/angular-resource.d.ts index c9ac81a02f..953ce7ef46 100644 --- a/angularjs/angular-resource.d.ts +++ b/angularjs/angular-resource.d.ts @@ -1,66 +1,82 @@ -// Type definitions for Angular JS 1.0 (ngResource module) -// Project: http://angularjs.org -// Definitions by: Diego Vilar -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - - -/////////////////////////////////////////////////////////////////////////////// -// ngResource module (angular-resource.js) -/////////////////////////////////////////////////////////////////////////////// -module ng.resource { - - /////////////////////////////////////////////////////////////////////////// - // ResourceService - // see http://docs.angularjs.org/api/ngResource.$resource - // Most part of the following definitions were achieved by analyzing the - // actual implementation, since the documentation doesn't seem to cover - // that deeply. - /////////////////////////////////////////////////////////////////////////// - interface IResourceService { - (url: string, paramDefaults?: any, actionDescriptors?: any): IResourceClass; - } - - // Just a reference to facilitate describing new actions - interface IActionDescriptor { - method: string; - isArray?: bool; - params?: any; - headers?: any; - } - - // Baseclass for everyresource with default actions. - // If you define your new actions for the resource, you will need - // to extend this interface and typecast the ResourceClass to it. - interface IResourceClass { - get: IActionCall; - save: IActionCall; - query: IActionCall; - remove: IActionCall; - delete: IActionCall; - } - - // In case of passing the first argument as anything but a function, - // it's gonna be considered data if the action method is POST, PUT or - // PATCH (in other words, methods with body). Otherwise, it's going - // to be considered as parameters to the request. - interface IActionCall { - (): IResource; - (dataOrParams: any): IResource; - (dataOrParams: any, success: Function): IResource; - (success: Function, error?: Function): IResource; - (params: any, data: any, success?: Function, error?: Function): IResource; - } - - interface IResource { - $save: IActionCall; - $remove: IActionCall; - $delete: IActionCall; - - // No documented, but they are there, just as any custom action will be - $query: IActionCall; - $get: IActionCall; - } - -} +// Type definitions for Angular JS 1.0 (ngResource module) +// Project: http://angularjs.org +// Definitions by: Diego Vilar +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + + +/////////////////////////////////////////////////////////////////////////////// +// ngResource module (angular-resource.js) +/////////////////////////////////////////////////////////////////////////////// +module ng.resource { + + /////////////////////////////////////////////////////////////////////////// + // ResourceService + // see http://docs.angularjs.org/api/ngResource.$resource + // Most part of the following definitions were achieved by analyzing the + // actual implementation, since the documentation doesn't seem to cover + // that deeply. + /////////////////////////////////////////////////////////////////////////// + interface IResourceService { + (url: string, paramDefaults?: any, + /** example: {update: { method: 'PUT' }, delete: deleteDescriptor } + where deleteDescriptor : IActionDescriptor */ + actionDescriptors?: any): IResourceClass; + } + + // Just a reference to facilitate describing new actions + interface IActionDescriptor { + method: string; + isArray?: bool; + params?: any; + headers?: any; + } + + // Baseclass for everyresource with default actions. + // If you define your new actions for the resource, you will need + // to extend this interface and typecast the ResourceClass to it. + interface IResourceClass { + get: IActionCall; + save: IActionCall; + query: IActionCall; + remove: IActionCall; + delete: IActionCall; + } + + // In case of passing the first argument as anything but a function, + // it's gonna be considered data if the action method is POST, PUT or + // PATCH (in other words, methods with body). Otherwise, it's going + // to be considered as parameters to the request. + interface IActionCall { + (): IResource; + (dataOrParams: any): IResource; + (dataOrParams: any, success: Function): IResource; + (success: Function, error?: Function): IResource; + (params: any, data: any, success?: Function, error?: Function): IResource; + } + + interface IResource { + $save: IActionCall; + $remove: IActionCall; + $delete: IActionCall; + + // No documented, but they are there, just as any custom action will be + $query: IActionCall; + $get: IActionCall; + } + + /** when creating a resource factory via IModule.factory */ + interface IResourceServiceFactoryFunction { + ($resource: ng.resource.IResourceService): ng.resource.IResourceClass; + } +} + +/** extensions to base ng based on using angular-resource */ +module ng { + + interface IModule { + /** creating a resource service factory */ + factory(name: string, resourceServiceFactoryFunction: ng.resource.IResourceServiceFactoryFunction): IModule; + } +} diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts new file mode 100644 index 0000000000..d5414dc627 --- /dev/null +++ b/angularjs/angular-tests.ts @@ -0,0 +1,140 @@ +/// + +// issue: https://github.com/borisyankov/DefinitelyTyped/issues/369 +https://github.com/witoldsz/angular-http-auth/blob/master/src/angular-http-auth.js +/** + * @license HTTP Auth Interceptor Module for AngularJS + * (c) 2012 Witold Szczerba + * License: MIT + */ +angular.module('http-auth-interceptor', []) + + .provider('authService', function () { + /** + * Holds all the requests which failed due to 401 response, + * so they can be re-requested in future, once login is completed. + */ + var buffer = []; + + /** + * Required by HTTP interceptor. + * Function is attached to provider to be invisible for regular users of this service. + */ + this.pushToBuffer = function (config: ng.IRequestConfig, deferred: ng.IDeferred) { + buffer.push({ + config: config, + deferred: deferred + }); + } + + this.$get = ['$rootScope', '$injector', function ($rootScope: ng.IScope, $injector: ng.auto.IInjectorService) { + var $http: ng.IHttpService; //initialized later because of circular dependency problem + function retry(config: ng.IRequestConfig, deferred: ng.IDeferred) { + $http = $http || $injector.get('$http'); + $http(config).then(function (response) { + deferred.resolve(response); + }); + } + function retryAll() { + for (var i = 0; i < buffer.length; ++i) { + retry(buffer[i].config, buffer[i].deferred); + } + buffer = []; + } + + return { + loginConfirmed: function () { + $rootScope.$broadcast('event:auth-loginConfirmed'); + retryAll(); + } + } + }] + }) + + /** + * $http interceptor. + * On 401 response - it stores the request and broadcasts 'event:angular-auth-loginRequired'. + */ + .config(['$httpProvider', 'authServiceProvider', function ($httpProvider: ng.IHttpProvider, authServiceProvider) { + + var interceptor = ['$rootScope', '$q', function ($rootScope: ng.IScope, $q: ng.IQService) { + function success(response: ng.IHttpPromiseCallbackArg) { + return response; + } + + function error(response: ng.IHttpPromiseCallbackArg) { + if (response.status === 401) { + var deferred = $q.defer(); + authServiceProvider.pushToBuffer(response.config, deferred); + $rootScope.$broadcast('event:auth-loginRequired'); + return deferred.promise; + } + // otherwise + return $q.reject(response); + } + + return function (promise: ng.IHttpPromise) { + return promise.then(success, error); + } + + }]; + $httpProvider.responseInterceptors.push(interceptor); + }]); + + +module HttpAndRegularPromiseTests { + interface Person { + firstName: string; + lastName: string; + } + + interface ExpectedResponse extends Person {} + + interface SomeControllerScope extends ng.IScope { + person: Person; + theAnswer: number; + letters: string[]; + } + + interface OurApiPromiseCallbackArg extends ng.IHttpPromiseCallbackArg { + data?: ExpectedResponse; + } + + var someController: Function = ($scope: SomeControllerScope, $http: ng.IHttpService, $q: ng.IQService) => { + $http.get("http://somewhere/some/resource") + .success((data: ExpectedResponse) => { + $scope.person = data; + }); + + $http.get("http://somewhere/some/resource") + .then((response: ng.IHttpPromiseCallbackArg) => { + // typing lost, so something like + // var i: number = response.data + // would type check + $scope.person = response.data; + }); + + $http.get("http://somewhere/some/resource") + .then((response: OurApiPromiseCallbackArg) => { + // typing lost, so something like + // var i: number = response.data + // would NOT type check + $scope.person = response.data; + }); + + var aPromise: ng.IPromise = $q.when({firstName: "Jack", lastName: "Sparrow"}); + aPromise.then((person: Person) => { + $scope.person = person; + }); + + var bPromise: ng.IPromise = $q.when(42); + bPromise.then((answer: number) => { + $scope.theAnswer = answer; + }); + + var cPromise: ng.IPromise = $q.when(["a", "b", "c"]); + cPromise.then((letters: string[]) => { + $scope.letters = letters; + }); + } +} diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index e49e0a86a5..b8d683c5c1 100644 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -1,639 +1,662 @@ -// Type definitions for Angular JS 1.0 -// Project: http://angularjs.org -// Definitions by: Diego Vilar -// Definitions: https://github.com/borisyankov/DefinitelyTyped - - -/// - -declare var angular: ng.IAngularStatic; - -/////////////////////////////////////////////////////////////////////////////// -// ng module (angular.js) -/////////////////////////////////////////////////////////////////////////////// -module ng { - - // All service providers extend this interface - interface IServiceProvider { - $get(): any; - } - - /////////////////////////////////////////////////////////////////////////// - // AngularStatic - // see http://docs.angularjs.org/api - /////////////////////////////////////////////////////////////////////////// - interface IAngularStatic { - bind(context: any, fn: Function, ...args: any[]): Function; - bootstrap(element: string, modules?: any[]): auto.IInjectorService; - bootstrap(element: JQuery, modules?: any[]): auto.IInjectorService; - bootstrap(element: Element, modules?: any[]): auto.IInjectorService; - copy(source: any, destination?: any): any; - element: JQueryStatic; - equals(value1: any, value2: any): bool; - extend(destination: any, ...sources: any[]): any; - forEach(obj: any, iterator: (value, key) => any, context?: any): any; - fromJson(json: string): any; - identity(arg?: any): any; - injector(modules?: any[]): auto.IInjectorService; - isArray(value: any): bool; - isDate(value: any): bool; - isDefined(value: any): bool; - isElement(value: any): bool; - isFunction(value: any): bool; - isNumber(value: any): bool; - isObject(value: any): bool; - isString(value: any): bool; - isUndefined(value: any): bool; - lowercase(str: string): string; - module(name: string, requires?: string[], configFunction?: Function): IModule; - noop(...args: any[]): void; - toJson(obj: any, pretty?: bool): string; - uppercase(str: string): string; - version: { - full: string; - major: number; - minor: number; - dot: number; - codename: string; - }; - } - - /////////////////////////////////////////////////////////////////////////// - // Module - // see http://docs.angularjs.org/api/angular.Module - /////////////////////////////////////////////////////////////////////////// - interface IModule { - config(configFn: Function): IModule; - config(inlineAnnotadedFunction: any[]): IModule; - constant(name: string, value: any): IModule; - controller(name: string, controllerConstructor: Function): IModule; - controller(name: string, inlineAnnotadedConstructor: any[]): IModule; - directive(name: string, directiveFactory: Function): IModule; - directive(name: string, inlineAnnotadedFunction: any[]): IModule; - factory(name: string, serviceFactoryFunction: Function): IModule; - factory(name: string, inlineAnnotadedFunction: any[]): IModule; - filter(name: string, filterFactoryFunction: Function): IModule; - filter(name: string, inlineAnnotadedFunction: any[]): IModule; - provider(name: string, serviceProviderConstructor: Function): IModule; - provider(name: string, inlineAnnotadedConstructor: any[]): IModule; - run(initializationFunction: Function): IModule; - run(inlineAnnotadedFunction: any[]): IModule; - service(name: string, serviceConstructor: Function): IModule; - service(name: string, inlineAnnotadedConstructor: any[]): IModule; - value(name: string, value: any): IModule; - - // Properties - name: string; - requires: string[]; - } - - /////////////////////////////////////////////////////////////////////////// - // Attributes - // see http://docs.angularjs.org/api/ng.$compile.directive.Attributes - /////////////////////////////////////////////////////////////////////////// - interface IAttributes { - $set(name: string, value: any): void; - $attr: any; - } - - /////////////////////////////////////////////////////////////////////////// - // FormController - // see http://docs.angularjs.org/api/ng.directive:form.FormController - /////////////////////////////////////////////////////////////////////////// - interface IFormController { - $pristine: bool; - $dirty: bool; - $valid: bool; - $invalid: bool; - $error: any; - } - - /////////////////////////////////////////////////////////////////////////// - // NgModelController - // see http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController - /////////////////////////////////////////////////////////////////////////// - interface INgModelController { - $render(): void; - $setValidity(validationErrorKey: string, isValid: bool): void; - $setViewValue(value: string): void; - - // XXX Not sure about the types here. Documentation states it's a string, but - // I've seen it receiving other types throughout the code. - // Falling back to any for now. - $viewValue: any; - - // XXX Same as avove - $modelValue: any; - - $parsers: IModelParser[]; - $formatters: IModelFormatter[]; - $error: any; - $pristine: bool; - $dirty: bool; - $valid: bool; - $invalid: bool; - } - - interface IModelParser { - (value: any): any; - } - - interface IModelFormatter { - (value: any): any; - } - - /////////////////////////////////////////////////////////////////////////// - // Scope - // see http://docs.angularjs.org/api/ng.$rootScope.Scope - /////////////////////////////////////////////////////////////////////////// - interface IScope { - // Documentation says exp is optional, but actual implementaton counts on it - $apply(exp: string): any; - $apply(exp: (scope: IScope) => any): any; - - $broadcast(name: string, ...args: any[]): IAngularEvent; - $destroy(): void; - $digest(): void; - $emit(name: string, ...args: any[]): IAngularEvent; - - // Documentation says exp is optional, but actual implementaton counts on it - $eval(expression: string): any; - $eval(expression: (scope: IScope) => any): any; - - // Documentation says exp is optional, but actual implementaton counts on it - $evalAsync(expression: string): void; - $evalAsync(expression: (scope: IScope) => any): void; - - // Defaults to false by the implementation checking strategy - $new(isolate?: bool): IScope; - - $on(name: string, listener: (event: IAngularEvent, ...args: any[]) => any): Function; - - $watch(watchExpression: string, listener?: string, objectEquality?: bool): Function; - $watch(watchExpression: string, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: bool): Function; - $watch(watchExpression: (scope: IScope) => any, listener?: string, objectEquality?: bool): Function; - $watch(watchExpression: (scope: IScope) => any, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: bool): Function; - - $id: number; - } - - interface IAngularEvent { - targetScope: IScope; - currentScope: IScope; - name: string; - preventDefault: Function; - defaultPrevented: bool; - - // Available only events that were $emit-ted - stopPropagation?: Function; - } - - /////////////////////////////////////////////////////////////////////////// - // WindowService - // see http://docs.angularjs.org/api/ng.$window - /////////////////////////////////////////////////////////////////////////// - interface IWindowService extends Window {} - - /////////////////////////////////////////////////////////////////////////// - // BrowserService - // TODO undocumented, so we need to get it from the source code - /////////////////////////////////////////////////////////////////////////// - interface IBrowserService {} - - /////////////////////////////////////////////////////////////////////////// - // TimeoutService - // see http://docs.angularjs.org/api/ng.$timeout - /////////////////////////////////////////////////////////////////////////// - interface ITimeoutService { - (func: Function, delay?: number, invokeApply?: bool): IPromise; - cancel(promise: IPromise): bool; - } - - /////////////////////////////////////////////////////////////////////////// - // FilterService - // see http://docs.angularjs.org/api/ng.$filter - // see http://docs.angularjs.org/api/ng.$filterProvider - /////////////////////////////////////////////////////////////////////////// - interface IFilterService { - (name: string): Function; - } - - interface IFilterProvider extends IServiceProvider { - register(name: string, filterFactory: Function): IServiceProvider; - } - - /////////////////////////////////////////////////////////////////////////// - // LocaleService - // see http://docs.angularjs.org/api/ng.$locale - /////////////////////////////////////////////////////////////////////////// - interface ILocaleService { - id: string; - - // These are not documented - // Check angular's i18n files for exemples - NUMBER_FORMATS: ILocaleNumberFormatDescriptor; - DATETIME_FORMATS: ILocaleDateTimeFormatDescriptor; - pluralCat: (num: any) => string; - } - - interface ILocaleNumberFormatDescriptor { - DECIMAL_SEP: string; - GROUP_SEP: string; - PATTERNS: ILocaleNumberPatternDescriptor[]; - CURRENCY_SYM: string; - } - - interface ILocaleNumberPatternDescriptor { - minInt: number; - minFrac: number; - maxFrac: number; - posPre: string; - posSuf: string; - negPre: string; - negSuf: string; - gSize: number; - lgSize: number; - } - - interface ILocaleDateTimeFormatDescriptor { - MONTH: string[]; - SHORTMONTH: string[]; - DAY: string[]; - SHORTDAY: string[]; - AMPMS: string[]; - medium: string; - short: string; - fullDate: string; - longDate: string; - mediumDate: string; - shortDate: string; - mediumTime: string; - shortTime: string; - } - - /////////////////////////////////////////////////////////////////////////// - // LogService - // see http://docs.angularjs.org/api/ng.$log - /////////////////////////////////////////////////////////////////////////// - interface ILogService { - error: ILogCall; - info: ILogCall; - log: ILogCall; - warn: ILogCall; - } - - // We define this as separete interface so we can reopen it later for - // the ngMock module. - interface ILogCall { - (...args: any[]): void; - } - - /////////////////////////////////////////////////////////////////////////// - // ParseService - // see http://docs.angularjs.org/api/ng.$parse - /////////////////////////////////////////////////////////////////////////// - interface IParseService { - (expression: string): ICompiledExpression; - } - - interface ICompiledExpression { - (context: any, locals?: any): any; - - // If value is not provided, undefined is gonna be used since the implementation - // does not check the parameter. Let's force a value for consistency. If consumer - // whants to undefine it, pass the undefined value explicitly. - assign(context: any, value: any): any; - } - - /////////////////////////////////////////////////////////////////////////// - // LocationService - // see http://docs.angularjs.org/api/ng.$location - // see http://docs.angularjs.org/api/ng.$locationProvider - // see http://docs.angularjs.org/guide/dev_guide.services.$location - /////////////////////////////////////////////////////////////////////////// - interface ILocationService { - absUrl(): string; - hash(): string; - hash(newHash: string): ILocationService; - host(): string; - path(): string; - path(newPath: string): ILocationService; - port(): number; - protocol(): string; - replace(): ILocationService; - search(): string; - search(parametersMap: any): ILocationService; - search(parameter: string, parameterValue: any): ILocationService; - url(): string; - url(url: string): ILocationService; - } - - interface ILocationProvider extends IServiceProvider { - hashPrefix(): string; - hashPrefix(prefix: string): ILocationProvider; - html5Mode(): bool; - - // Documentation states that parameter is string, but - // implementation tests it as boolean, which makes more sense - // since this is a toggler - html5Mode(active: bool): ILocationProvider; - } - - /////////////////////////////////////////////////////////////////////////// - // DocumentService - // see http://docs.angularjs.org/api/ng.$document - /////////////////////////////////////////////////////////////////////////// - interface IDocumentService extends Document {} - - /////////////////////////////////////////////////////////////////////////// - // ExceptionHandlerService - // see http://docs.angularjs.org/api/ng.$exceptionHandler - /////////////////////////////////////////////////////////////////////////// - interface IExceptionHandlerService { - (exception: Error, cause?: string): void; - } - - /////////////////////////////////////////////////////////////////////////// - // RootElementService - // see http://docs.angularjs.org/api/ng.$rootElement - /////////////////////////////////////////////////////////////////////////// - interface IRootElementService extends JQuery {} - - /////////////////////////////////////////////////////////////////////////// - // QService - // see http://docs.angularjs.org/api/ng.$q - /////////////////////////////////////////////////////////////////////////// - interface IQService { - all(promises: IPromise[]): IPromise; - defer(): IDeferred; - reject(reason?: any): IPromise; - when(value: any): IPromise; - } - - interface IPromise { - then(successCallback: Function, errorCallback?: Function): IPromise; - } - - interface IDeferred { - resolve(value?: any): void; - reject(reason?: string): void; - promise: IPromise; - } - - /////////////////////////////////////////////////////////////////////////// - // AnchorScrollService - // see http://docs.angularjs.org/api/ng.$anchorScroll - /////////////////////////////////////////////////////////////////////////// - interface IAnchorScrollService { - (): void; - } - - interface IAnchorScrollProvider extends IServiceProvider { - disableAutoScrolling(): void; - } - - /////////////////////////////////////////////////////////////////////////// - // CacheFactoryService - // see http://docs.angularjs.org/api/ng.$cacheFactory - /////////////////////////////////////////////////////////////////////////// - interface ICacheFactoryService { - // Lets not foce the optionsMap to have the capacity member. Even though - // it's the ONLY option considered by the implementation today, a consumer - // might find it useful to associate some other options to the cache object. - //(cacheId: string, optionsMap?: { capacity: number; }): CacheObject; - (cacheId: string, optionsMap?: { capacity: number; }): ICacheObject; - - // Methods bellow are not documented - info(): any; - get(cacheId: string): ICacheObject; - } - - interface ICacheObject { - info(): { - id: string; - size: number; - - // Not garanteed to have, since it's a non-mandatory option - //capacity: number; - }; - put(key: string, value?: any): void; - get(key: string): any; - remove(key: string): void; - removeAll(): void; - destroy(): void; - } - - /////////////////////////////////////////////////////////////////////////// - // CompileService - // see http://docs.angularjs.org/api/ng.$compile - // see http://docs.angularjs.org/api/ng.$compileProvider - /////////////////////////////////////////////////////////////////////////// - interface ICompileService { - (element: string, transclude?: ITemplateLinkingFunction, maxPriority?: number): ITemplateLinkingFunction; - (element: Element, transclude?: ITemplateLinkingFunction, maxPriority?: number): ITemplateLinkingFunction; - (element: JQuery, transclude?: ITemplateLinkingFunction, maxPriority?: number): ITemplateLinkingFunction; - } - - interface ICompileProvider extends IServiceProvider { - directive(name: string, directiveFactory: Function): ICompileProvider; - - // Undocumented, but it is there... - directive(directivesMap: any): ICompileProvider; - } - - interface ITemplateLinkingFunction { - // Let's hint but not force cloneAttachFn's signature - (scope: IScope, cloneAttachFn?: (clonedElement?: JQuery, scope?: IScope) => any): JQuery; - } - - /////////////////////////////////////////////////////////////////////////// - // ControllerService - // see http://docs.angularjs.org/api/ng.$controller - // see http://docs.angularjs.org/api/ng.$controllerProvider - /////////////////////////////////////////////////////////////////////////// - interface IControllerService { - // Although the documentation doesn't state this, locals are optional - (controllerConstructor: Function, locals?: any): any; - (controllerName: string, locals?: any): any; - } - - interface IControlerProvider extends IServiceProvider { - register(name: string, controllerConstructor: Function): void; - register(name: string, dependencyAnnotadedConstructor: any[]): void; - } - - /////////////////////////////////////////////////////////////////////////// - // HttpService - // see http://docs.angularjs.org/api/ng.$http - /////////////////////////////////////////////////////////////////////////// - interface IHttpService { - // At least moethod and url must be provided... - (config: IRequestConfig): IHttpPromise; - get(url: string, RequestConfig?: any): IHttpPromise; - delete(url: string, RequestConfig?: any): IHttpPromise; - head(url: string, RequestConfig?: any): IHttpPromise; - jsonp(url: string, RequestConfig?: any): IHttpPromise; - post(url: string, data: any, RequestConfig?: any): IHttpPromise; - put(url: string, data: any, RequestConfig?: any): IHttpPromise; - defaults: IRequestConfig; - - // For debugging, BUT it is documented as public, so... - pendingRequests: any[]; - } - - // This is just for hinting. - // Some opetions might not be available depending on the request. - // see http://docs.angularjs.org/api/ng.$http#Usage for options explanations - interface IRequestConfig { - method: string; - url: string; - params?: any; - - // XXX it has it's own structure... perhaps we should define it in the future - headers?: any; - - cache?: any; - timeout?: number; - withCredentials?: bool; - - // These accept multiple types, so let's defile them as any - data?: any; - transformRequest?: any; - transformResponse?: any; - } - - interface IHttpPromise extends IPromise { - success(callback: (data: any, status: number, headers: (headerName: string) => string, config: IRequestConfig) => any): IHttpPromise; - error(callback: (data: any, status: number, headers: (headerName: string) => string, config: IRequestConfig) => any): IHttpPromise; - } - - interface IHttpProvider extends IServiceProvider { - defaults: IRequestConfig; - responseInterceptors: any[]; - } - - /////////////////////////////////////////////////////////////////////////// - // HttpBackendService - // see http://docs.angularjs.org/api/ng.$httpBackend - // You should never need to use this service directly. - /////////////////////////////////////////////////////////////////////////// - interface IHttpBackendService { - // XXX Perhaps define callback signature in the future - (method: string, url: string, post?: any, callback?: Function, headers?: any, timeout?: number, withCredentials?: bool): void; - } - - /////////////////////////////////////////////////////////////////////////// - // InterpolateService - // see http://docs.angularjs.org/api/ng.$interpolate - // see http://docs.angularjs.org/api/ng.$interpolateProvider - /////////////////////////////////////////////////////////////////////////// - interface IInterpolateService { - (text: string, mustHaveExpression?: bool): IInterpolationFunction; - endSymbol(): string; - startSymbol(): string; - } - - interface IInterpolationFunction { - (context: any): string; - } - - interface IInterpolateProvider extends IServiceProvider { - startSymbol(): string; - startSymbol(value: string): IInterpolateProvider; - endSymbol(): string; - endSymbol(value: string): IInterpolateProvider; - } - - /////////////////////////////////////////////////////////////////////////// - // RouteParamsService - // see http://docs.angularjs.org/api/ng.$routeParams - /////////////////////////////////////////////////////////////////////////// - interface IRouteParamsService {} - - /////////////////////////////////////////////////////////////////////////// - // TemplateCacheService - // see http://docs.angularjs.org/api/ng.$templateCache - /////////////////////////////////////////////////////////////////////////// - interface ITemplateCacheService extends ICacheObject {} - - /////////////////////////////////////////////////////////////////////////// - // RootScopeService - // see http://docs.angularjs.org/api/ng.$rootScope - /////////////////////////////////////////////////////////////////////////// - interface IRootScopeService extends IScope {} - - /////////////////////////////////////////////////////////////////////////// - // RouteService - // see http://docs.angularjs.org/api/ng.$route - // see http://docs.angularjs.org/api/ng.$routeProvider - /////////////////////////////////////////////////////////////////////////// - interface IRouteService { - reload(): void; - routes: any; - - // May not always be available. For instance, current will not be available - // to a controller that was not initialized as a result of a route maching. - current?: ICurrentRoute; - } - - // see http://docs.angularjs.org/api/ng.$routeProvider#when for options explanations - interface IRoute { - controller?: any; - template?: string; - templateUrl?: string; - resolve?: any; - redirectTo?: any; - reloadOnSearch?: bool; - } - - // see http://docs.angularjs.org/api/ng.$route#current - interface ICurrentRoute extends IRoute { - locals: { - $scope: IScope; - $template: string; - }; - } - - interface IRouteProviderProvider extends IServiceProvider { - otherwise(params: any): IRouteProviderProvider; - when(path: string, route: IRoute): IRouteProviderProvider; - } - - /////////////////////////////////////////////////////////////////////////// - // AUTO module (angular.js) - /////////////////////////////////////////////////////////////////////////// - export module auto { - - /////////////////////////////////////////////////////////////////////// - // InjectorService - // see http://docs.angularjs.org/api/AUTO.$injector - /////////////////////////////////////////////////////////////////////// - interface IInjectorService { - annotate(fn: Function): string[]; - annotate(inlineAnnotadedFunction: any[]): string[]; - get(name: string): any; - instantiate(typeConstructor: Function, locals?: any): any; - invoke(func: Function, context?: any, locals?: any): any; - } - - /////////////////////////////////////////////////////////////////////// - // ProvideService - // see http://docs.angularjs.org/api/AUTO.$provide - /////////////////////////////////////////////////////////////////////// - interface IProvideService { - // Documentation says it returns the registered instance, but actual - // implementation does not return anything. - // constant(name: string, value: any): any; - constant(name: string, value: any): void; - - decorator(name: string, decorator: Function): void; - factory(name: string, serviceFactoryFunction: Function): ng.IServiceProvider; - provider(name: string, provider: ng.IServiceProvider): ng.IServiceProvider; - provider(name: string, serviceProviderConstructor: Function): ng.IServiceProvider; - service(name: string, constructor: Function): ng.IServiceProvider; - value(name: string, value: any): ng.IServiceProvider; - } - - } - -} +// Type definitions for Angular JS 1.0 +// Project: http://angularjs.org +// Definitions by: Diego Vilar +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +/// + +declare var angular: ng.IAngularStatic; + +/////////////////////////////////////////////////////////////////////////////// +// ng module (angular.js) +/////////////////////////////////////////////////////////////////////////////// +module ng { + + // All service providers extend this interface + interface IServiceProvider { + $get(): any; + } + + /////////////////////////////////////////////////////////////////////////// + // AngularStatic + // see http://docs.angularjs.org/api + /////////////////////////////////////////////////////////////////////////// + interface IAngularStatic { + bind(context: any, fn: Function, ...args: any[]): Function; + bootstrap(element: string, modules?: any[]): auto.IInjectorService; + bootstrap(element: JQuery, modules?: any[]): auto.IInjectorService; + bootstrap(element: Element, modules?: any[]): auto.IInjectorService; + copy(source: any, destination?: any): any; + element: JQueryStatic; + equals(value1: any, value2: any): bool; + extend(destination: any, ...sources: any[]): any; + forEach(obj: any, iterator: (value, key) => any, context?: any): any; + fromJson(json: string): any; + identity(arg?: any): any; + injector(modules?: any[]): auto.IInjectorService; + isArray(value: any): bool; + isDate(value: any): bool; + isDefined(value: any): bool; + isElement(value: any): bool; + isFunction(value: any): bool; + isNumber(value: any): bool; + isObject(value: any): bool; + isString(value: any): bool; + isUndefined(value: any): bool; + lowercase(str: string): string; + /** construct your angular application + official docs: Interface for configuring angular modules. + see: http://docs.angularjs.org/api/angular.Module + */ + module( + /** name of your module you want to create */ + name: string, + /** name of modules yours depends on */ + requires?: string[], + configFunction?: Function): IModule; + noop(...args: any[]): void; + toJson(obj: any, pretty?: bool): string; + uppercase(str: string): string; + version: { + full: string; + major: number; + minor: number; + dot: number; + codename: string; + }; + } + + /////////////////////////////////////////////////////////////////////////// + // Module + // see http://docs.angularjs.org/api/angular.Module + /////////////////////////////////////////////////////////////////////////// + interface IModule { + /** configure existing services. + Use this method to register work which needs to be performed on module loading + */ + config(configFn: Function): IModule; + /** configure existing services. + Use this method to register work which needs to be performed on module loading + */ + config(inlineAnnotadedFunction: any[]): IModule; + constant(name: string, value: any): IModule; + controller(name: string, controllerConstructor: Function): IModule; + controller(name: string, inlineAnnotadedConstructor: any[]): IModule; + directive(name: string, directiveFactory: Function): IModule; + directive(name: string, inlineAnnotadedFunction: any[]): IModule; + factory(name: string, serviceFactoryFunction: Function): IModule; + factory(name: string, inlineAnnotadedFunction: any[]): IModule; + filter(name: string, filterFactoryFunction: Function): IModule; + filter(name: string, inlineAnnotadedFunction: any[]): IModule; + provider(name: string, serviceProviderConstructor: Function): IModule; + provider(name: string, inlineAnnotadedConstructor: any[]): IModule; + run(initializationFunction: Function): IModule; + run(inlineAnnotadedFunction: any[]): IModule; + service(name: string, serviceConstructor: Function): IModule; + service(name: string, inlineAnnotadedConstructor: any[]): IModule; + value(name: string, value: any): IModule; + + // Properties + name: string; + requires: string[]; + } + + /////////////////////////////////////////////////////////////////////////// + // Attributes + // see http://docs.angularjs.org/api/ng.$compile.directive.Attributes + /////////////////////////////////////////////////////////////////////////// + interface IAttributes { + $set(name: string, value: any): void; + $attr: any; + } + + /////////////////////////////////////////////////////////////////////////// + // FormController + // see http://docs.angularjs.org/api/ng.directive:form.FormController + /////////////////////////////////////////////////////////////////////////// + interface IFormController { + $pristine: bool; + $dirty: bool; + $valid: bool; + $invalid: bool; + $error: any; + } + + /////////////////////////////////////////////////////////////////////////// + // NgModelController + // see http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController + /////////////////////////////////////////////////////////////////////////// + interface INgModelController { + $render(): void; + $setValidity(validationErrorKey: string, isValid: bool): void; + $setViewValue(value: string): void; + + // XXX Not sure about the types here. Documentation states it's a string, but + // I've seen it receiving other types throughout the code. + // Falling back to any for now. + $viewValue: any; + + // XXX Same as avove + $modelValue: any; + + $parsers: IModelParser[]; + $formatters: IModelFormatter[]; + $error: any; + $pristine: bool; + $dirty: bool; + $valid: bool; + $invalid: bool; + } + + interface IModelParser { + (value: any): any; + } + + interface IModelFormatter { + (value: any): any; + } + + /////////////////////////////////////////////////////////////////////////// + // Scope + // see http://docs.angularjs.org/api/ng.$rootScope.Scope + /////////////////////////////////////////////////////////////////////////// + interface IScope { + // Documentation says exp is optional, but actual implementaton counts on it + $apply(exp: string): any; + $apply(exp: (scope: IScope) => any): any; + + $broadcast(name: string, ...args: any[]): IAngularEvent; + $destroy(): void; + $digest(): void; + $emit(name: string, ...args: any[]): IAngularEvent; + + // Documentation says exp is optional, but actual implementaton counts on it + $eval(expression: string): any; + $eval(expression: (scope: IScope) => any): any; + + // Documentation says exp is optional, but actual implementaton counts on it + $evalAsync(expression: string): void; + $evalAsync(expression: (scope: IScope) => any): void; + + // Defaults to false by the implementation checking strategy + $new(isolate?: bool): IScope; + + $on(name: string, listener: (event: IAngularEvent, ...args: any[]) => any): Function; + + $watch(watchExpression: string, listener?: string, objectEquality?: bool): Function; + $watch(watchExpression: string, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: bool): Function; + $watch(watchExpression: (scope: IScope) => any, listener?: string, objectEquality?: bool): Function; + $watch(watchExpression: (scope: IScope) => any, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: bool): Function; + + $id: number; + } + + interface IAngularEvent { + targetScope: IScope; + currentScope: IScope; + name: string; + preventDefault: Function; + defaultPrevented: bool; + + // Available only events that were $emit-ted + stopPropagation?: Function; + } + + /////////////////////////////////////////////////////////////////////////// + // WindowService + // see http://docs.angularjs.org/api/ng.$window + /////////////////////////////////////////////////////////////////////////// + interface IWindowService extends Window {} + + /////////////////////////////////////////////////////////////////////////// + // BrowserService + // TODO undocumented, so we need to get it from the source code + /////////////////////////////////////////////////////////////////////////// + interface IBrowserService {} + + /////////////////////////////////////////////////////////////////////////// + // TimeoutService + // see http://docs.angularjs.org/api/ng.$timeout + /////////////////////////////////////////////////////////////////////////// + interface ITimeoutService { + (func: Function, delay?: number, invokeApply?: bool): IPromise; + cancel(promise: IPromise): bool; + } + + /////////////////////////////////////////////////////////////////////////// + // FilterService + // see http://docs.angularjs.org/api/ng.$filter + // see http://docs.angularjs.org/api/ng.$filterProvider + /////////////////////////////////////////////////////////////////////////// + interface IFilterService { + (name: string): Function; + } + + interface IFilterProvider extends IServiceProvider { + register(name: string, filterFactory: Function): IServiceProvider; + } + + /////////////////////////////////////////////////////////////////////////// + // LocaleService + // see http://docs.angularjs.org/api/ng.$locale + /////////////////////////////////////////////////////////////////////////// + interface ILocaleService { + id: string; + + // These are not documented + // Check angular's i18n files for exemples + NUMBER_FORMATS: ILocaleNumberFormatDescriptor; + DATETIME_FORMATS: ILocaleDateTimeFormatDescriptor; + pluralCat: (num: any) => string; + } + + interface ILocaleNumberFormatDescriptor { + DECIMAL_SEP: string; + GROUP_SEP: string; + PATTERNS: ILocaleNumberPatternDescriptor[]; + CURRENCY_SYM: string; + } + + interface ILocaleNumberPatternDescriptor { + minInt: number; + minFrac: number; + maxFrac: number; + posPre: string; + posSuf: string; + negPre: string; + negSuf: string; + gSize: number; + lgSize: number; + } + + interface ILocaleDateTimeFormatDescriptor { + MONTH: string[]; + SHORTMONTH: string[]; + DAY: string[]; + SHORTDAY: string[]; + AMPMS: string[]; + medium: string; + short: string; + fullDate: string; + longDate: string; + mediumDate: string; + shortDate: string; + mediumTime: string; + shortTime: string; + } + + /////////////////////////////////////////////////////////////////////////// + // LogService + // see http://docs.angularjs.org/api/ng.$log + /////////////////////////////////////////////////////////////////////////// + interface ILogService { + error: ILogCall; + info: ILogCall; + log: ILogCall; + warn: ILogCall; + } + + // We define this as separete interface so we can reopen it later for + // the ngMock module. + interface ILogCall { + (...args: any[]): void; + } + + /////////////////////////////////////////////////////////////////////////// + // ParseService + // see http://docs.angularjs.org/api/ng.$parse + /////////////////////////////////////////////////////////////////////////// + interface IParseService { + (expression: string): ICompiledExpression; + } + + interface ICompiledExpression { + (context: any, locals?: any): any; + + // If value is not provided, undefined is gonna be used since the implementation + // does not check the parameter. Let's force a value for consistency. If consumer + // whants to undefine it, pass the undefined value explicitly. + assign(context: any, value: any): any; + } + + /////////////////////////////////////////////////////////////////////////// + // LocationService + // see http://docs.angularjs.org/api/ng.$location + // see http://docs.angularjs.org/api/ng.$locationProvider + // see http://docs.angularjs.org/guide/dev_guide.services.$location + /////////////////////////////////////////////////////////////////////////// + interface ILocationService { + absUrl(): string; + hash(): string; + hash(newHash: string): ILocationService; + host(): string; + path(): string; + path(newPath: string): ILocationService; + port(): number; + protocol(): string; + replace(): ILocationService; + search(): string; + search(parametersMap: any): ILocationService; + search(parameter: string, parameterValue: any): ILocationService; + url(): string; + url(url: string): ILocationService; + } + + interface ILocationProvider extends IServiceProvider { + hashPrefix(): string; + hashPrefix(prefix: string): ILocationProvider; + html5Mode(): bool; + + // Documentation states that parameter is string, but + // implementation tests it as boolean, which makes more sense + // since this is a toggler + html5Mode(active: bool): ILocationProvider; + } + + /////////////////////////////////////////////////////////////////////////// + // DocumentService + // see http://docs.angularjs.org/api/ng.$document + /////////////////////////////////////////////////////////////////////////// + interface IDocumentService extends Document {} + + /////////////////////////////////////////////////////////////////////////// + // ExceptionHandlerService + // see http://docs.angularjs.org/api/ng.$exceptionHandler + /////////////////////////////////////////////////////////////////////////// + interface IExceptionHandlerService { + (exception: Error, cause?: string): void; + } + + /////////////////////////////////////////////////////////////////////////// + // RootElementService + // see http://docs.angularjs.org/api/ng.$rootElement + /////////////////////////////////////////////////////////////////////////// + interface IRootElementService extends JQuery {} + + /////////////////////////////////////////////////////////////////////////// + // QService + // see http://docs.angularjs.org/api/ng.$q + /////////////////////////////////////////////////////////////////////////// + interface IQService { + all(promises: IPromise[]): IPromise; + defer(): IDeferred; + reject(reason?: any): IPromise; + when(value: any): IPromise; + } + + interface IPromise { + then(successCallback: (promiseValue: any) => any, errorCallback?: (reason: any) => any): IPromise; + } + + interface IDeferred { + resolve(value?: any): void; + reject(reason?: any): void; + promise: IPromise; + } + + /////////////////////////////////////////////////////////////////////////// + // AnchorScrollService + // see http://docs.angularjs.org/api/ng.$anchorScroll + /////////////////////////////////////////////////////////////////////////// + interface IAnchorScrollService { + (): void; + } + + interface IAnchorScrollProvider extends IServiceProvider { + disableAutoScrolling(): void; + } + + /////////////////////////////////////////////////////////////////////////// + // CacheFactoryService + // see http://docs.angularjs.org/api/ng.$cacheFactory + /////////////////////////////////////////////////////////////////////////// + interface ICacheFactoryService { + // Lets not foce the optionsMap to have the capacity member. Even though + // it's the ONLY option considered by the implementation today, a consumer + // might find it useful to associate some other options to the cache object. + //(cacheId: string, optionsMap?: { capacity: number; }): CacheObject; + (cacheId: string, optionsMap?: { capacity: number; }): ICacheObject; + + // Methods bellow are not documented + info(): any; + get (cacheId: string): ICacheObject; + } + + interface ICacheObject { + info(): { + id: string; + size: number; + + // Not garanteed to have, since it's a non-mandatory option + //capacity: number; + }; + put(key: string, value?: any): void; + get (key: string): any; + remove(key: string): void; + removeAll(): void; + destroy(): void; + } + + /////////////////////////////////////////////////////////////////////////// + // CompileService + // see http://docs.angularjs.org/api/ng.$compile + // see http://docs.angularjs.org/api/ng.$compileProvider + /////////////////////////////////////////////////////////////////////////// + interface ICompileService { + (element: string, transclude?: ITemplateLinkingFunction, maxPriority?: number): ITemplateLinkingFunction; + (element: Element, transclude?: ITemplateLinkingFunction, maxPriority?: number): ITemplateLinkingFunction; + (element: JQuery, transclude?: ITemplateLinkingFunction, maxPriority?: number): ITemplateLinkingFunction; + } + + interface ICompileProvider extends IServiceProvider { + directive(name: string, directiveFactory: Function): ICompileProvider; + + // Undocumented, but it is there... + directive(directivesMap: any): ICompileProvider; + } + + interface ITemplateLinkingFunction { + // Let's hint but not force cloneAttachFn's signature + (scope: IScope, cloneAttachFn?: (clonedElement?: JQuery, scope?: IScope) => any): JQuery; + } + + /////////////////////////////////////////////////////////////////////////// + // ControllerService + // see http://docs.angularjs.org/api/ng.$controller + // see http://docs.angularjs.org/api/ng.$controllerProvider + /////////////////////////////////////////////////////////////////////////// + interface IControllerService { + // Although the documentation doesn't state this, locals are optional + (controllerConstructor: Function, locals?: any): any; + (controllerName: string, locals?: any): any; + } + + interface IControlerProvider extends IServiceProvider { + register(name: string, controllerConstructor: Function): void; + register(name: string, dependencyAnnotadedConstructor: any[]): void; + } + + /////////////////////////////////////////////////////////////////////////// + // HttpService + // see http://docs.angularjs.org/api/ng.$http + /////////////////////////////////////////////////////////////////////////// + interface IHttpService { + // At least moethod and url must be provided... + (config: IRequestConfig): IHttpPromise; + get (url: string, RequestConfig?: any): IHttpPromise; + delete (url: string, RequestConfig?: any): IHttpPromise; + head(url: string, RequestConfig?: any): IHttpPromise; + jsonp(url: string, RequestConfig?: any): IHttpPromise; + post(url: string, data: any, RequestConfig?: any): IHttpPromise; + put(url: string, data: any, RequestConfig?: any): IHttpPromise; + defaults: IRequestConfig; + + // For debugging, BUT it is documented as public, so... + pendingRequests: any[]; + } + + // This is just for hinting. + // Some opetions might not be available depending on the request. + // see http://docs.angularjs.org/api/ng.$http#Usage for options explanations + interface IRequestConfig { + method: string; + url: string; + params?: any; + + // XXX it has it's own structure... perhaps we should define it in the future + headers?: any; + + cache?: any; + timeout?: number; + withCredentials?: bool; + + // These accept multiple types, so let's defile them as any + data?: any; + transformRequest?: any; + transformResponse?: any; + } + + interface IHttpPromiseCallbackArg { + data?: any; + status?: number; + headers?: (headerName: string) => string; + config?: IRequestConfig; + } + + interface IHttpPromise extends IPromise { + success(callback: (data: any, status: number, headers: (headerName: string) => string, config: IRequestConfig) => any): IHttpPromise; + error(callback: (data: any, status: number, headers: (headerName: string) => string, config: IRequestConfig) => any): IHttpPromise; + then(successCallback: (response: IHttpPromiseCallbackArg) => any, errorCallback?: (response: IHttpPromiseCallbackArg) => any): IPromise; + } + + interface IHttpProvider extends IServiceProvider { + defaults: IRequestConfig; + responseInterceptors: any[]; + } + + /////////////////////////////////////////////////////////////////////////// + // HttpBackendService + // see http://docs.angularjs.org/api/ng.$httpBackend + // You should never need to use this service directly. + /////////////////////////////////////////////////////////////////////////// + interface IHttpBackendService { + // XXX Perhaps define callback signature in the future + (method: string, url: string, post?: any, callback?: Function, headers?: any, timeout?: number, withCredentials?: bool): void; + } + + /////////////////////////////////////////////////////////////////////////// + // InterpolateService + // see http://docs.angularjs.org/api/ng.$interpolate + // see http://docs.angularjs.org/api/ng.$interpolateProvider + /////////////////////////////////////////////////////////////////////////// + interface IInterpolateService { + (text: string, mustHaveExpression?: bool): IInterpolationFunction; + endSymbol(): string; + startSymbol(): string; + } + + interface IInterpolationFunction { + (context: any): string; + } + + interface IInterpolateProvider extends IServiceProvider { + startSymbol(): string; + startSymbol(value: string): IInterpolateProvider; + endSymbol(): string; + endSymbol(value: string): IInterpolateProvider; + } + + /////////////////////////////////////////////////////////////////////////// + // RouteParamsService + // see http://docs.angularjs.org/api/ng.$routeParams + /////////////////////////////////////////////////////////////////////////// + interface IRouteParamsService {} + + /////////////////////////////////////////////////////////////////////////// + // TemplateCacheService + // see http://docs.angularjs.org/api/ng.$templateCache + /////////////////////////////////////////////////////////////////////////// + interface ITemplateCacheService extends ICacheObject {} + + /////////////////////////////////////////////////////////////////////////// + // RootScopeService + // see http://docs.angularjs.org/api/ng.$rootScope + /////////////////////////////////////////////////////////////////////////// + interface IRootScopeService extends IScope {} + + /////////////////////////////////////////////////////////////////////////// + // RouteService + // see http://docs.angularjs.org/api/ng.$route + // see http://docs.angularjs.org/api/ng.$routeProvider + /////////////////////////////////////////////////////////////////////////// + interface IRouteService { + reload(): void; + routes: any; + + // May not always be available. For instance, current will not be available + // to a controller that was not initialized as a result of a route maching. + current?: ICurrentRoute; + } + + // see http://docs.angularjs.org/api/ng.$routeProvider#when for options explanations + interface IRoute { + controller?: any; + template?: string; + templateUrl?: string; + resolve?: any; + redirectTo?: any; + reloadOnSearch?: bool; + } + + // see http://docs.angularjs.org/api/ng.$route#current + interface ICurrentRoute extends IRoute { + locals: { + $scope: IScope; + $template: string; + }; + } + + interface IRouteProvider extends IServiceProvider { + otherwise(params: any): IRouteProvider; + when(path: string, route: IRoute): IRouteProvider; + } + + /////////////////////////////////////////////////////////////////////////// + // AUTO module (angular.js) + /////////////////////////////////////////////////////////////////////////// + export module auto { + + /////////////////////////////////////////////////////////////////////// + // InjectorService + // see http://docs.angularjs.org/api/AUTO.$injector + /////////////////////////////////////////////////////////////////////// + interface IInjectorService { + annotate(fn: Function): string[]; + annotate(inlineAnnotadedFunction: any[]): string[]; + get (name: string): any; + instantiate(typeConstructor: Function, locals?: any): any; + invoke(func: Function, context?: any, locals?: any): any; + } + + /////////////////////////////////////////////////////////////////////// + // ProvideService + // see http://docs.angularjs.org/api/AUTO.$provide + /////////////////////////////////////////////////////////////////////// + interface IProvideService { + // Documentation says it returns the registered instance, but actual + // implementation does not return anything. + // constant(name: string, value: any): any; + constant(name: string, value: any): void; + + decorator(name: string, decorator: Function): void; + factory(name: string, serviceFactoryFunction: Function): ng.IServiceProvider; + provider(name: string, provider: ng.IServiceProvider): ng.IServiceProvider; + provider(name: string, serviceProviderConstructor: Function): ng.IServiceProvider; + service(name: string, constructor: Function): ng.IServiceProvider; + value(name: string, value: any): ng.IServiceProvider; + } + + } + +} diff --git a/async/async-tests.ts b/async/async-tests.ts index 5330f09287..e7b57a1f89 100644 --- a/async/async-tests.ts +++ b/async/async-tests.ts @@ -156,14 +156,16 @@ q.push([{ name: 'baz' }, { name: 'bay' }, { name: 'bax' }], function (err) { console.log('finished processing bar'); }); - +var filename = ''; async.auto({ get_data: function (callback) { }, make_folder: function (callback) { }, - write_file: ['get_data', 'make_folder', function (callback) { + //arrays with different types are not accepted by TypeScript. + write_file: ['get_data', 'make_folder', function (callback) { callback(null, filename); }], - email_link: ['write_file', function (callback, results) { }] + //arrays with different types are not accepted by TypeScript. + email_link: ['write_file', function (callback, results) { }] }); @@ -174,7 +176,7 @@ async.parallel([ function (results) { async.series([ function (callback) { }, - email_link: function(callback) { } + function email_link(callback) { } ]); }); diff --git a/backbone/backbone-tests.ts b/backbone/backbone-tests.ts index 681dbf6155..f89b731969 100644 --- a/backbone/backbone-tests.ts +++ b/backbone/backbone-tests.ts @@ -105,6 +105,7 @@ function test_collection() { }); var alphabetical = Books.sortBy(function (book) { + return null; }); } diff --git a/backbone/backbone.d.ts b/backbone/backbone.d.ts index b9fcc33800..04bee0f5d7 100644 --- a/backbone/backbone.d.ts +++ b/backbone/backbone.d.ts @@ -1,246 +1,247 @@ -// Type definitions for Backbone 0.9 -// Project: http://backbonejs.org/ -// Definitions by: Boris Yankov -// Definitions: https://github.com/borisyankov/DefinitelyTyped - - -/// - -declare module Backbone { - - export interface AddOptions extends Silenceable { - at: number; - } - - export interface CreateOptions extends Silenceable { - wait: bool; - } - - export interface HistoryOptions extends Silenceable { - pushState: bool; - root: string; - } - - export interface NavigateOptions { - trigger: bool; - } - - export interface RouterOptions { - routes: any; - } - - export interface Silenceable { - silent: bool; - } - - interface on { (eventName: string, callback: (...args: any[]) => void, context?: any): any; } - interface off { (eventName?: string, callback?: (...args: any[]) => void, context?: any): any; } - interface trigger { (eventName: string, ...args: any[]): any; } - interface bind { (eventName: string, callback: (...args: any[]) => void, context?: any): any; } - interface unbind { (eventName?: string, callback?: (...args: any[]) => void, context?: any): any; } - - declare class Events { - on(eventName: string, callback: (...args:any[]) => void, context?: any): any; - off(eventName?: string, callback?: (...args:any[]) => void, context?: any): any; - trigger(eventName: string, ...args: any[]): any; - bind(eventName: string, callback: (...args:any[]) => void, context?: any): any; - unbind(eventName?: string, callback?: (...args:any[]) => void, context?: any): any; - } - - export class ModelBase extends Events { - fetch(options?: JQueryAjaxSettings); - url(): string; - parse(response); - toJSON(): any; - } - - export class Model extends ModelBase { - - static extend(properties: any, classProperties?: any): any; // do not use, prefer TypeScript's extend functionality - - attributes: any; - changed: any[]; - cid: string; - id: any; - idAttribute: string; - urlRoot() : string; - - constructor (attributes?: any, options?: any); - initialize(attributes?: any); - - get(attributeName: string): any; - set(attributeName: string, value: any); - set(obj: any); - - change(); - changedAttributes(attributes?: any): any[]; - clear(options?: Silenceable); - clone(): Model; - defaults(): any; - destroy(options?: JQueryAjaxSettings); - escape(attribute: string); - has(attribute: string): bool; - hasChanged(attribute?: string): bool; - isNew(): bool; - isValid(): string; - previous(attribute: string): any; - previousAttributes(): any[]; - save(attributes?: any, options?: JQueryAjaxSettings); - unset(attribute: string, options?: Silenceable); - validate(attributes: any): any; - } - - export class Collection extends ModelBase { - - static extend(properties: any, classProperties?: any): any; // do not use, prefer TypeScript's extend functionality - - model: Model; - models: any; - collection: Model; - length: number; - - constructor (models?: any, options?: any); - - comparator(element: Model): number; - comparator(element: Model): string; - comparator(compare: Model, to?: Model): number; - - add(model: Model, options?: AddOptions); - add(models: Model[], options?: AddOptions); - at(index: number): Model; - get(id: any): Model; - getByCid(cid): Model; - create(attributes: any, options?: CreateOptions): Model; - pluck(attribute: string): any[]; - push(model: Model, options?: AddOptions); - pop(options?: Silenceable); - remove(model: Model, options?: Silenceable); - remove(models: Model[], options?: Silenceable); - reset(models?: Model[], options?: Silenceable); - shift(options?: Silenceable); - sort(options?: Silenceable); - unshift(model: Model, options?: AddOptions); - where(properies: any): Model[]; - - all(iterator: (element: Model, index: number) => bool, context?: any): bool; - any(iterator: (element: Model, index: number) => bool, context?: any): bool; - collect(iterator: (element: Model, index: number, context?: any) => any[], context?: any): any[]; - compact(): Model[]; - contains(value: any): bool; - countBy(iterator: (element: Model, index: number) => any): any[]; - countBy(attribute: string): any[]; - detect(iterator: (item: any) => bool, context?: any): any; // ??? - difference(...model: Model[]): Model[]; - drop(): Model; - drop(n: number): Model[]; - each(iterator: (element: Model, index: number, list?: any) => void, context?: any); - every(iterator: (element: Model, index: number) => bool, context?: any): bool; - filter(iterator: (element: Model, index: number) => bool, context?: any): Model[]; - find(iterator: (element: Model, index: number) => bool, context?: any): Model; - first(): Model; - first(n: number): Model[]; - flatten(shallow?: bool): Model[]; - foldl(iterator: (memo: any, element: Model, index: number) => any, initialMemo: any, context?: any): any; - forEach(iterator: (element: Model, index: number, list?: any) => void, context?: any); - include(value: any): bool; - indexOf(element: Model, isSorted?: bool): number; - initial(): Model; - initial(n: number): Model[]; - inject(iterator: (memo: any, element: Model, index: number) => any, initialMemo: any, context?: any): any; - intersection(...model: Model[]): Model[]; - isEmpty(object: any): bool; - invoke(methodName: string, arguments?: any[]); - last(): Model; - last(n: number): Model[]; - lastIndexOf(element: Model, fromIndex?: number): number; - map(iterator: (element: Model, index: number, context?: any) => any[], context?: any): any[]; - max(iterator?: (element: Model, index: number) => any, context?: any): Model; - min(iterator?: (element: Model, index: number) => any, context?: any): Model; - object(...values: any[]): any[]; - reduce(iterator: (memo: any, element: Model, index: number) => any, initialMemo: any, context?: any): any; - select(iterator: any, context?: any): any[]; - size(): number; - shuffle(): any[]; - some(iterator: (element: Model, index: number) => bool, context?: any): bool; - sortBy(iterator: (element: Model, index: number) => number, context?: any): Model[]; - sortBy(attribute: string, context?: any): Model[]; - sortedIndex(element: Model, iterator?: (element: Model, index: number) => number): number; - range(stop: number, step?: number); - range(start: number, stop: number, step?: number); - reduceRight(iterator: (memo: any, element: Model, index: number) => any, initialMemo: any, context?: any): any[]; - reject(iterator: (element: Model, index: number) => bool, context?: any): Model[]; - rest(): Model; - rest(n: number): Model[]; - tail(): Model; - tail(n: number): Model[]; - toArray(): any[]; - union(...model: Model[]): Model[]; - uniq(isSorted?: bool, iterator?: (element: Model, index: number) => bool): Model[]; - without(...values: any[]): Model[]; - zip(...model: Model[]): Model[]; - } - - export class Router extends Events { - - static extend(properties: any, classProperties?: any): any; // do not use, prefer TypeScript's extend functionality - - routes: any; - - constructor (options?: RouterOptions); - initialize (options?: RouterOptions); - route(route: string, name: string, callback?: (...parameter: any[]) => void); - navigate(fragment: string, options?: NavigateOptions); - } - - export var history: History; - export class History { - start(options?: HistoryOptions); - navigate(fragment: string, options: any); - pushSate(); - } - - export interface ViewOptions { - model?: Backbone.Model; - collection?: Backbone.Collection; - el?: Element; - id?: string; - className?: string; - tagName?: string; - attributes?: any[]; - } - - export class View extends Events { - - static extend(properties: any, classProperties?: any): any; // do not use, prefer TypeScript's extend functionality - - constructor (options?: ViewOptions); - - $(selector: string): any; - model: Model; - make(tagName: string, attrs?, opts?): View; - setElement(element: HTMLElement, delegate?: bool); - tagName: string; - events: any; - - el: HTMLElement; - $el; - setElement(element); - attributes; - $(selector); - render(); - remove(); - make(tagName, attributes?, content?); - //delegateEvents: any; - delegateEvents(events?: any): any; - undelegateEvents(); - } - - // SYNC - function sync(method, model, options?: JQueryAjaxSettings); - var emulateHTTP: bool; - var emulateJSONBackbone: bool; - - // Utility - function noConflict(): Backbone; - function setDomLibrary(jQueryNew); -} +// Type definitions for Backbone 0.9.10 +// Project: http://backbonejs.org/ +// Definitions by: Boris Yankov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +/// + +declare module Backbone { + + export interface AddOptions extends Silenceable { + at: number; + } + + export interface CreateOptions extends Silenceable { + wait: bool; + } + + export interface HistoryOptions extends Silenceable { + pushState?: bool; + root?: string; + } + + export interface NavigateOptions { + trigger: bool; + } + + export interface RouterOptions { + routes: any; + } + + export interface Silenceable { + silent?: bool; + } + + interface on { (eventName: string, callback: (...args: any[]) => void, context?: any): any; } + interface off { (eventName?: string, callback?: (...args: any[]) => void, context?: any): any; } + interface trigger { (eventName: string, ...args: any[]): any; } + interface bind { (eventName: string, callback: (...args: any[]) => void, context?: any): any; } + interface unbind { (eventName?: string, callback?: (...args: any[]) => void, context?: any): any; } + + declare class Events { + on(eventName: string, callback: (...args:any[]) => void, context?: any): any; + off(eventName?: string, callback?: (...args:any[]) => void, context?: any): any; + trigger(eventName: string, ...args: any[]): any; + bind(eventName: string, callback: (...args:any[]) => void, context?: any): any; + unbind(eventName?: string, callback?: (...args:any[]) => void, context?: any): any; + } + + export class ModelBase extends Events { + fetch(options?: JQueryAjaxSettings); + url: any; + parse(response); + toJSON(): any; + } + + export class Model extends ModelBase { + + static extend(properties: any, classProperties?: any): any; // do not use, prefer TypeScript's extend functionality + + attributes: any; + changed: any[]; + cid: string; + id: any; + idAttribute: string; + urlRoot() : string; + + constructor (attributes?: any, options?: any); + initialize(attributes?: any); + + get(attributeName: string): any; + set(attributeName: string, value: any, options?: Silenceable); + set(obj: any, options?: Silenceable); + + change(); + changedAttributes(attributes?: any): any[]; + clear(options?: Silenceable); + clone(): Model; + defaults(): any; + destroy(options?: JQueryAjaxSettings); + escape(attribute: string); + has(attribute: string): bool; + hasChanged(attribute?: string): bool; + isNew(): bool; + isValid(): string; + previous(attribute: string): any; + previousAttributes(): any[]; + save(attributes?: any, options?: JQueryAjaxSettings); + unset(attribute: string, options?: Silenceable); + validate(attributes: any): any; + } + + export class Collection extends ModelBase { + + static extend(properties: any, classProperties?: any): any; // do not use, prefer TypeScript's extend functionality + + model: Model; + models: any; + collection: Model; + length: number; + + constructor (models?: any, options?: any); + + comparator(element: Model): number; + comparator(element: Model): string; + comparator(compare: Model, to?: Model): number; + + add(model: Model, options?: AddOptions); + add(models: Model[], options?: AddOptions); + at(index: number): Model; + get(id: any): Model; + create(attributes: any, options?: CreateOptions): Model; + pluck(attribute: string): any[]; + push(model: Model, options?: AddOptions); + pop(options?: Silenceable); + remove(model: Model, options?: Silenceable); + remove(models: Model[], options?: Silenceable); + reset(models?: Model[], options?: Silenceable); + shift(options?: Silenceable); + sort(options?: Silenceable); + unshift(model: Model, options?: AddOptions); + where(properies: any): Model[]; + + all(iterator: (element: Model, index: number) => bool, context?: any): bool; + any(iterator: (element: Model, index: number) => bool, context?: any): bool; + collect(iterator: (element: Model, index: number, context?: any) => any[], context?: any): any[]; + compact(): Model[]; + contains(value: any): bool; + countBy(iterator: (element: Model, index: number) => any): any[]; + countBy(attribute: string): any[]; + detect(iterator: (item: any) => bool, context?: any): any; // ??? + difference(...model: Model[]): Model[]; + drop(): Model; + drop(n: number): Model[]; + each(iterator: (element: Model, index: number, list?: any) => void, context?: any); + every(iterator: (element: Model, index: number) => bool, context?: any): bool; + filter(iterator: (element: Model, index: number) => bool, context?: any): Model[]; + find(iterator: (element: Model, index: number) => bool, context?: any): Model; + first(): Model; + first(n: number): Model[]; + flatten(shallow?: bool): Model[]; + foldl(iterator: (memo: any, element: Model, index: number) => any, initialMemo: any, context?: any): any; + forEach(iterator: (element: Model, index: number, list?: any) => void, context?: any); + include(value: any): bool; + indexOf(element: Model, isSorted?: bool): number; + initial(): Model; + initial(n: number): Model[]; + inject(iterator: (memo: any, element: Model, index: number) => any, initialMemo: any, context?: any): any; + intersection(...model: Model[]): Model[]; + isEmpty(object: any): bool; + invoke(methodName: string, arguments?: any[]); + last(): Model; + last(n: number): Model[]; + lastIndexOf(element: Model, fromIndex?: number): number; + map(iterator: (element: Model, index: number, context?: any) => any[], context?: any): any[]; + max(iterator?: (element: Model, index: number) => any, context?: any): Model; + min(iterator?: (element: Model, index: number) => any, context?: any): Model; + object(...values: any[]): any[]; + reduce(iterator: (memo: any, element: Model, index: number) => any, initialMemo: any, context?: any): any; + select(iterator: any, context?: any): any[]; + size(): number; + shuffle(): any[]; + some(iterator: (element: Model, index: number) => bool, context?: any): bool; + sortBy(iterator: (element: Model, index: number) => number, context?: any): Model[]; + sortBy(attribute: string, context?: any): Model[]; + sortedIndex(element: Model, iterator?: (element: Model, index: number) => number): number; + range(stop: number, step?: number); + range(start: number, stop: number, step?: number); + reduceRight(iterator: (memo: any, element: Model, index: number) => any, initialMemo: any, context?: any): any[]; + reject(iterator: (element: Model, index: number) => bool, context?: any): Model[]; + rest(): Model; + rest(n: number): Model[]; + tail(): Model; + tail(n: number): Model[]; + toArray(): any[]; + union(...model: Model[]): Model[]; + uniq(isSorted?: bool, iterator?: (element: Model, index: number) => bool): Model[]; + without(...values: any[]): Model[]; + zip(...model: Model[]): Model[]; + } + + export class Router extends Events { + + static extend(properties: any, classProperties?: any): any; // do not use, prefer TypeScript's extend functionality + + routes: any; + + constructor (options?: RouterOptions); + initialize (options?: RouterOptions); + route(route: string, name: string, callback?: (...parameter: any[]) => void); + navigate(fragment: string, options?: NavigateOptions); + } + + export var history: History; + export class History { + start(options?: HistoryOptions); + navigate(fragment: string, options: any); + pushSate(); + getFragment(fragment?: string, forcePushState?: bool): string; + getHash(window?: Window): string; + } + + export interface ViewOptions { + model?: Backbone.Model; + collection?: Backbone.Collection; + el?: Element; + id?: string; + className?: string; + tagName?: string; + attributes?: any[]; + } + + export class View extends Events { + + static extend(properties: any, classProperties?: any): any; // do not use, prefer TypeScript's extend functionality + + constructor (options?: ViewOptions); + + $(selector: string): any; + model: Model; + make(tagName: string, attrs?, opts?): View; + setElement(element: HTMLElement, delegate?: bool); + tagName: string; + events: any; + + el: HTMLElement; + $el; + setElement(element); + attributes; + $(selector); + render(); + remove(); + make(tagName, attributes?, content?); + //delegateEvents: any; + delegateEvents(events?: any): any; + undelegateEvents(); + } + + // SYNC + function sync(method, model, options?: JQueryAjaxSettings); + var emulateHTTP: bool; + var emulateJSONBackbone: bool; + + // Utility + function noConflict(): Backbone; + function setDomLibrary(jQueryNew); +} diff --git a/bgiframe/typescript.bgiframe.d.ts b/bgiframe/typescript.bgiframe.d.ts new file mode 100644 index 0000000000..b0b77cf07c --- /dev/null +++ b/bgiframe/typescript.bgiframe.d.ts @@ -0,0 +1,33 @@ +// Type definitions for typescript.bgiframe 1.0 +// Project: https://github.com/sumegizoltan/BgiFrame +// Definitions by: Zoltan Sumegi +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/*! The plugin based on: + * + * bgiframe for IE6 + * https://github.com/brandonaaron/bgiframe + * + * Copyrights for the jQuery plugin: + * Copyright (c) 2013 Brandon Aaron (http://brandonaaron.net) + */ + +module BgiFrame { + interface ISettings { + top: string; + left: string; + width: string; + height: string; + opacity: bool; + src: string; + conditional: bool; + } + + interface IBgiframe { + s: ISettings; + createIframe(): HTMLElement; + fire(element: HTMLElement): void; + getIframe(element: HTMLElement): HTMLElement; + prop(n: any): string; + } +} \ No newline at end of file diff --git a/bootstrap-notify/bootstrap-notify.d.ts b/bootstrap-notify/bootstrap-notify.d.ts new file mode 100644 index 0000000000..e532ec19b9 --- /dev/null +++ b/bootstrap-notify/bootstrap-notify.d.ts @@ -0,0 +1,68 @@ +// Type definitions for bootstrap-notify +// Project: https://github.com/Nijikokun/bootstrap-notify +// Definitions by: Blake Niemyjski +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface NotifyOptions { + /** + Alert style, omit alert- from style name. + @param {string} type + */ + type?: string; + /** + Allow alert to be closable through a close icon. + @param {bool} closable + */ + closable?: bool; + /** + Alert transition, pretty sure only fade is supported, you can try others if you wish. + @param {string} transition + */ + transition?: string; + /** + Fade alert out after a certain delay (in ms) + @param {string} fadeOut + */ + fadeOut?: NotifyFadeOutSettings; + /** + Text to show on alert, you can use either html or text. HTML will override text. + @param {MessageOptions} message + */ + message?: MessageOptions; + /** + Called before alert closes. + @param {function} onClose + */ + onClose?: () => void; + /** + Called after alert closes. + @param {function} onClosed + */ + onClosed?: () => void; +} + +interface NotifyFadeOutSettings { + enabled?: bool; + delay?: number; +} + +interface MessageOptions { + html?: string; + text?: string; +} + +interface Notification { + show(); + hide(); +} + +interface JQuery { + /** + Creates a notification instance with default options. + @constructor + @param {NotifyOptions} options + */ + notify(options: NotifyOptions): Notification; +} \ No newline at end of file diff --git a/box2d/box2dweb.d.ts b/box2d/box2dweb.d.ts index 8df8d6c90a..1126379803 100644 --- a/box2d/box2dweb.d.ts +++ b/box2d/box2dweb.d.ts @@ -1,5 +1,5 @@ /** -* Box2DWeb-2.1.d.ts Copyright (c) 2012 Josh Baldwin http://github.com/jbaldwin/box2dweb.d.ts +* Box2DWeb-2.1.d.ts Copyright (c) 2012-2013 Josh Baldwin http://github.com/jbaldwin/box2dweb.d.ts * There are a few competing javascript Box2D ports. * This definitions file is for Box2dWeb.js -> * http://code.google.com/p/box2dweb/ @@ -36,7 +36,7 @@ module Box2D.Common { * Color for debug drawing. Each value has the range [0, 1]. **/ export class b2Color { - + /** * Red **/ @@ -60,20 +60,23 @@ module Box2D.Common { /** * Constructor - * @rr Red value - * @gg Green value - * @bb Blue value + * @param rr Red value + * @param gg Green value + * @param bb Blue value **/ - constructor (rr: number, gg: number, bb: number); + constructor(rr: number, gg: number, bb: number); /** * Sets the Color to new RGB values. - * @rr Red value - * @gg Green value - * @bb Blue value + * @param rr Red value + * @param gg Green value + * @param bb Blue value **/ public Set(rr: number, gg: number, bb: number): void; } +} + +module Box2D.Common { /** * Controls Box2D global settings. @@ -82,6 +85,7 @@ module Box2D.Common { /** * b2Assert is used internally to handle assertions. By default, calls are commented out to save performance, so they serve more as documentation than anything else. + * @param a Asset an expression is true. **/ public static b2Assert(a: bool): void; @@ -89,8 +93,8 @@ module Box2D.Common { * Friction mixing law. Feel free to customize this. * Friction values are usually set between 0 and 1. (0 = no friction, 1 = high friction) * By default this is `return Math.sqrt(friction1, friction2);` - * @friction1 Friction 1 to mix. - * @friction2 Friction 2 to mix. + * @param friction1 Friction 1 to mix. + * @param friction2 Friction 2 to mix. * @return The two frictions mixed as one value. **/ public static b2MixFriction(friction1: number, friction2: number): number; @@ -99,8 +103,8 @@ module Box2D.Common { * Restitution mixing law. Feel free to customize this. Restitution is used to make objects bounce. * Restitution values are usually set between 0 and 1. (0 = no bounce (inelastic), 1 = perfect bounce (perfectly elastic)) * By default this is `return Math.Max(restitution1, restitution2);` - * @restitution1 Restitution 1 to mix. - * @restitution2 Restitution 2 to mix. + * @param restitution1 Restitution 1 to mix. + * @param restitution2 Restitution 2 to mix. * @return The two restitutions mixed as one value. **/ public static b2MixRestitution(restitution1: number, restitution2: number): number; @@ -244,7 +248,7 @@ module Box2D.Common.Math { /** * Empty constructor **/ - constructor (); + constructor(); /** * Sets all internal matrix values to absolute values. @@ -253,7 +257,7 @@ module Box2D.Common.Math { /** * Adds the two 2x2 matricies together and stores the result in this matrix. - * @m 2x2 matrix to add. + * @param m 2x2 matrix to add. **/ public AddM(m: b2Mat22): void; @@ -267,19 +271,19 @@ module Box2D.Common.Math { * Creates a rotation 2x2 matrix from the given angle. * R(theta) = [ cos(theta) -sin(theta) ] * [ sin(theta) cos(theta) ] - * @angle Matrix angle (theta). + * @param angle Matrix angle (theta). * @return 2x2 matrix. **/ public static FromAngle(angle: number): b2Mat22; - + /** * Creates a 2x2 matrix from two columns. - * @c1 Column 1 vector. - * @c2 Column 2 vector. + * @param c1 Column 1 vector. + * @param c2 Column 2 vector. * @return 2x2 matrix. **/ public static FromVV(c1: b2Vec2, c2: b2Vec2): b2Mat22; - + /** * Gets the rotation matrix angle. * R(theta) = [ cos(theta) -sin(theta) ] @@ -290,7 +294,7 @@ module Box2D.Common.Math { /** * Compute the inverse of this matrix, such that inv(A) A = identity. - * @out Inverse matrix. + * @param out Inverse matrix. * @return Inverse matrix. **/ public GetInverse(out: b2Mat22): b2Mat22; @@ -299,10 +303,10 @@ module Box2D.Common.Math { * Sets the 2x2 rotation matrix from the given angle. * R(theta) = [ cos(theta) -sin(theta) ] * [ sin(theta) cos(theta) ] - * @angle Matrix angle (theta). + * @param angle Matrix angle (theta). **/ public Set(angle: number): void; - + /** * Sets the 2x2 matrix to identity. **/ @@ -310,14 +314,14 @@ module Box2D.Common.Math { /** * Sets the 2x2 matrix from a 2x2 matrix. - * @m 2x2 matrix values. + * @param m 2x2 matrix values. **/ public SetM(m: b2Mat22): void; /** * Sets the 2x2 matrix from 2 column vectors. - * @c1 Column 1 vector. - * @c2 Column 2 vector. + * @param c1 Column 1 vector. + * @param c2 Column 2 vector. **/ public SetVV(c1: b2Vec2, c2: b2Vec2): void; @@ -328,13 +332,16 @@ module Box2D.Common.Math { /** * TODO, has something to do with the determinant - * @out Solved vector - * @bX - * @bY + * @param out Solved vector + * @param bX + * @param bY * @return Solved vector **/ public Solve(out: b2Vec2, bX: number, bY: number): b2Vec2; } +} + +module Box2D.Common.Math { /** * A 3-by3 matrix. Stored in column-major order. @@ -358,15 +365,15 @@ module Box2D.Common.Math { /** * Constructor - * @c1 Column 1 - * @c2 Column 2 - * @c3 Column 3 + * @param c1 Column 1 + * @param c2 Column 2 + * @param c3 Column 3 **/ - constructor (c1: b2Vec3, c2: b2Vec3, c3: b2Vec3); + constructor(c1: b2Vec3, c2: b2Vec3, c3: b2Vec3); /** * Adds the two 3x3 matricies together and stores the result in this matrix. - * @m 3x3 matrix to add. + * @param m 3x3 matrix to add. **/ public AddM(m: b2Mat33): void; @@ -383,15 +390,15 @@ module Box2D.Common.Math { /** * Sets the 3x3 matrix from a 3x3 matrix. - * @m 3x3 matrix values. + * @param m 3x3 matrix values. **/ public SetM(m: b2Mat33): void; /** * Sets the 3x3 matrix from 3 column vectors. - * @c1 Column 1 vector. - * @c2 Column 2 vector. - * @c3 Column 2 vector. + * @param c1 Column 1 vector. + * @param c2 Column 2 vector. + * @param c3 Column 2 vector. **/ public SetVVV(c1: b2Vec3, c2: b2Vec3, c3: b2Vec3): void; @@ -402,23 +409,26 @@ module Box2D.Common.Math { /** * TODO, has something to do with the determinant - * @out Solved vector - * @bX - * @bY + * @param out Solved vector + * @param bX + * @param bY * @return Solved vector **/ public Solve22(out: b2Vec2, bX: number, bY: number): b2Vec2; /** * TODO, has something to do with the determinant - * @out Solved vector - * @bX - * @bY - * @bZ + * @param out Solved vector + * @param bX + * @param bY + * @param bZ * @return Solved vector **/ public Solve33(out: b2Vec3, bX: number, bY: number, bZ: number): b2Vec3; } +} + +module Box2D.Common.Math { /** * Math utility functions. @@ -427,241 +437,241 @@ module Box2D.Common.Math { /** * Determines if a number is valid. A number is valid if it is finite. - * @x Number to check for validity. + * @param x Number to check for validity. * @return True if x is valid, otherwise false. **/ public static IsValid(x: number): bool; /** * Dot product of two vector 2s. - * @a Vector 2 to use in dot product. - * @b Vector 2 to use in dot product. + * @param a Vector 2 to use in dot product. + * @param b Vector 2 to use in dot product. * @return Dot product of a and b. **/ public static Dot(a: b2Vec2, b: b2Vec2): number; /** * Cross product of two vector 2s. - * @a Vector 2 to use in cross product. - * @b Vector 2 to use in cross product. + * @param a Vector 2 to use in cross product. + * @param b Vector 2 to use in cross product. * @return Cross product of a and b. **/ public static CrossVV(a: b2Vec2, b: b2Vec2): number; /** * Cross product of vector 2 and s. - * @a Vector 2 to use in cross product. - * @s s value. + * @param a Vector 2 to use in cross product. + * @param s s value. * @return Cross product of a and s. **/ public static CrossVF(a: b2Vec2, s: number): b2Vec2; /** * Cross product of s and vector 2. - * @s s value. - * @a Vector 2 to use in cross product. + * @param s s value. + * @param a Vector 2 to use in cross product. * @return Cross product of s and a. **/ public static CrossFV(s: number, a: b2Vec2): b2Vec2; /** * Multiply matrix and vector. - * @A Matrix. - * @v Vector. + * @param A Matrix. + * @param v Vector. * @return Result. **/ public static MulMV(A: b2Mat22, v: b2Vec2): b2Vec2; /** * - * @A - * @v + * @param A + * @param v * @return **/ public static MulTMV(A: b2Mat22, v: b2Vec2): b2Vec2; /** * - * @T - * @v + * @param T + * @param v * @return **/ public static MulX(T: b2Transform, v: b2Vec2): b2Vec2; /** * - * @T - * @v + * @param T + * @param v * @return **/ public static MulXT(T: b2Transform, v: b2Vec2): b2Vec2; /** * Adds two vectors. - * @a First vector. - * @b Second vector. + * @param a First vector. + * @param b Second vector. * @return a + b. **/ public static AddVV(a: b2Vec2, b: b2Vec2): b2Vec2; /** * Subtracts two vectors. - * @a First vector. - * @b Second vector. + * @param a First vector. + * @param b Second vector. * @return a - b. **/ public static SubtractVV(a: b2Vec2, b: b2Vec2): b2Vec2; /** * Calculates the distance between two vectors. - * @a First vector. - * @b Second vector. + * @param a First vector. + * @param b Second vector. * @return Distance between a and b. **/ public static Distance(a: b2Vec2, b: b2Vec2): number; /** * Calculates the squared distance between two vectors. - * @a First vector. - * @b Second vector. + * @param a First vector. + * @param b Second vector. * @return dist^2 between a and b. **/ public static DistanceSquared(a: b2Vec2, b: b2Vec2): number; /** * - * @s - * @a + * @param s + * @param a * @return **/ public static MulFV(s: number, a: b2Vec2): b2Vec2; /** * - * @A - * @B + * @param A + * @param B * @return **/ public static AddMM(A: b2Mat22, B: b2Mat22): b2Mat22; /** * - * @A - * @B + * @param A + * @param B * @return **/ public static MulMM(A: b2Mat22, B: b2Mat22): b2Mat22; /** * - * @A - * @B + * @param A + * @param B * @return **/ public static MulTMM(A: b2Mat22, B: b2Mat22): b2Mat22; /** * Creates an ABS number. - * @a Number to ABS. + * @param a Number to ABS. * @return Absolute value of a. **/ public static Abs(a: number): number; /** * Creates an ABS vector. - * @a Vector to ABS all values. + * @param a Vector to ABS all values. * @return Vector with all positive values. **/ public static AbsV(a: b2Vec2): b2Vec2; /** * Creates an ABS matrix. - * @A Matrix to ABS all values. + * @param A Matrix to ABS all values. * @return Matrix with all positive values. **/ public static AbsM(A: b2Mat22): b2Mat22; /** * Determines the minimum number. - * @a First number. - * @b Second number. + * @param a First number. + * @param b Second number. * @return a or b depending on which is the minimum. **/ public static Min(a: number, b: number): number; /** * Determines the minimum vector. - * @a First vector. - * @b Second vector. + * @param a First vector. + * @param b Second vector. * @return a or b depending on which is the minimum. **/ public static MinV(a: b2Vec2, b: b2Vec2): b2Vec2; /** * Determines the max number. - * @a First number. - * @b Second number. + * @param a First number. + * @param b Second number. * @return a or b depending on which is the maximum. **/ public static Max(a: number, b: number): number; /** * Determines the max vector. - * @a First vector. - * @b Second vector. + * @param a First vector. + * @param b Second vector. * @return a or b depending on which is the maximum. **/ public static MaxV(a: b2Vec2, b: b2Vec2): b2Vec2; /** * Clamp a number to the range of low to high. - * @a Number to clamp. - * @low Low range. - * @high High range. + * @param a Number to clamp. + * @param low Low range. + * @param high High range. * @return Number a clamped to range of low to high. **/ public static Clamp(a: number, low: number, high: number): number; /** * Clamps a vector to the range of low to high. - * @a Vector to clamp. - * @low Low range. - * @high High range. + * @param a Vector to clamp. + * @param low Low range. + * @param high High range. * @return Vector a clamped to range of low to high. **/ public static ClampV(a: b2Vec2, low: b2Vec2, high: b2Vec2): b2Vec2; /** * Swaps a and b objects. - * @a a -> b. - * @b b -> a. + * @param a a -> b. + * @param b b -> a. **/ public static Swap(a: any, b: any): void; /** * Generates a random number. - * @return Random number. + * @param return Random number. **/ public static Random(): number; /** * Returns a random number between lo and hi. - * @lo Lowest random number. - * @hi Highest random number. + * @param lo Lowest random number. + * @param hi Highest random number. * @return Number between lo and hi. **/ public static RandomRange(lo: number, hi: number): number; /** * Calculates the next power of 2 after the given number. - * @x Number to start search for the next power of 2. + * @param x Number to start search for the next power of 2. * @return The next number that is a power of 2. **/ public static NextPowerOfTwo(x: number): number; /** * Check if a number is a power of 2. - * @x Number to check if it is a power of 2. + * @param x Number to check if it is a power of 2. * @return True if x is a power of 2, otherwise false. **/ public static IsPowerOfTwo(x: number): bool; @@ -681,6 +691,9 @@ module Box2D.Common.Math { **/ public static b2Transform_identity: b2Transform; } +} + +module Box2D.Common.Math { /** * This describes the motion of a body/shape for TOI computation. Shapes are defined with respect to the body origin, which may no coincide with the center of mass. However, to support dynamics we must interpolate the center of mass position. @@ -706,12 +719,12 @@ module Box2D.Common.Math { * Center world position. **/ public c0: b2Vec2; - + /** * Local center of mass position. **/ public localCenter: b2Vec2; - + /** * Time interval = [t0,1], where t0 is in [0,1]. **/ @@ -730,17 +743,20 @@ module Box2D.Common.Math { /** * Get the interpolated transform at a specific time. - * @xf Transform at specified time, this is an out parameter. - * @alpha Is a factor in [0,1], where 0 indicates t0. + * @param xf Transform at specified time, this is an out parameter. + * @param alpha Is a factor in [0,1], where 0 indicates t0. **/ public GetTransform(xf: b2Transform, alpha: number): void; /** * Sets the sweep from a sweep. - * @other Sweep values to copy from. + * @param other Sweep values to copy from. **/ public Set(other: b2Sweep): void; } +} + +module Box2D.Common.Math { /** * A transform contains translation and rotation. It is used to represent the position and orientation of rigid frames. @@ -759,10 +775,10 @@ module Box2D.Common.Math { /** * The default constructor does nothing (for performance). - * @pos Position - * @r Rotation + * @param pos Position + * @param r Rotation **/ - constructor (pos: b2Vec2, r: b2Mat22); + constructor(pos: b2Vec2, r: b2Mat22); /** * Calculate the angle that the rotation matrix represents. @@ -772,14 +788,14 @@ module Box2D.Common.Math { /** * Initialize using a position vector and rotation matrix. - * @pos Position - * @r Rotation + * @param pos Position + * @param r Rotation **/ public Initialize(pos: b2Vec2, r: b2Mat22): void; /** * Sets the transfrom from a transfrom. - * @x Transform to copy values from. + * @param x Transform to copy values from. **/ public Set(x: b2Transform): void; @@ -788,6 +804,9 @@ module Box2D.Common.Math { **/ public SetIdentity(): void; } +} + +module Box2D.Common.Math { /** * A 2D column vector. @@ -806,10 +825,10 @@ module Box2D.Common.Math { /** * Creates a new vector 2. - * @x x value, default = 0. - * @y y value, default = 0. + * @param x x value, default = 0. + * @param y y value, default = 0. **/ - constructor (x?: number, y?: number); + constructor(x?: number, y?: number); /** * Sets x and y to absolute values. @@ -818,7 +837,7 @@ module Box2D.Common.Math { /** * Adds the vector 2 to this vector 2. The result is stored in this vector 2. - * @v Vector 2 to add. + * @param v Vector 2 to add. **/ public Add(v: b2Vec2): void; @@ -830,13 +849,13 @@ module Box2D.Common.Math { /** * Cross F V - * @s + * @param s **/ public CrossFV(s: number): void; /** * Cross V F - * @s + * @param s **/ public CrossVF(s: number): void; @@ -866,38 +885,38 @@ module Box2D.Common.Math { /** * Creates a new vector 2 from the given values. - * @x x value. - * @y y value. + * @param x x value. + * @param y y value. **/ public static Make(x: number, y: number): b2Vec2; /** * Calculates which vector has the maximum values and sets this vector to those values. - * @b Vector 2 to compare for maximum values. + * @param b Vector 2 to compare for maximum values. **/ public MaxV(b: b2Vec2): void; /** * Calculates which vector has the minimum values and sets this vector to those values. - * @b Vector 2 to compare for minimum values. + * @param b Vector 2 to compare for minimum values. **/ public MinV(b: b2Vec2): void; /** * Matrix multiplication. Stores the result in this vector 2. - * @A Matrix to muliply by. + * @param A Matrix to muliply by. **/ public MulM(A: b2Mat22): void; /** * Vector multiplication. Stores the result in this vector 2. - * @a Value to multiple the vector's values by. + * @param a Value to multiple the vector's values by. **/ public Multiply(a: number): void; /** * Dot product multiplication. Stores the result in this vector 2. - * @A Matrix to multiply by. + * @param A Matrix to multiply by. **/ public MulTM(A: b2Mat22): void; @@ -914,14 +933,14 @@ module Box2D.Common.Math { /** * Sets the vector 2. - * @x x value, default is 0. - * @y y value, default is 0. + * @param x x value, default is 0. + * @param y y value, default is 0. **/ public Set(x?: number, y?: number): void; /** * Sets the vector 2 from a vector 2. - * @v Vector 2 to copy values from. + * @param v Vector 2 to copy values from. **/ public SetV(v: b2Vec2): void; @@ -932,10 +951,13 @@ module Box2D.Common.Math { /** * Subtracts the vector 2 from this vector 2. The result is stored in this vector 2. - * @v Vector 2 to subtract. + * @param v Vector 2 to subtract. **/ public Subtract(v: b2Vec2): void; } +} + +module Box2D.Common.Math { /** * A 2D column vector with 3 elements. @@ -959,15 +981,15 @@ module Box2D.Common.Math { /** * Construct using coordinates x,y,z. - * @x x value, default = 0. - * @y y value, default = 0. - * @z z value, default = 0. + * @param x x value, default = 0. + * @param y y value, default = 0. + * @param z z value, default = 0. **/ - constructor (x?: number, y?: number, z?: number); + constructor(x?: number, y?: number, z?: number); /** * Adds the vector 3 to this vector 3. The result is stored in this vector 3. - * @v Vector 3 to add. + * @param v Vector 3 to add. **/ public Add(v: b2Vec3): void; @@ -985,7 +1007,7 @@ module Box2D.Common.Math { /** * Vector multiplication. Stores the result in this vector 3. - * @a Value to multiple the vector's values by. + * @param a Value to multiple the vector's values by. **/ public Multiply(a: number): void; @@ -996,15 +1018,15 @@ module Box2D.Common.Math { /** * Sets the vector 3. - * @x x value, default is 0. - * @y y value, default is 0. - * @z z value, default is 0. + * @param x x value, default is 0. + * @param y y value, default is 0. + * @param z z value, default is 0. **/ public Set(x?: number, y?: number, z?: number): void; /** * Sets the vector 3 from a vector 3. - * @v Vector 3 to copy values from. + * @param v Vector 3 to copy values from. **/ public SetV(v: b2Vec3): void; @@ -1015,7 +1037,7 @@ module Box2D.Common.Math { /** * Subtracts the vector 3 from this vector 3. The result is stored in this vector 3. - * @v Vector 3 to subtract. + * @param v Vector 3 to subtract. **/ public Subtract(v: b2Vec3): void; } @@ -1040,22 +1062,22 @@ module Box2D.Collision { /** * Combines two AABBs into one with max values for upper bound and min values for lower bound. - * @aabb1 First AABB to combine. - * @aabb2 Second AABB to combine. + * @param aabb1 First AABB to combine. + * @param aabb2 Second AABB to combine. * @return New AABB with max values from aabb1 and aabb2. **/ public static Combine(aabb1: b2AABB, aabb2: b2AABB): b2AABB; /** * Combines two AABBs into one with max values for upper bound and min values for lower bound. The result is stored in this AABB. - * @aabb1 First AABB to combine. - * @aabb2 Second AABB to combine. + * @param aabb1 First AABB to combine. + * @param aabb2 Second AABB to combine. **/ public Combine(aabb1: b2AABB, aabb2: b2AABB): void; /** * Determines if an AABB is contained within this one. - * @aabb AABB to see if it is contained. + * @param aabb AABB to see if it is contained. * @return True if aabb is contained, otherwise false. **/ public Contains(aabb: b2AABB): bool; @@ -1080,19 +1102,22 @@ module Box2D.Collision { /** * Perform a precise raycast against this AABB. - * @output Ray cast output values. - * @input Ray cast input values. + * @param output Ray cast output values. + * @param input Ray cast input values. * @return True if the ray cast hits this AABB, otherwise false. **/ public RayCast(output: b2RayCastOutput, input: b2RayCastInput): bool; /** * Tests if another AABB overlaps this AABB. - * @other Other AABB to test for overlap. + * @param other Other AABB to test for overlap. * @return True if other overlaps this AABB, otherwise false. **/ public TestOverlap(other: b2AABB): bool; } +} + +module Box2D.Collision { /** * We use contact ids to facilitate warm starting. @@ -1122,10 +1147,13 @@ module Box2D.Collision { /** * Sets the Contact ID from a Contact ID. - * @id The Contact ID to copy values from. + * @param id The Contact ID to copy values from. **/ public Set(id: b2ContactID): void; } +} + +module Box2D.Collision { /** * This structure is used to report contact points. @@ -1136,7 +1164,7 @@ module Box2D.Collision { * The combined friction coefficient. **/ public friction: number; - + /** * The contact id identifies the features in contact. **/ @@ -1177,6 +1205,9 @@ module Box2D.Collision { **/ public velocity: b2Math.b2Vec2; } +} + +module Box2D.Collision { /** * Input for b2Distance. You have to option to use the shape radii in the computation. Even @@ -1208,12 +1239,15 @@ module Box2D.Collision { **/ public useRadii: bool; } +} + +module Box2D.Collision { /** * Output calculation for b2Distance. **/ export class b2DistanceOutput { - + /** * Calculated distance. **/ @@ -1234,12 +1268,15 @@ module Box2D.Collision { **/ public pointB: b2Math.b2Vec2; } +} + +module Box2D.Collision { /** * A distance proxy is used by the GJK algorithm. It encapsulates any shape. **/ export class b2DistanceProxy { - + /** * Count **/ @@ -1257,20 +1294,21 @@ module Box2D.Collision { /** * Get the supporting vertex index in the given direction. - * @d Direction to look for the supporting vertex. + * @param d Direction to look for the supporting vertex. * @return Supporting vertex index. **/ public GetSupport(d: b2Math.b2Vec2): number; /** * Get the supporting vertex in the given direction. - * @d Direction to look for the supporting vertex. + * @param d Direction to look for the supporting vertex. * @return Supporting vertex. **/ public GetSupportVertex(d: b2Math.b2Vec2): b2Math.b2Vec2; /** * Get a vertex by index. Used by b2Distance. + * @param index Vetex's index. * @return Vertex at the given index. **/ public GetVertex(index: number): b2Math.b2Vec2; @@ -1283,10 +1321,13 @@ module Box2D.Collision { /** * Initialize the proxy using the given shape. The shape must remain in scope while the proxy is in use. - * @shape Shape to initialize the distance proxy. + * @param shape Shape to initialize the distance proxy. **/ public Set(shape: Shapes.b2Shape): void; } +} + +module Box2D.Collision { /** * A dynamic tree arranges data in a binary tree to accelerate queries such as volume queries and ray casts. Leafs are proxies with an AABB. In the tree we expand the proxy AABB by b2_fatAABBFactor so that the proxy AABB is bigger than the client object. This allows the client object to move by small amounts without triggering a tree update. Nodes are pooled. @@ -1296,25 +1337,25 @@ module Box2D.Collision { /** * Constructing the tree initializes the node pool. **/ - constructor (); + constructor(); /** * Create a proxy. Provide a tight fitting AABB and a userData. - * @aabb AABB. - * @userDate User defined data for this proxy. + * @param aabb AABB. + * @param userDate User defined data for this proxy. * @return Dynamic tree node. **/ public CreateProxy(aabb: b2AABB, userData: any): b2DynamicTreeNode; /** * Destroy a proxy. This asserts if the id is invalid. - * @proxy Proxy to destroy. + * @param proxy Proxy to destroy. **/ public DestroyProxy(proxy: b2DynamicTreeNode): void; /** * Gets the Fat AABB for the proxy. - * @proxy Proxy to retrieve Fat AABB. + * @param proxy Proxy to retrieve Fat AABB. * @return Fat AABB for proxy. **/ public GetFatAABB(proxy: b2DynamicTreeNode): b2AABB; @@ -1322,43 +1363,46 @@ module Box2D.Collision { /** * Get user data from a proxy. Returns null if the proxy is invalid. * Cast to your type on return. - * @proxy Proxy to retrieve user data from. + * @param proxy Proxy to retrieve user data from. * @return User data for proxy or null if proxy is invalid. **/ public GetUserData(proxy: b2DynamicTreeNode): any; /** * Move a proxy with a swept AABB. If the proxy has moved outside of its fattened AABB, then the proxy is removed from the tree and re-inserted. Otherwise the function returns immediately. - * @proxy Proxy to move. - * @aabb Swept AABB. - * @displacement Extra AABB displacement. + * @param proxy Proxy to move. + * @param aabb Swept AABB. + * @param displacement Extra AABB displacement. **/ public MoveProxy(proxy: b2DynamicTreeNode, aabb: b2AABB, displacement: b2Math.b2Vec2): bool; /** * Query an AABB for overlapping proxies. The callback is called for each proxy that overlaps the supplied AABB. The callback should match function signature fuction callback(proxy:b2DynamicTreeNode):Boolean and should return false to trigger premature termination. - * @callback Called for each proxy that overlaps the supplied AABB. - * @proxy Proxy overlapping the supplied AABB. + * @param callback Called for each proxy that overlaps the supplied AABB. + * param proxy Proxy overlapping the supplied AABB. * @aabb Proxies are query for overlap on this AABB. **/ public Query(callback: (proxy: b2DynamicTreeNode) => bool, aabb: b2AABB): void; /** * Ray-cast against the proxies in the tree. This relies on the callback to perform a exact ray-cast in the case were the proxy contains a shape. The callback also performs the any collision filtering. This has performance roughly equal to k log(n), where k is the number of collisions and n is the number of proxies in the tree. - * @callback Called for each proxy that is hit by the ray. - * @input Ray cast input data. - * @proxy The proxy hit by the ray cast. - * @return Return value is the new value for maxFraction. - * @input Ray cast input data. Query all proxies along this ray cast. + * @param callback Called for each proxy that is hit by the ray. + * param input Ray cast input data. + * param proxy The proxy hit by the ray cast. + * return Return value is the new value for maxFraction. + * @param input Ray cast input data. Query all proxies along this ray cast. **/ public RayCast(callback: (input: b2RayCastInput, proxy: b2DynamicTreeNode) => number, input: b2RayCastInput): void; /** * Perform some iterations to re-balance the tree. - * @iterations Number of rebalance iterations to perform. + * @param iterations Number of rebalance iterations to perform. **/ public Rebalance(iterations: number): void; } +} + +module Box2D.Collision { /** * The broad-phase is used for computing pairs and performing volume queries and ray casts. This broad-phase does not persist pairs. Instead, this reports potentially new pairs. It is up to the client to consume the new pairs and to track subsequent overlap. @@ -1368,87 +1412,68 @@ module Box2D.Collision { /** * Creates the dynamic tree broad phase. **/ - constructor (); + constructor(); /** - * Create a proxy with an initial AABB. Pairs are not reported until UpdatePairs is called. - * @aabb Proxy Fat AABB. - * @userData User defined data. - * @return Proxy created from aabb and userData. + * @see IBroadPhase.CreateProxy **/ public CreateProxy(aabb: b2AABB, userData: any): b2DynamicTreeNode; /** - * Destroy a proxy. It is up to the client to remove any pairs. - * @proxy Proxy to destroy. + * @see IBroadPhase.DestroyProxy **/ public DestroyProxy(proxy: b2DynamicTreeNode): void; - + /** - * Get the Fat AABB for a proxy. - * @proxy Proxy to retrieve the Fat AABB. + * @see IBroadPhase.GetFatAABB **/ public GetFatAABB(proxy: b2DynamicTreeNode): b2AABB; /** - * Get the number of proxies. - * @return Number of proxies. + * @see IBroadPhase.GetProxyCount **/ public GetProxyCount(): number; /** - * Get user data from a proxy. Returns null if the proxy is invalid. - * @return Gets the user data from proxy, or null if the proxy is invalid. + * @see IBroadPhase.GetUserData **/ public GetUserData(proxy: b2DynamicTreeNode): any; /** - * Call MoveProxy as many times as you like, then when you are done call UpdatePairs to finalized the proxy pairs (for your time step). - * @proxy Proxy to move. - * @aabb Swept AABB. - * @displacement Extra AABB displacement. + * @see IBroadPhase.MoveProxy **/ public MoveProxy(proxy: b2DynamicTreeNode, aabb: b2AABB, displacement: b2Math.b2Vec2): void; /** - * Query an AABB for overlapping proxies. The callback is called for each proxy that overlaps the supplied AABB. The callback should match function signature fuction callback(proxy:b2DynamicTreeNode):Boolean and should return false to trigger premature termination. - * @callback Called for each proxy that overlaps the supplied AABB. - * @proxy Proxy overlapping the supplied AABB. - * @aabb Proxies are query for overlap on this AABB. + * @see IBroadPhase.Query **/ public Query(callback: (proxy: b2DynamicTreeNode) => bool, aabb: b2AABB): void; /** - * Ray-cast against the proxies in the tree. This relies on the callback to perform a exact ray-cast in the case were the proxy contains a shape. The callback also performs the any collision filtering. This has performance roughly equal to k log(n), where k is the number of collisions and n is the number of proxies in the tree. - * @callback Called for each proxy that is hit by the ray. - * @input Ray cast input data. - * @proxy The proxy hit by the ray cast. - * @return Return value is the new value for maxFraction. - * @input Ray cast input data. Query all proxies along this ray cast. + * @see IBroadPhase.RayCast **/ public RayCast(callback: (input: b2RayCastInput, proxy: b2DynamicTreeNode) => number, input: b2RayCastInput): void; /** - * Perform some iterations to re-balance the tree. - * @iterations Number of rebalance iterations to perform. + * @see IBroadPhase.Rebalance **/ public Rebalance(iterations: number): void; /** * Tests if two proxies overlap. - * @proxyA First proxy to test. - * @proxyB Second proxy to test. + * @param proxyA First proxy to test. + * @param proxyB Second proxy to test. * @return True if the proxyA and proxyB overlap with Fat AABBs, otherwise false. **/ public TestOverlap(proxyA: b2DynamicTreeNode, proxyB: b2DynamicTreeNode): bool; /** * Update the pairs. This results in pair callbacks. This can only add pairs. - * @callback Called for all new proxy pairs. - * @userDataA Proxy A in the pair user data. - * @userDataB Proxy B in the pair user data. + * @param callback Called for all new proxy pairs. + * param userDataA Proxy A in the pair user data. + * param userDataB Proxy B in the pair user data. **/ - public UpdatePairs(callback: (userDataA: any, userDataB: any) => void): void; + public UpdatePairs(callback: (userDataA: any, userDataB: any) => void ): void; /** * Validates the dynamic tree. @@ -1456,6 +1481,9 @@ module Box2D.Collision { **/ public Validate(): void; } +} + +module Box2D.Collision { /** * Empty declaration, used in many callbacks within b2DynamicTree. @@ -1464,6 +1492,9 @@ module Box2D.Collision { export class b2DynamicTreeNode { } +} + +module Box2D.Collision { /** * A manifold for two touching convex shapes. Box2D supports multiple types of contact: - clip point versus plane with radius - point versus point with radius (circles) The local point usage depends on the manifold type: -e_circles: the local center of circleA -e_faceA: the center of faceA -e_faceB: the center of faceB Similarly the local normal usage: -e_circles: not used -e_faceA: the normal on polygonA -e_faceB: the normal on polygonB We store contacts in this way so that position correction can account for movement, which is critical for continuous physics. All contact scenarios must be expressed in one of these types. This structure is stored across time steps, so we keep it small. @@ -1513,7 +1544,7 @@ module Box2D.Collision { /** * Creates a new manifold. **/ - constructor (); + constructor(); /** * Copies the manifold. @@ -1528,10 +1559,13 @@ module Box2D.Collision { /** * Sets this manifold from another manifold. - * @m Manifold to copy values from. + * @param m Manifold to copy values from. **/ public Set(m: b2Manifold): void; } +} + +module Box2D.Collision { /** * A manifold point is a contact point belonging to a contact manifold. It holds details related to the geometry and dynamics of the contact points. The local point usage depends on the manifold type: -e_circles: the local center of circleB -e_faceA: the local center of cirlceB or the clip point of polygonB -e_faceB: the clip point of polygonA This structure is stored across time steps, so we keep it small. Note: the impulses are used for internal caching and may not provide reliable contact forces, especially for high speed collisions. @@ -1547,7 +1581,7 @@ module Box2D.Collision { * Local contact point. **/ public m_localpoint: b2Math.b2Vec2; - + /** * Normal impluse for this contact point. **/ @@ -1561,7 +1595,7 @@ module Box2D.Collision { /** * Creates a new manifold point. **/ - constructor (); + constructor(); /** * Resets this manifold point. @@ -1570,10 +1604,13 @@ module Box2D.Collision { /** * Sets this manifold point from a manifold point. - * @m The manifold point to copy values from. + * @param m The manifold point to copy values from. **/ public Set(m: b2ManifoldPoint): void; } +} + +module Box2D.Collision { /** * An oriented bounding box. @@ -1595,6 +1632,9 @@ module Box2D.Collision { **/ public R: b2Math.b2Mat22; } +} + +module Box2D.Collision { /** * Ray cast input data. @@ -1615,15 +1655,18 @@ module Box2D.Collision { * The end point of the ray. **/ public p2: b2Math.b2Vec2; - + /** * Creates a new ray cast input. - * @p1 Start point of the ray, default = null. - * @p2 End point of the ray, default = null. - * @maxFraction Truncate the ray to reach up to this fraction from p1 to p2. + * @param p1 Start point of the ray, default = null. + * @param p2 End point of the ray, default = null. + * @param maxFraction Truncate the ray to reach up to this fraction from p1 to p2. **/ - constructor (p1?: b2Math.b2Vec2, p2?: b2Math.b2Vec2, maxFraction?: number); + constructor(p1?: b2Math.b2Vec2, p2?: b2Math.b2Vec2, maxFraction?: number); } +} + +module Box2D.Collision { /** * Results of a ray cast. @@ -1640,6 +1683,9 @@ module Box2D.Collision { **/ public normal: b2Math.b2Vec2; } +} + +module Box2D.Collision { /** * A line in space between two given vertices. @@ -1658,27 +1704,27 @@ module Box2D.Collision { /** * Extends or clips the segment so that it's ends lie on the boundary of the AABB. - * @aabb AABB to extend/clip the segement. + * @param aabb AABB to extend/clip the segement. **/ public Extend(aabb: b2AABB): void; /** * See Extend, this works on the ending point. - * @aabb AABB to extend/clip the ending point. + * @param aabb AABB to extend/clip the ending point. **/ public ExtendBackward(aabb: b2AABB): void; /** * See Extend, this works on the starting point. - * @aabb AABB to extend/clip the starting point. + * @param aabb AABB to extend/clip the starting point. **/ public ExtendForward(aabb: b2AABB): void; /** * Ray cast against this segment with another segment. - * @lambda returns the hit fraction. You can use this to compute the contact point * p = (1 - lambda) * segment.p1 + lambda * segment.p2 * @normal Normal at the contact point. If there is no intersection, the normal is not set. - * @segment Defines the begining and end point of the ray cast. - * @maxLambda a number typically in the range [0,1]. + * @param lambda returns the hit fraction. You can use this to compute the contact point * p = (1 - lambda) * segment.p1 + lambda * segment.p2 * @normal Normal at the contact point. If there is no intersection, the normal is not set. + * @param segment Defines the begining and end point of the ray cast. + * @param maxLambda a number typically in the range [0,1]. * @return True if there is an intersection, otherwise false. **/ public TestSegment( @@ -1687,6 +1733,9 @@ module Box2D.Collision { segment: b2Segment, maxLambda: number): bool; } +} + +module Box2D.Collision { /** * Used to warm start b2Distance. Set count to zero on first call. @@ -1713,6 +1762,9 @@ module Box2D.Collision { **/ public metric: number; } +} + +module Box2D.Collision { /** * Inpute parameters for b2TimeOfImpact @@ -1744,6 +1796,9 @@ module Box2D.Collision { **/ public tolerance: number; } +} + +module Box2D.Collision { /** * This is used to compute the current state of a contact manifold. @@ -1763,15 +1818,15 @@ module Box2D.Collision { /** * Creates a new b2WorldManifold. **/ - constructor (); + constructor(); /** * Evaluate the manifold with supplied transforms. This assumes modest motion from the original state. This does not change the point count, impulses, etc. The radii must come from the shapes that generated the manifold. - * @manifold Manifold to evaluate. - * @xfA A transform. - * @radiusA A radius. - * @xfB B transform. - * @radiusB B radius. + * @param manifold Manifold to evaluate. + * @param xfA A transform. + * @param radiusA A radius. + * @param xfB B transform. + * @param radiusB B radius. **/ public Initialize( manifold: b2Manifold, @@ -1780,6 +1835,9 @@ module Box2D.Collision { xfB: b2Math.b2Transform, radiusB: number): void; } +} + +module Box2D.Collision { /** * We use contact ids to facilitate warm starting. @@ -1806,29 +1864,32 @@ module Box2D.Collision { **/ public referenceEdge: number; } +} + +module Box2D.Collision { /** * Interface for objects tracking overlap of many AABBs. **/ export interface IBroadPhase { - + /** * Create a proxy with an initial AABB. Pairs are not reported until UpdatePairs is called. - * @aabb Proxy Fat AABB. - * @userData User defined data. + * @param aabb Proxy Fat AABB. + * @param userData User defined data. * @return Proxy created from aabb and userData. **/ CreateProxy(aabb: b2AABB, userData: any): b2DynamicTreeNode; /** * Destroy a proxy. It is up to the client to remove any pairs. - * @proxy Proxy to destroy. + * @param proxy Proxy to destroy. **/ DestroyProxy(proxy: b2DynamicTreeNode): void; /** * Get the Fat AABB for a proxy. - * @proxy Proxy to retrieve the Fat AABB. + * @param proxy Proxy to retrieve the Fat AABB. **/ GetFatAABB(proxy: b2DynamicTreeNode): b2AABB; @@ -1840,39 +1901,40 @@ module Box2D.Collision { /** * Get user data from a proxy. Returns null if the proxy is invalid. + * @param proxy Proxy to retrieve user data from. * @return Gets the user data from proxy, or null if the proxy is invalid. **/ GetUserData(proxy: b2DynamicTreeNode): any; /** * Call MoveProxy as many times as you like, then when you are done call UpdatePairs to finalized the proxy pairs (for your time step). - * @proxy Proxy to move. - * @aabb Swept AABB. - * @displacement Extra AABB displacement. + * @param proxy Proxy to move. + * @param aabb Swept AABB. + * @param displacement Extra AABB displacement. **/ MoveProxy(proxy: b2DynamicTreeNode, aabb: b2AABB, displacement: b2Math.b2Vec2): void; - + /** * Query an AABB for overlapping proxies. The callback is called for each proxy that overlaps the supplied AABB. The callback should match function signature fuction callback(proxy:b2DynamicTreeNode):Boolean and should return false to trigger premature termination. - * @callback Called for each proxy that overlaps the supplied AABB. - * @proxy Proxy overlapping the supplied AABB. - * @aabb Proxies are query for overlap on this AABB. + * @param callback Called for each proxy that overlaps the supplied AABB. + * param proxy Proxy overlapping the supplied AABB. + * @param aabb Proxies are query for overlap on this AABB. **/ Query(callback: (proxy: b2DynamicTreeNode) => bool, aabb: b2AABB): void; /** * Ray-cast against the proxies in the tree. This relies on the callback to perform a exact ray-cast in the case were the proxy contains a shape. The callback also performs the any collision filtering. This has performance roughly equal to k log(n), where k is the number of collisions and n is the number of proxies in the tree. - * @callback Called for each proxy that is hit by the ray. - * @input Ray cast input data. - * @proxy The proxy hit by the ray cast. - * @return Return value is the new value for maxFraction. - * @input Ray cast input data. Query all proxies along this ray cast. + * @param callback Called for each proxy that is hit by the ray. + * param input Ray cast input data. + * param proxy The proxy hit by the ray cast. + * param return Return value is the new value for maxFraction. + * @param input Ray cast input data. Query all proxies along this ray cast. **/ RayCast(callback: (input: b2RayCastInput, proxy: b2DynamicTreeNode) => number, input: b2RayCastInput): void; /** * Perform some iterations to re-balance the tree. - * @iterations Number of rebalance iterations to perform. + * @param iterations Number of rebalance iterations to perform. **/ Rebalance(iterations: number): void; } @@ -1887,28 +1949,30 @@ module Box2D.Collision.Shapes { /** * Creates a new circle shape. + * @param radius Circle radius. **/ - constructor (radius?:number); + constructor(radius?: number); /** * Given a transform, compute the associated axis aligned bounding box for this shape. - * @aabb Calculated AABB, this argument is `out`. - * @xf Transform to calculate the AABB. + * @param aabb Calculated AABB, this argument is `out`. + * @param xf Transform to calculate the AABB. **/ public ComputeAABB(aabb: b2AABB, xf: b2Math.b2Transform): void; /** * Compute the mass properties of this shape using its dimensions and density. The inertia tensor is computed about the local origin, not the centroid. - * @massData Calculate the mass, this argument is `out`. + * @param massData Calculate the mass, this argument is `out`. + * @param density **/ public ComputeMass(massData: b2MassData, density: number): void; /** * Compute the volume and centroid of this shape intersected with a half plane - * @normal The surface normal. - * @offset The surface offset along the normal. - * @xf The shape transform. - * @c The centroid, this argument is `out`. + * @param normal The surface normal. + * @param offset The surface offset along the normal. + * @param xf The shape transform. + * @param c The centroid, this argument is `out`. **/ public ComputeSubmergedArea( normal: b2Math.b2Vec2, @@ -1936,9 +2000,9 @@ module Box2D.Collision.Shapes { /** * Cast a ray against this shape. - * @output Ray cast results, this argument is `out`. - * @input Ray cast input parameters. - * @transform The transform to be applied to the shape. + * @param output Ray cast results, this argument is `out`. + * @param input Ray cast input parameters. + * @param transform The transform to be applied to the shape. * @return True if the ray hits the shape, otherwise false. **/ public RayCast( @@ -1948,30 +2012,33 @@ module Box2D.Collision.Shapes { /** * Set the circle shape values from another shape. - * @other The other circle shape to copy values from. + * @param other The other circle shape to copy values from. **/ public Set(other: b2CircleShape): void; /** * Set the local position of this circle in its parent body. - * @position The new local position of this circle. + * @param position The new local position of this circle. **/ public SetLocalPosition(position: b2Math.b2Vec2): void; /** * Set the radius of the circle. - * @radius The new radius of the circle. + * @param radius The new radius of the circle. **/ public SetRadius(radius: number): void; - + /** * Test a point for containment in this shape. This only works for convex shapes. - * @xf Shape world transform. - * @p Point to test against, in world coordinates. + * @param xf Shape world transform. + * @param p Point to test against, in world coordinates. * @return True if the point is in this shape, otherwise false. **/ public TestPoint(xf: b2Math.b2Transform, p: b2Math.b2Vec2): bool; } +} + +module Box2D.Collision.Shapes { /** * This structure is used to build edge shapes. @@ -1996,8 +2063,11 @@ module Box2D.Collision.Shapes { /** * Creates a new edge chain def. **/ - constructor (); + constructor(); } +} + +module Box2D.Collision.Shapes { /** * An edge shape. @@ -2006,28 +2076,30 @@ module Box2D.Collision.Shapes { /** * Creates a new edge shape. + * @param v1 First vertex + * @param v2 Second vertex **/ - constructor (v1: b2Math.b2Vec2, v2: b2Math.b2Vec2); + constructor(v1: b2Math.b2Vec2, v2: b2Math.b2Vec2); /** * Given a transform, compute the associated axis aligned bounding box for this shape. - * @aabb Calculated AABB, this argument is `out`. - * @xf Transform to calculate the AABB. + * @param aabb Calculated AABB, this argument is `out`. + * @param xf Transform to calculate the AABB. **/ public ComputeAABB(aabb: b2AABB, xf: b2Math.b2Transform): void; /** * Compute the mass properties of this shape using its dimensions and density. The inertia tensor is computed about the local origin, not the centroid. - * @massData Calculate the mass, this argument is `out`. + * @param massData Calculate the mass, this argument is `out`. **/ public ComputeMass(massData: b2MassData, density: number): void; /** * Compute the volume and centroid of this shape intersected with a half plane - * @normal The surface normal. - * @offset The surface offset along the normal. - * @xf The shape transform. - * @c The centroid, this argument is `out`. + * @param normal The surface normal. + * @param offset The surface offset along the normal. + * @param xf The shape transform. + * @param c The centroid, this argument is `out`. **/ public ComputeSubmergedArea( normal: b2Math.b2Vec2, @@ -2103,6 +2175,7 @@ module Box2D.Collision.Shapes { /** * Get the first vertex and apply the supplied transform. + * @param xf Transform to apply. * @return First vertex with xf transform applied. **/ public GetFirstVertex(xf: b2Math.b2Transform): b2Math.b2Vec2; @@ -2121,18 +2194,18 @@ module Box2D.Collision.Shapes { /** * Get the support point in the given world direction with the supplied transform. - * @xf Transform to apply. - * @dX X world direction. - * @dY Y world direction. + * @param xf Transform to apply. + * @param dX X world direction. + * @param dY Y world direction. * @return Support point. **/ public Support(xf: b2Math.b2Transform, dX: number, dY: number): b2Math.b2Vec2; /** * Cast a ray against this shape. - * @output Ray cast results, this argument is `out`. - * @input Ray cast input parameters. - * @transform The transform to be applied to the shape. + * @param output Ray cast results, this argument is `out`. + * @param input Ray cast input parameters. + * @param transform The transform to be applied to the shape. * @return True if the ray hits the shape, otherwise false. **/ public RayCast( @@ -2142,12 +2215,15 @@ module Box2D.Collision.Shapes { /** * Test a point for containment in this shape. This only works for convex shapes. - * @xf Shape world transform. - * @p Point to test against, in world coordinates. + * @param xf Shape world transform. + * @param p Point to test against, in world coordinates. * @return True if the point is in this shape, otherwise false. **/ public TestPoint(xf: b2Math.b2Transform, p: b2Math.b2Vec2): bool; } +} + +module Box2D.Collision.Shapes { /** * This holds the mass data computed for a shape. @@ -2169,73 +2245,76 @@ module Box2D.Collision.Shapes { **/ public mass: number; } +} + +module Box2D.Collision.Shapes { /** * Convex polygon. The vertices must be in CCW order for a right-handed coordinate system with the z-axis coming out of the screen. **/ export class b2PolygonShape extends b2Shape { - + /** * Creates a b2PolygonShape from a vertices list. This assumes the vertices define a convex polygon. It is assumed that the exterior is the the right of each edge. - * @vertices List of vertices to create the polygon shape from. - * @vertexCount Number of vertices in the shape, default value is 0 and in the box2dweb.js code it is ignored. + * @param vertices List of vertices to create the polygon shape from. + * @param vertexCount Number of vertices in the shape, default value is 0 and in the box2dweb.js code it is ignored. * @return Convex polygon shape. **/ public static AsArray(vertices: b2Math.b2Vec2[], vertexCount?: number): b2PolygonShape; /** * Build vertices to represent an axis-aligned box. - * @hx The half-width. - * @hy The half-height. + * @param hx The half-width. + * @param hy The half-height. * @return Box polygon shape. **/ public static AsBox(hx: number, hy: number): b2PolygonShape; /** * Creates a single edge from two vertices. - * @v1 First vertex. - * @v2 Second vertex. + * @param v1 First vertex. + * @param v2 Second vertex. * @return Edge polygon shape. **/ public static AsEdge(v1: b2Math.b2Vec2, b2: b2Math.b2Vec2): b2PolygonShape; /** * Build vertices to represent an oriented box. - * @hx The half-width. - * @hy The half-height. - * @center The center of the box in local coordinates, default is null (no center?) - * @angle The rotation of the box in local coordinates, default is 0.0. + * @param hx The half-width. + * @param hy The half-height. + * @param center The center of the box in local coordinates, default is null (no center?) + * @param angle The rotation of the box in local coordinates, default is 0.0. * @return Oriented box shape. **/ public static AsOrientedBox(hx: number, hy: number, center?: b2Math.b2Vec2, angle?: number): b2PolygonShape; /** * This assumes the vertices define a convex polygon. It is assumed that the exterior is the the right of each edge. - * @vertices List of vertices to create the polygon shape from. - * @vertexCount The number of vertices, default is 0 and in the box2dweb.js code it is ignored. + * @param vertices List of vertices to create the polygon shape from. + * @param vertexCount The number of vertices, default is 0 and in the box2dweb.js code it is ignored. * @return Convex polygon shape. **/ public static AsVector(vertices: b2Math.b2Vec2[], vertexCount?: number): b2PolygonShape; /** * Given a transform, compute the associated axis aligned bounding box for this shape. - * @aabb Calculated AABB, this argument is `out`. - * @xf Transform to calculate the AABB. + * @param aabb Calculated AABB, this argument is `out`. + * @param xf Transform to calculate the AABB. **/ public ComputeAABB(aabb: b2AABB, xf: b2Math.b2Transform): void; /** * Compute the mass properties of this shape using its dimensions and density. The inertia tensor is computed about the local origin, not the centroid. - * @massData Calculate the mass, this argument is `out`. + * @param massData Calculate the mass, this argument is `out`. **/ public ComputeMass(massData: b2MassData, density: number): void; /** * Compute the volume and centroid of this shape intersected with a half plane - * @normal The surface normal. - * @offset The surface offset along the normal. - * @xf The shape transform. - * @c The centroid, this argument is `out`. + * @param normal The surface normal. + * @param offset The surface offset along the normal. + * @param xf The shape transform. + * @param c The centroid, this argument is `out`. **/ public ComputeSubmergedArea( normal: b2Math.b2Vec2, @@ -2256,14 +2335,14 @@ module Box2D.Collision.Shapes { /** * Get the supporting vertex index in the given direction. - * @d Direction to look. + * @param d Direction to look. * @return Vertex index supporting the direction. **/ public GetSupport(d: b2Math.b2Vec2): number; /** * Get the supporting vertex in the given direction. - * @d Direciton to look. + * @param d Direciton to look. * @return Vertex supporting the direction. **/ public GetSupportVertex(d: b2Math.b2Vec2): b2Math.b2Vec2; @@ -2282,71 +2361,75 @@ module Box2D.Collision.Shapes { /** * Cast a ray against this shape. - * @output Ray cast results, this argument is `out`. - * @input Ray cast input parameters. - * @transform The transform to be applied to the shape. + * @param output Ray cast results, this argument is `out`. + * @param input Ray cast input parameters. + * @param transform The transform to be applied to the shape. * @return True if the ray hits the shape, otherwise false. **/ - public RayCast(output: b2RayCastOutput, + public RayCast( + output: b2RayCastOutput, input: b2RayCastInput, transform: b2Math.b2Transform): bool; /** * Set the shape values from another shape. - * @other The other shape to copy values from. + * @param other The other shape to copy values from. **/ public Set(other: b2Shape): void; /** * Copy vertices. This assumes the vertices define a convex polygon. It is assumed that the exterior is the the right of each edge. - * @vertices List of vertices to create the polygon shape from. - * @vertexCount Number of vertices in the shape, default value is 0 and in the box2dweb.js code it is ignored. + * @param vertices List of vertices to create the polygon shape from. + * @param vertexCount Number of vertices in the shape, default value is 0 and in the box2dweb.js code it is ignored. * @return Convex polygon shape. **/ public SetAsArray(vertices: b2Math.b2Vec2[], vertexCount?: number): void; /** * Build vertices to represent an axis-aligned box. - * @hx The half-width. - * @hy The half-height. + * @param hx The half-width. + * @param hy The half-height. * @return Box polygon shape. **/ public SetAsBox(hx: number, hy: number): void; /** * Creates a single edge from two vertices. - * @v1 First vertex. - * @v2 Second vertex. + * @param v1 First vertex. + * @param v2 Second vertex. * @return Edge polygon shape. **/ public SetAsEdge(v1: b2Math.b2Vec2, b2: b2Math.b2Vec2): void; /** * Build vertices to represent an oriented box. - * @hx The half-width. - * @hy The half-height. - * @center The center of the box in local coordinates, default is null (no center?) - * @angle The rotation of the box in local coordinates, default is 0.0. + * @param hx The half-width. + * @param hy The half-height. + * @param center The center of the box in local coordinates, default is null (no center?) + * @param angle The rotation of the box in local coordinates, default is 0.0. * @return Oriented box shape. **/ public SetAsOrientedBox(hx: number, hy: number, center?: b2Math.b2Vec2, angle?: number): void; /** * This assumes the vertices define a convex polygon. It is assumed that the exterior is the the right of each edge. - * @vertices List of vertices to create the polygon shape from. - * @vertexCount The number of vertices, default is 0 and in the box2dweb.js code it is ignored. + * @param vertices List of vertices to create the polygon shape from. + * @param vertexCount The number of vertices, default is 0 and in the box2dweb.js code it is ignored. * @return Convex polygon shape. **/ public SetAsVector(vertices: any[], vertexCount?: number): void; /** * Test a point for containment in this shape. This only works for convex shapes. - * @xf Shape world transform. - * @p Point to test against, in world coordinates. + * @param xf Shape world transform. + * @param p Point to test against, in world coordinates. * @return True if the point is in this shape, otherwise false. **/ public TestPoint(xf: b2Math.b2Transform, p: b2Math.b2Vec2): bool; } +} + +module Box2D.Collision.Shapes { /** * A shape is used for collision detection. Shapes are created in b2Body. You can use shape for collision detection before they are attached to the world. @@ -2379,27 +2462,28 @@ module Box2D.Collision.Shapes { /** * Creates a new b2Shape. **/ - constructor (); + constructor(); /** * Given a transform, compute the associated axis aligned bounding box for this shape. - * @aabb Calculated AABB, this argument is `out`. - * @xf Transform to calculate the AABB. + * @param aabb Calculated AABB, this argument is `out`. + * @param xf Transform to calculate the AABB. **/ public ComputeAABB(aabb: b2AABB, xf: b2Math.b2Transform): void; /** * Compute the mass properties of this shape using its dimensions and density. The inertia tensor is computed about the local origin, not the centroid. - * @massData Calculate the mass, this argument is `out`. + * @param massData Calculate the mass, this argument is `out`. + * @param density Density. **/ public ComputeMass(massData: b2MassData, density: number): void; /** * Compute the volume and centroid of this shape intersected with a half plane - * @normal The surface normal. - * @offset The surface offset along the normal. - * @xf The shape transform. - * @c The centroid, this argument is `out`. + * @param normal The surface normal. + * @param offset The surface offset along the normal. + * @param xf The shape transform. + * @param c The centroid, this argument is `out`. **/ public ComputeSubmergedArea( normal: b2Math.b2Vec2, @@ -2419,10 +2503,10 @@ module Box2D.Collision.Shapes { /** * Cast a ray against this shape. - * @output Ray cast results, this argument is `out`. - * @input Ray cast input parameters. - * @transform The transform to be applied to the shape. - * @return True if the ray hits the shape, otherwise false. + * @param output Ray cast results, this argument is `out`. + * @param input Ray cast input parameters. + * @param transform The transform to be applied to the shape. + * @param return True if the ray hits the shape, otherwise false. **/ public RayCast( output: b2RayCastOutput, @@ -2431,16 +2515,16 @@ module Box2D.Collision.Shapes { /** * Set the shape values from another shape. - * @other The other shape to copy values from. + * @param other The other shape to copy values from. **/ public Set(other: b2Shape): void; /** * Test if two shapes overlap with the applied transforms. - * @shape1 shape to test for overlap with shape2. - * @transform1 shape1 transform to apply. - * @shape2 shape to test for overlap with shape1. - * @transform2 shape2 transform to apply. + * @param shape1 shape to test for overlap with shape2. + * @param transform1 shape1 transform to apply. + * @param shape2 shape to test for overlap with shape1. + * @param transform2 shape2 transform to apply. * @return True if shape1 and shape2 overlap, otherwise false. **/ public static TestOverlap( @@ -2451,8 +2535,8 @@ module Box2D.Collision.Shapes { /** * Test a point for containment in this shape. This only works for convex shapes. - * @xf Shape world transform. - * @p Point to test against, in world coordinates. + * @param xf Shape world transform. + * @param p Point to test against, in world coordinates. * @return True if the point is in this shape, otherwise false. **/ public TestPoint(xf: b2Math.b2Transform, p: b2Math.b2Vec2): bool; @@ -2483,28 +2567,28 @@ module Box2D.Dynamics { /** * Apply a force at a world point. If the force is not applied at the center of mass, it will generate a torque and affect the angular velocity. This wakes up the body. - * @force The world force vector, usually in Newtons (N). - * @point The world position of the point of application. + * @param force The world force vector, usually in Newtons (N). + * @param point The world position of the point of application. **/ public ApplyForce(force: b2Math.b2Vec2, point: b2Math.b2Vec2): void; /** * Apply an impulse at a point. This immediately modifies the velocity. It also modifies the angular velocity if the point of application is not at the center of mass. This wakes up the body. - * @impules The world impulse vector, usually in N-seconds or kg-m/s. - * @point The world position of the point of application. + * @param impules The world impulse vector, usually in N-seconds or kg-m/s. + * @param point The world position of the point of application. **/ public ApplyImpulse(impulse: b2Math.b2Vec2, point: b2Math.b2Vec2): void; /** * Apply a torque. This affects the angular velocity without affecting the linear velocity of the center of mass. This wakes up the body. - * @torque Force applied about the z-axis (out of the screen), usually in N-m. + * @param torque Force applied about the z-axis (out of the screen), usually in N-m. **/ public ApplyTorque(torque: number): void; /** * Creates a fixture and attach it to this body. Use this function if you need to set some fixture parameters, like friction. Otherwise you can create the fixture directly from a shape. If the density is non-zero, this function automatically updates the mass of the body. Contacts are not created until the next time step. * @warning This function is locked during callbacks. - * @def The fixture definition; + * @param def The fixture definition; * @return The created fixture. **/ public CreateFixture(def: b2FixtureDef): b2Fixture; @@ -2512,8 +2596,8 @@ module Box2D.Dynamics { /** * Creates a fixture from a shape and attach it to this body. This is a convenience function. Use b2FixtureDef if you need to set parameters like friction, restitution, user data, or filtering. This function automatically updates the mass of the body. * @warning This function is locked during callbacks. - * @shape The shaped of the fixture (to be cloned). - * @density The shape density, default is 0.0, set to zero for static bodies. + * @param shape The shaped of the fixture (to be cloned). + * @param density The shape density, default is 0.0, set to zero for static bodies. * @return The created fixture. **/ public CreateFixture2(shape: b2Shapes.b2Shape, density?: number): b2Fixture; @@ -2521,7 +2605,7 @@ module Box2D.Dynamics { /** * Destroy a fixture. This removes the fixture from the broad-phase and destroys all contacts associated with this fixture. This will automatically adjust the mass of the body if the body is dynamic and the fixture has positive density. All fixtures attached to a body are implicitly destroyed when the body is destroyed. * @warning This function is locked during callbacks. - * @fixture The fixed to be removed. + * @param fixture The fixed to be removed. **/ public DestroyFixture(fixture: b2Fixture): void; @@ -2594,14 +2678,14 @@ module Box2D.Dynamics { /** * Get the world velocity of a local point. - * @localPoint Point in local coordinates. + * @param localPoint Point in local coordinates. * @return The world velocity of the point. **/ public GetLinearVelocityFromLocalPoint(localPoint: b2Math.b2Vec2): b2Math.b2Vec2; /** * Get the world linear velocity of a world point attached to this body. - * @worldPoint Point in world coordinates. + * @param worldPoint Point in world coordinates. * @return The world velocity of the point. **/ public GetLinearVelocityFromWorldPoint(worldPoint: b2Math.b2Vec2): b2Math.b2Vec2; @@ -2614,14 +2698,14 @@ module Box2D.Dynamics { /** * Gets a local point relative to the body's origin given a world point. - * @worldPoint Pointin world coordinates. + * @param worldPoint Pointin world coordinates. * @return The corresponding local point relative to the body's origin. **/ public GetLocalPoint(worldPoint: b2Math.b2Vec2): b2Math.b2Vec2; /** * Gets a local vector given a world vector. - * @worldVector World vector. + * @param worldVector World vector. * @return The corresponding local vector. **/ public GetLocalVector(worldVector: b2Math.b2Vec2): b2Math.b2Vec2; @@ -2634,7 +2718,7 @@ module Box2D.Dynamics { /** * Get the mass data of the body. The rotational inertial is relative to the center of mass. - * @data Body's mass data, this argument is `out`. + * @param data Body's mass data, this argument is `out`. **/ public GetMassData(data: b2Shapes.b2MassData): void; @@ -2682,14 +2766,14 @@ module Box2D.Dynamics { /** * Get the world coordinates of a point given the local coordinates. - * @localPoint Point on the body measured relative to the body's origin. + * @param localPoint Point on the body measured relative to the body's origin. * @return localPoint expressed in world coordinates. **/ public GetWorldPoint(localPoint: b2Math.b2Vec2): b2Math.b2Vec2; /** * Get the world coordinates of a vector given the local coordinates. - * @localVector Vector fixed in the body. + * @param localVector Vector fixed in the body. * @return localVector expressed in world coordinates. **/ public GetWorldVector(localVector: b2Math.b2Vec2): b2Math.b2Vec2; @@ -2737,109 +2821,113 @@ module Box2D.Dynamics { /** * Set the active state of the body. An inactive body is not simulated and cannot be collided with or woken up. If you pass a flag of true, all fixtures will be added to the broad-phase. If you pass a flag of false, all fixtures will be removed from the broad-phase and all contacts will be destroyed. Fixtures and joints are otherwise unaffected. You may continue to create/destroy fixtures and joints on inactive bodies. Fixtures on an inactive body are implicitly inactive and will not participate in collisions, ray-casts, or queries. Joints connected to an inactive body are implicitly inactive. An inactive body is still owned by a b2World object and remains in the body list. - * @flag True to activate, false to deactivate. + * @param flag True to activate, false to deactivate. **/ public SetActive(flag: bool): void; /** * Set the world body angle - * @angle New angle of the body. + * @param angle New angle of the body. **/ public SetAngle(angle: number): void; /** * Set the angular damping of the body. - * @angularDamping New angular damping value. + * @param angularDamping New angular damping value. **/ public SetAngularDamping(angularDamping: number): void; /** * Set the angular velocity. - * @omega New angular velocity in radians/second. + * @param omega New angular velocity in radians/second. **/ public SetAngularVelocity(omega: number): void; /** * Set the sleep state of the body. A sleeping body has vety low CPU cost. - * @flag True to set the body to awake, false to put it to sleep. + * @param flag True to set the body to awake, false to put it to sleep. **/ public SetAwake(flag: bool): void; /** * Should this body be treated like a bullet for continuous collision detection? - * @flag True for bullet, false for normal. + * @param flag True for bullet, false for normal. **/ public SetBullet(flag: bool): void; /** * Set this body to have fixed rotation. This causes the mass to be reset. - * @fixed True for no rotation, false to allow for rotation. + * @param fixed True for no rotation, false to allow for rotation. **/ public SetFixedRotation(fixed: bool): void; /** * Set the linear damping of the body. - * @linearDamping The new linear damping for this body. + * @param linearDamping The new linear damping for this body. **/ public SetLinearDamping(linearDamping: number): void; /** * Set the linear velocity of the center of mass. - * @v New linear velocity of the center of mass. + * @param v New linear velocity of the center of mass. **/ public SetLinearVelocity(v: b2Math.b2Vec2): void; /** * Set the mass properties to override the mass properties of the fixtures Note that this changes the center of mass position. Note that creating or destroying fixtures can also alter the mass. This function has no effect if the body isn't dynamic. * @warning The supplied rotational inertia should be relative to the center of mass. - * @massData New mass data properties. + * @param massData New mass data properties. **/ public SetMassData(massData: b2Shapes.b2MassData): void; /** * Set the world body origin position. - * @position New world body origin position. + * @param position New world body origin position. **/ public SetPosition(position: b2Math.b2Vec2): void; /** * Set the position of the body's origin and rotation (radians). This breaks any contacts and wakes the other bodies. - * @position New world body origin position. - * @angle New world rotation angle of the body in radians. + * @param position New world body origin position. + * @param angle New world rotation angle of the body in radians. **/ public SetPositionAndAngle(position: b2Math.b2Vec2, angle: number): void; /** * Is this body allowed to sleep - * @flag True if the body can sleep, false if not. + * @param flag True if the body can sleep, false if not. **/ public SetSleepingAllowed(flag: bool): void; /** * Set the position of the body's origin and rotation (radians). This breaks any contacts and wakes the other bodies. Note this is less efficient than the other overload - you should use that if the angle is available. - * @xf Body's origin and rotation (radians). + * @param xf Body's origin and rotation (radians). **/ public SetTransform(xf: b2Math.b2Transform): void; /** * Set the type of this body. This may alter the mass and velocity - * @type Type enum. + * @param type Type enum. **/ public SetType(type: number): void; /** * Set the user data. Use this to store your application specific data. - * @data The user data for this body. + * @param data The user data for this body. **/ public SetUserData(data: any): void; /** * Splits a body into two, preserving dynamic properties * @note This provides a feature specific to this port. + * @param callback * @return The newly created bodies from the split. **/ public Split(callback: (fixture: b2Fixture) => bool): b2Body; } +} + +module Box2D.Dynamics { /** * A body definition holds all the data needed to construct a rigid body. You can safely re-use body definitions. @@ -2919,6 +3007,9 @@ module Box2D.Dynamics { **/ public userData: any; } +} + +module Box2D.Dynamics { /** * Implement this class to provide collision filtering. In other words, you can implement this class if you want finer control over contact creation. @@ -2930,7 +3021,7 @@ module Box2D.Dynamics { * @note This function is not in the box2dweb.as code -- might not work. * @see b2World.Raycast() * @see b2ContactFilter.ShouldCollide() - * @userData User provided data. Comments indicate that this might be a b2Fixture. + * @param userData User provided data. Comments indicate that this might be a b2Fixture. * @return True if the fixture should be considered for ray intersection, otherwise false. **/ public RayCollide(userData: any): bool; @@ -2938,12 +3029,15 @@ module Box2D.Dynamics { /** * Return true if contact calculations should be performed between these two fixtures. * @warning For performance reasons this is only called when the AABBs begin to overlap. - * @fixtureA b2Fixture potentially colliding with fixtureB. - * @fixtureB b2Fixture potentially colliding with fixtureA. + * @param fixtureA b2Fixture potentially colliding with fixtureB. + * @param fixtureB b2Fixture potentially colliding with fixtureA. * @return True if fixtureA and fixtureB probably collide requiring more calculations, otherwise false. **/ public ShouldCollide(fixtureA: b2Fixture, fixtureB: b2Fixture): bool; } +} + +module Box2D.Dynamics { /** * Contact impulses for reporting. Impulses are used instead of forces because sub-step forces may approach infinity for rigid body collisions. These match up one-to-one with the contact points in b2Manifold. @@ -2960,6 +3054,9 @@ module Box2D.Dynamics { **/ public tangentImpulses: b2Math.b2Vec2; } +} + +module Box2D.Dynamics { /** * Implement this class to get contact information. You can use these results for things like sounds and game logic. You can also get contact results by traversing the contact lists after the time step. However, you might miss some contacts because continuous physics leads to sub-stepping. Additionally you may receive multiple callbacks for the same contact in a single time step. You should strive to make your callbacks efficient because there may be many callbacks per time step. @@ -2969,30 +3066,33 @@ module Box2D.Dynamics { /** * Called when two fixtures begin to touch. - * @contact Contact point. + * @param contact Contact point. **/ public BeginContact(contact: Contacts.b2Contact): void; /** * Called when two fixtures cease to touch. - * @contact Contact point. + * @param contact Contact point. **/ public EndContact(contact: Contacts.b2Contact): void; /** * This lets you inspect a contact after the solver is finished. This is useful for inspecting impulses. Note: the contact manifold does not include time of impact impulses, which can be arbitrarily large if the sub-step is small. Hence the impulse is provided explicitly in a separate data structure. Note: this is only called for contacts that are touching, solid, and awake. - * @contact Contact point. - * @impulse Contact impulse. + * @param contact Contact point. + * @param impulse Contact impulse. **/ public PostSolve(contact: Contacts.b2Contact, impulse: b2ContactImpulse): void; /** * This is called after a contact is updated. This allows you to inspect a contact before it goes to the solver. If you are careful, you can modify the contact manifold (e.g. disable contact). A copy of the old manifold is provided so that you can detect changes. Note: this is called only for awake bodies. Note: this is called even when the number of contact points is zero. Note: this is not called for sensors. Note: if you set the number of contact points to zero, you will not get an EndContact callback. However, you may get a BeginContact callback the next step. - * @contact Contact point. - * @oldManifold Old manifold. + * @param contact Contact point. + * @param oldManifold Old manifold. **/ public PreSolve(contact: Contacts.b2Contact, oldManifold: b2Collision.b2Manifold): void; } +} + +module Box2D.Dynamics { /** * Implement and register this class with a b2World to provide debug drawing of physics entities in your game. @@ -3040,60 +3140,60 @@ module Box2D.Dynamics { /** * Append flags to the current flags. - * @flags Flags to add. + * @param flags Flags to add. **/ - public AppendFlags(flags:number): void; + public AppendFlags(flags: number): void; /** * Clear flags from the current flags. - * @flags flags to clear. + * @param flags flags to clear. **/ - public ClearFlags(flags:number): void; + public ClearFlags(flags: number): void; /** * Draw a circle. - * @center Circle center point. - * @radius Circle radius. - * @color Circle draw color. + * @param center Circle center point. + * @param radius Circle radius. + * @param color Circle draw color. **/ public DrawCircle(center: b2Math.b2Vec2, radius: number, color: b2Common.b2Color): void; /** * Draw a closed polygon provided in CCW order. - * @vertices Polygon verticies. - * @vertexCount Number of vertices in the polygon, usually vertices.length. - * @color Polygon draw color. + * @param vertices Polygon verticies. + * @param vertexCount Number of vertices in the polygon, usually vertices.length. + * @param color Polygon draw color. **/ - public DrawPolygon(vertices: b2Math.b2Vec2[], vertexCount:number, color: b2Common.b2Color): void; + public DrawPolygon(vertices: b2Math.b2Vec2[], vertexCount: number, color: b2Common.b2Color): void; /** * Draw a line segment. - * @p1 Line beginpoint. - * @p2 Line endpoint. - * @color Line color. + * @param p1 Line beginpoint. + * @param p2 Line endpoint. + * @param color Line color. **/ public DrawSegment(p1: b2Math.b2Vec2, p2: b2Math.b2Vec2, color: b2Common.b2Color): void; /** * Draw a solid circle. - * @center Circle center point. - * @radius Circle radius. - * @axis Circle axis. - * @color Circle color. + * @param center Circle center point. + * @param radius Circle radius. + * @param axis Circle axis. + * @param color Circle color. **/ public DrawSolidCircle(center: b2Math.b2Vec2, radius: number, axis: b2Math.b2Vec2, color: b2Common.b2Color): void; /** * Draw a solid closed polygon provided in CCW order. - * @vertices Polygon verticies. - * @vertexCount Number of vertices in the polygon, usually vertices.length. - * @color Polygon draw color. + * @param vertices Polygon verticies. + * @param vertexCount Number of vertices in the polygon, usually vertices.length. + * @param color Polygon draw color. **/ - public DrawSolidPolygon(vertices: b2Math.b2Vec2[], vertexCount:number, color: b2Common.b2Color): void; + public DrawSolidPolygon(vertices: b2Math.b2Vec2[], vertexCount: number, color: b2Common.b2Color): void; /** * Draw a transform. Choose your own length scale. - * @xf Transform to draw. + * @param xf Transform to draw. **/ public DrawTransform(xf: b2Math.b2Transform): void; @@ -3142,47 +3242,50 @@ module Box2D.Dynamics { /** * Set the alpha value used for lines. - * @alpha Alpha value for drawing lines. + * @param alpha Alpha value for drawing lines. **/ public SetAlpha(alpha: number): void; /** * Set the draw scale. - * @drawScale Draw scale ratio. + * @param drawScale Draw scale ratio. **/ public SetDrawScale(drawScale: number): void; /** * Set the alpha value used for fills. - * @alpha Alpha value for drawing fills. + * @param alpha Alpha value for drawing fills. **/ public SetFillAlpha(alpha: number): void; /** * Set the drawing flags. - * @flags Sets the drawing flags. + * @param flags Sets the drawing flags. **/ public SetFlags(flags: number): void; /** * Set the line thickness. - * @lineThickness The new line thickness. + * @param lineThickness The new line thickness. **/ public SetLineThickness(lineThickness: number): void; /** * Set the HTML Canvas Element for drawing. * @note box2dflash uses Sprite object, box2dweb uses CanvasRenderingContext2D, that is why this function is called SetSprite(). - * @canvas HTML Canvas Element to draw debug information to. + * @param canvas HTML Canvas Element to draw debug information to. **/ public SetSprite(canvas: CanvasRenderingContext2D): void; /** * Set the scale used for drawing XForms. - * @xformScale The transform scale. + * @param xformScale The transform scale. **/ public SetXFormScale(xformScale: number): void; } +} + +module Box2D.Dynamics { /** * Joints and shapes are destroyed when their associated body is destroyed. Implement this listener so that you may nullify references to these joints and shapes. @@ -3191,22 +3294,25 @@ module Box2D.Dynamics { /** * Called when any fixture is about to be destroyed due to the destruction of its parent body. - * @fixture b2Fixture being destroyed. + * @param fixture b2Fixture being destroyed. **/ public SayGoodbyeFixture(fixture: b2Fixture): void; /** * Called when any joint is about to be destroyed due to the destruction of one of its attached bodies. - * @joint b2Joint being destroyed. + * @param joint b2Joint being destroyed. **/ public SayGoodbyeJoint(joint: Joints.b2Joint): void; } +} + +module Box2D.Dynamics { /** * This holds contact filtering data. **/ export class b2FilterData { - + /** * The collision category bits. Normally you would just set one bit. **/ @@ -3228,6 +3334,9 @@ module Box2D.Dynamics { **/ public Copy(): b2FilterData; } +} + +module Box2D.Dynamics { /** * A fixture is used to attach a shape to a body for collision detection. A fixture inherits its transform from its parent. Fixtures hold additional non-geometric data such as friction, collision filters, etc. Fixtures are created via b2Body::CreateFixture. @@ -3267,7 +3376,7 @@ module Box2D.Dynamics { /** * Get the mass data for this fixture. The mass data is based on the density and the shape. The rotational inertia is about the shape's origin. This operation may be expensive. - * @massData This is a reference to a valid b2MassData, if it is null a new b2MassData is allocated and then returned. Default = null. + * @param massData This is a reference to a valid b2MassData, if it is null a new b2MassData is allocated and then returned. Default = null. * @return Mass data. **/ public GetMassData(massData?: b2Shapes.b2MassData): b2Shapes.b2MassData; @@ -3310,55 +3419,58 @@ module Box2D.Dynamics { /** * Perform a ray cast against this shape. - * @output Ray cast results. This argument is out. - * @input Ray cast input parameters. + * @param output Ray cast results. This argument is out. + * @param input Ray cast input parameters. * @return True if the ray hits the shape, otherwise false. **/ public RayCast(output: b2Collision.b2RayCastOutput, input: b2Collision.b2RayCastInput): bool; /** * Set the density of this fixture. This will _not_ automatically adjust the mass of the body. You must call b2Body::ResetMassData to update the body's mass. - * @density The new density. + * @param density The new density. **/ public SetDensity(density: number): void; /** * Set the contact filtering data. This will not update contacts until the next time step when either parent body is active and awake. - * @filter The new filter data. + * @param filter The new filter data. **/ public SetFilterData(filter: any): void; /** * Set the coefficient of friction. - * @friction The new friction coefficient. + * @param friction The new friction coefficient. **/ public SetFriction(friction: number): void; /** * Get the coefficient of restitution. - * @resitution The new restitution coefficient. + * @param resitution The new restitution coefficient. **/ public SetRestitution(restitution: number): void; /** * Set if this fixture is a sensor. - * @sensor True to set as a sensor, false to not be a sensor. + * @param sensor True to set as a sensor, false to not be a sensor. **/ public SetSensor(sensor: bool): void; /** * Set the user data. Use this to store your application specific data. - * @data User provided data. + * @param data User provided data. **/ public SetUserData(data: any): void; /** * Test a point for containment in this fixture. - * @p Point to test against, in world coordinates. + * @param p Point to test against, in world coordinates. * @return True if the point is in this shape, otherwise false. **/ public TestPoint(p: b2Math.b2Vec2): bool; } +} + +module Box2D.Dynamics { /** * A fixture definition is used to create a fixture. This class defines an abstract fixture definition. You can reuse fixture definitions safely. @@ -3405,12 +3517,15 @@ module Box2D.Dynamics { **/ constructor(); } +} + +module Box2D.Dynamics { /** * The world class manages all physics entities, dynamic simulation, and asynchronous queries. **/ export class b2World { - + /** * Locked **/ @@ -3423,14 +3538,14 @@ module Box2D.Dynamics { /** * Creates a new world. - * @gravity The world gravity vector. - * @doSleep Improvie performance by not simulating inactive bodies. + * @param gravity The world gravity vector. + * @param doSleep Improvie performance by not simulating inactive bodies. **/ constructor(gravity: b2Math.b2Vec2, doSleep: bool); /** * Add a controller to the world list. - * @c Controller to add. + * @param c Controller to add. * @return Controller that was added to the world. **/ public AddController(c: Controllers.b2Controller): Controllers.b2Controller; @@ -3442,14 +3557,14 @@ module Box2D.Dynamics { /** * Create a rigid body given a definition. No reference to the definition is retained. - * @def Body's definition. + * @param def Body's definition. * @return Created rigid body. **/ public CreateBody(def: b2BodyDef): b2Body; /** * Creates a new controller. - * @controller New controller. + * @param controller New controller. * @return New controller. **/ public CreateController(controller: Controllers.b2Controller): Controllers.b2Controller; @@ -3457,14 +3572,14 @@ module Box2D.Dynamics { /** * Create a joint to constrain bodies together. No reference to the definition is retained. This may cause the connected bodies to cease colliding. * @warning This function is locked during callbacks. - * @def Joint definition. + * @param def Joint definition. * @return New created joint. **/ public CreateJoint(def: Joints.b2JointDef): Joints.b2Joint; /** * Destroy a rigid body given a definition. No reference to the definition is retained. This function is locked during callbacks. - * @b Body to destroy. + * @param b Body to destroy. * @warning This function is locked during callbacks. **/ public DestroyBody(b: b2Body): void; @@ -3472,13 +3587,13 @@ module Box2D.Dynamics { /** * Destroy a controller given the controller instance. * @warning This function is locked during callbacks. - * @controller Controller to destroy. + * @param controller Controller to destroy. **/ public DestroyController(controller: Controllers.b2Controller): void; /** * Destroy a joint. This may cause the connected bodies to begin colliding. - * @j Joint to destroy. + * @param j Joint to destroy. **/ public DestroyJoint(j: Joints.b2Joint): void; @@ -3549,31 +3664,31 @@ module Box2D.Dynamics { /** * Query the world for all fixtures that potentially overlap the provided AABB. - * @callback A user implemented callback class. It should match signature function Callback(fixture:b2Fixture):Boolean. Return true to continue to the next fixture. - * @aabb The query bounding box. + * @param callback A user implemented callback class. It should match signature function Callback(fixture:b2Fixture):Boolean. Return true to continue to the next fixture. + * @param aabb The query bounding box. **/ public QueryAABB(callback: (fixutre: b2Fixture) => bool, aabb: b2Collision.b2AABB): void; /** * Query the world for all fixtures that contain a point. * @note This provides a feature specific to this port. - * @callback A user implemented callback class. It should match signature function Callback(fixture:b2Fixture):Boolean. Return true to continue to the next fixture. - * @p The query point. + * @param callback A user implemented callback class. It should match signature function Callback(fixture:b2Fixture):Boolean. Return true to continue to the next fixture. + * @param p The query point. **/ public QueryPoint(callback: (fixture: b2Fixture) => bool, p: b2Math.b2Vec2): void; /** * Query the world for all fixtures that precisely overlap the provided transformed shape. * @note This provides a feature specific to this port. - * @callback A user implemented callback class. It should match signature function Callback(fixture:b2Fixture):Boolean. Return true to continue to the next fixture. - * @shape The query shape. - * @transform Optional transform, default = null. + * @param callback A user implemented callback class. It should match signature function Callback(fixture:b2Fixture):Boolean. Return true to continue to the next fixture. + * @param shape The query shape. + * @param transform Optional transform, default = null. **/ public QueryShape(callback: (fixture: b2Fixture) => bool, shape: b2Shapes.b2Shape, transform?: b2Math.b2Transform): void; /** * Ray-cast the world for all fixtures in the path of the ray. Your callback Controls whether you get the closest point, any point, or n-points The ray-cast ignores shapes that contain the starting point. - * @callback A callback function which must be of signature: + * @param callback A callback function which must be of signature: * function Callback( * fixture:b2Fixture, // The fixture hit by the ray * point:b2Vec2, // The point of initial intersection @@ -3581,87 +3696,87 @@ module Box2D.Dynamics { * fraction:Number // The fractional length along the ray of the intersection * ):Number * Callback should return the new length of the ray as a fraction of the original length. By returning 0, you immediately terminate. By returning 1, you continue wiht the original ray. By returning the current fraction, you proceed to find the closest point. - * @point1 The ray starting point. - * @point2 The ray ending point. + * @param point1 The ray starting point. + * @param point2 The ray ending point. **/ public RayCast(callback: (fixture: b2Fixture, point: b2Math.b2Vec2, normal: b2Math.b2Vec2, fraction: number) => number, point1: b2Math.b2Vec2, point2: b2Math.b2Vec2): void; /** * Ray-cast the world for all fixture in the path of the ray. - * @point1 The ray starting point. - * @point2 The ray ending point. + * @param point1 The ray starting point. + * @param point2 The ray ending point. * @return Array of all the fixtures intersected by the ray. **/ public RayCastAll(point1: b2Math.b2Vec2, point2: b2Math.b2Vec2): b2Fixture[]; /** * Ray-cast the world for the first fixture in the path of the ray. - * @point1 The ray starting point. - * @point2 The ray ending point. + * @param point1 The ray starting point. + * @param point2 The ray ending point. * @return First fixture intersected by the ray. **/ public RayCastOne(point1: b2Math.b2Vec2, point2: b2Math.b2Vec2): b2Fixture; /** * Removes the controller from the world. - * @c Controller to remove. + * @param c Controller to remove. **/ public RemoveController(c: Controllers.b2Controller): void; /** * Use the given object as a broadphase. The old broadphase will not be cleanly emptied. * @warning This function is locked during callbacks. - * @broadphase: Broad phase implementation. + * @param broadphase: Broad phase implementation. **/ public SetBroadPhase(broadPhase: b2Collision.IBroadPhase): void; /** * Register a contact filter to provide specific control over collision. Otherwise the default filter is used (b2_defaultFilter). - * @filter Contact filter'er. + * @param filter Contact filter'er. **/ public SetContactFilter(filter: b2ContactFilter): void; /** * Register a contact event listener. - * @listener Contact event listener. + * @param listener Contact event listener. **/ public SetContactListener(listener: b2ContactListener): void; /** * Enable/disable continuous physics. For testing. - * @flag True for continuous physics, otherwise false. + * @param flag True for continuous physics, otherwise false. **/ public SetContinuousPhysics(flag: bool): void; /** * Register a routine for debug drawing. The debug draw functions are called inside the b2World::Step method, so make sure your renderer is ready to consume draw commands when you call Step(). - * @debugDraw Debug drawing instance. + * @param debugDraw Debug drawing instance. **/ public SetDebugDraw(debugDraw: b2DebugDraw): void; - + /** * Destruct the world. All physics entities are destroyed and all heap memory is released. - * @listener Destruction listener instance. + * @param listener Destruction listener instance. **/ public SetDestructionListener(listener: b2DestructionListener): void; /** * Change the global gravity vector. - * @gravity New global gravity vector. + * @param gravity New global gravity vector. **/ public SetGravity(gravity: b2Math.b2Vec2): void; /** * Enable/disable warm starting. For testing. - * @flag True for warm starting, otherwise false. + * @param flag True for warm starting, otherwise false. **/ public SetWarmStarting(flag: bool): void; /** * Take a time step. This performs collision detection, integration, and constraint solution. - * @dt The amout of time to simulate, this should not vary. - * @velocityIterations For the velocity constraint solver. - * @positionIterations For the position constraint solver. + * @param dt The amout of time to simulate, this should not vary. + * @param velocityIterations For the velocity constraint solver. + * @param positionIterations For the position constraint solver. **/ public Step(dt: number, velocityIterations: number, positionIterations: number): void; @@ -3683,78 +3798,82 @@ module Box2D.Dynamics.Contacts { * Constructor **/ constructor(); - + /** * Flag this contact for filtering. Filtering will occur the next time step. **/ public FlagForFiltering(): void; - + /** * Get the first fixture in this contact. * @return First fixture in this contact. **/ public GetFixtureA(): b2Fixture; - + /** * Get the second fixture in this contact. * @return Second fixture in this contact. **/ public GetFixtureB(): b2Fixture; - + /** * Get the contact manifold. Do not modify the manifold unless you understand the internals of Box2D. * @return Contact manifold. **/ public GetManifold(): b2Collision.b2Manifold; - + /** * Get the next contact in the world's contact list. * @return Next contact in the world's contact list. **/ public GetNext(): b2Contact; - + /** * Get the world manifold. + * @param worldManifold World manifold out. * @return World manifold. **/ public GetWorldManifold(worldManifold: b2Collision.b2WorldManifold): void; - + /** * Does this contact generate TOI events for continuous simulation. * @return True for continous, otherwise false. **/ public IsContinuous(): bool; - + /** * Has this contact been disabled? * @return True if disabled, otherwise false. **/ public IsEnabled(): bool; - + /** * Is this contact a sensor? * @return True if sensor, otherwise false. **/ public IsSensor(): bool; - + /** * Is this contact touching. * @return True if contact is touching, otherwise false. **/ public IsTouching(): bool; - + /** * Enable/disable this contact. This can be used inside the pre-solve contact listener. The contact is only disabled for the current time step (or sub-step in continuous collision). - * @flag True to enable, false to disable. + * @param flag True to enable, false to disable. **/ public SetEnabled(flag: bool): void; /** * Change this to be a sensor or-non-sensor contact. - * @sensor True to be sensor, false to not be a sensor. + * @param sensor True to be sensor, false to not be a sensor. **/ public SetSensor(sensor: bool): void; } +} + +module Box2D.Dynamics.Contacts { /** * A contact edge is used to connect bodies and contacts together in a contact graph where each body is a node and each contact is an edge. A contact edge belongs to a doubly linked list maintained in each attached body. Each contact has two contact nodes, one for each attached body. @@ -3781,6 +3900,9 @@ module Box2D.Dynamics.Contacts { **/ public prev: b2ContactEdge; } +} + +module Box2D.Dynamics.Contacts { /** * This structure is used to report contact point results. @@ -3822,9 +3944,111 @@ module Box2D.Dynamics.Contacts { **/ public tangentImpulse: number; } +} +module Box2D.Dynamics.Controllers { + /** + * Base class for controllers. Controllers are a convience for encapsulating common per-step functionality. + **/ + export class b2Controller { + /** + * Body count. + **/ + public m_bodyCount: number; + + /** + * List of bodies. + **/ + public m_bodyList: b2ControllerEdge; + + /** + * Adds a body to the controller. + * @param body Body to add. + **/ + public AddBody(body: b2Body): void; + + /** + * Removes all bodies from the controller. + **/ + public Clear(): void; + + /** + * Debug drawing. + * @param debugDraw Handle to drawer. + **/ + public Draw(debugDraw: b2DebugDraw): void; + + /** + * Gets the body list. + * @return Body list. + **/ + public GetBodyList(): b2ControllerEdge; + + /** + * Gets the next controller. + * @return Next controller. + **/ + public GetNext(): b2Controller; + + /** + * Gets the world. + * @return World. + **/ + public GetWorld(): b2World; + + /** + * Removes a body from the controller. + * @param body Body to remove from this controller. + **/ + public RemoveBody(body: b2Body): void; + + /** + * Step + * @param step b2TimeStep -> Private internal class. Not sure why this is exposed. + **/ + public Step(step: any/*b2TimeStep*/): void; + } +} + +module Box2D.Dynamics.Controllers { + + /** + * Controller Edge. + **/ + export class b2ControllerEdge { + + /** + * Body. + **/ + public body: b2Body; + + /** + * Provides quick access to the other end of this edge. + **/ + public controller: b2Controller; + + /** + * The next controller edge in the controller's body list. + **/ + public nextBody: b2ControllerEdge; + + /** + * The next controller edge in the body's controller list. + **/ + public nextController: b2ControllerEdge; + + /** + * The previous controller edge in the controller's body list. + **/ + public prevBody: b2ControllerEdge; + + /** + * The previous controller edge in the body's controller list. + **/ + public prevController: b2ControllerEdge; + } } module Box2D.Dynamics.Controllers { @@ -3886,6 +4110,9 @@ module Box2D.Dynamics.Controllers { **/ public velocity: b2Math.b2Vec2; } +} + +module Box2D.Dynamics.Controllers { /** * Applies an acceleration every frame, like gravity @@ -3898,11 +4125,13 @@ module Box2D.Dynamics.Controllers { public A: b2Math.b2Vec2; /** - * Step. - * @step Internal b2TimeStep structure. + * @see b2Controller.Step **/ public Step(step: any/* b2TimeStep*/): void; } +} + +module Box2D.Dynamics.Controllers { /** * Applies an acceleration every frame, like gravity. @@ -3915,110 +4144,13 @@ module Box2D.Dynamics.Controllers { public A: b2Math.b2Vec2; /** - * Step. - * @step Internal b2TimeStep structure. + * @see b2Controller.Step **/ public Step(step: any/* b2TimeStep*/): void; } +} - /** - * Base class for controllers. Controllers are a convience for encapsulating common per-step functionality. - **/ - export class b2Controller { - - /** - * Body count. - **/ - public m_bodyCount: number; - - /** - * List of bodies. - **/ - public m_bodyList: b2ControllerEdge; - - /** - * Adds a body to the controller. - * @body Body to add. - **/ - public AddBody(body: b2Body): void; - - /** - * Removes all bodies from the controller. - **/ - public Clear(): void; - - /** - * Debug drawing. - * @debugDraw Handle to drawer. - **/ - public Draw(debugDraw: b2DebugDraw): void; - - /** - * Gets the body list. - * @return Body list. - **/ - public GetBodyList(): b2ControllerEdge; - - /** - * Gets the next controller. - * @return Next controller. - **/ - public GetNext(): b2Controller; - - /** - * Gets the world. - * @return World. - **/ - public GetWorld(): b2World; - - /** - * Removes a body from the controller. - * @body Body to remove from this controller. - **/ - public RemoveBody(body: b2Body): void; - - /** - * Step - * @step b2TimeStep -> Private internal class. Not sure why this is exposed. - **/ - public Step(step: any/*b2TimeStep*/): void; - } - - /** - * Controller Edge. - **/ - export class b2ControllerEdge { - - /** - * Body. - **/ - public body: b2Body; - - /** - * Provides quick access to the other end of this edge. - **/ - public controller: b2Controller; - - /** - * The next controller edge in the controller's body list. - **/ - public nextBody: b2ControllerEdge; - - /** - * The next controller edge in the body's controller list. - **/ - public nextController: b2ControllerEdge; - - /** - * The previous controller edge in the controller's body list. - **/ - public prevBody: b2ControllerEdge; - - /** - * The previous controller edge in the body's controller list. - **/ - public prevController: b2ControllerEdge; - } +module Box2D.Dynamics.Controllers { /** * Applies simplified gravity between every pair of bodies. @@ -4037,11 +4169,13 @@ module Box2D.Dynamics.Controllers { public invSqr: bool; /** - * Step. - * @step Internal b2TimeStep structure. + * @see b2Controller.Step **/ public Step(step: any/* b2TimeStep*/): void; } +} + +module Box2D.Dynamics.Controllers { /** * Applies top down linear damping to the controlled bodies The damping is calculated by multiplying velocity by a matrix in local co-ordinates. @@ -4061,19 +4195,163 @@ module Box2D.Dynamics.Controllers { /** * Helper function to set T in a common case. - * @xDamping x - * @yDamping y + * @param xDamping x + * @param yDamping y **/ public SetAxisAligned(xDamping: number, yDamping: number): void; /** - * Step. - * @step Internal b2TimeStep structure. + * @see b2Controller.Step **/ public Step(step: any/* b2TimeStep*/): void; } } +module Box2D.Dynamics.Joints { + + /** + * The base joint class. Joints are used to constraint two bodies together in various fashions. Some joints also feature limits and motors. + **/ + export class b2Joint { + + /** + * Get the anchor point on bodyA in world coordinates. + * @return Anchor A point. + **/ + public GetAnchorA(): b2Math.b2Vec2; + + /** + * Get the anchor point on bodyB in world coordinates. + * @return Anchor B point. + **/ + public GetAnchorB(): b2Math.b2Vec2; + + /** + * Get the first body attached to this joint. + * @return Body A. + **/ + public GetBodyA(): b2Body; + + /** + * Get the second body attached to this joint. + * @return Body B. + **/ + public GetBodyB(): b2Body; + + /** + * Get the next joint the world joint list. + * @return Next joint. + **/ + public GetNext(): b2Joint; + + /** + * Get the reaction force on body2 at the joint anchor in Newtons. + * @param inv_dt + * @return Reaction force (N) + **/ + public GetReactionForce(inv_dt: number): b2Math.b2Vec2; + + /** + * Get the reaction torque on body2 in N. + * @param inv_dt + * @return Reaction torque (N). + **/ + public GetReactionTorque(inv_dt: number): number; + + /** + * Get the type of the concrete joint. + * @return Joint type. + **/ + public GetType(): number; + + /** + * Get the user data pointer. + * @return User data. Cast to your data type. + **/ + public GetUserData(): any; + + /** + * Short-cut function to determine if either body is inactive. + * @return True if active, otherwise false. + **/ + public IsActive(): bool; + + /** + * Set the user data pointer. + * @param data Your custom data. + **/ + public SetUserData(data: any); void; + } +} + +module Box2D.Dynamics.Joints { + + /** + * Joint definitions are used to construct joints. + **/ + export class b2JointDef { + + /** + * The first attached body. + **/ + public bodyA: b2Body; + + /** + * The second attached body. + **/ + public bodyB: b2Body; + + /** + * Set this flag to true if the attached bodies should collide. + **/ + public collideConnected: bool; + + /** + * The joint type is set automatically for concrete joint types. + **/ + public type: number; + + /** + * Use this to attach application specific data to your joints. + **/ + public userData: any; + + /** + * Constructor. + **/ + constructor(); + } +} + +module Box2D.Dynamics.Joints { + + /** + * A joint edge is used to connect bodies and joints together in a joint graph where each body is a node and each joint is an edge. A joint edge belongs to a doubly linked list maintained in each attached body. Each joint has two joint nodes, one for each attached body. + **/ + export class b2JointEdge { + + /** + * The joint. + **/ + public joint: b2Joint; + + /** + * The next joint edge in the body's joint list. + **/ + public next: b2JointEdge; + + /** + * Provides quick access to the other body attached. + **/ + public other: b2Body; + + /** + * The previous joint edge in the body's joint list. + **/ + public prev: b2JointEdge; + } +} + module Box2D.Dynamics.Joints { /** @@ -4113,35 +4391,39 @@ module Box2D.Dynamics.Joints { /** * Get the reaction force on body2 at the joint anchor in N. - * @inv_dt + * @param inv_dt * @return Reaction force in N. **/ public GetReactionForce(inv_dt: number): b2Math.b2Vec2; /** * Get the reaction torque on body 2 in N. + * @param inv_dt * @return Reaction torque in N. **/ public GetReactionTorque(inv_dt: number): number; /** * Sets the damping ratio. - * @ratio New damping ratio. + * @param ratio New damping ratio. **/ public SetDampingRatio(ratio: number): void; /** * Sets the frequency. - * @hz New frequency (hertz). + * @param hz New frequency (hertz). **/ public SetFrequency(hz: number): void; /** * Sets the length of distance between the two bodies. - * @length New length. + * @param length New length. **/ public SetLength(length: number): void; } +} + +module Box2D.Dynamics.Joints { /** * Distance joint definition. This requires defining an anchor point on both bodies and the non-zero length of the distance joint. The definition uses local anchor points so that the initial configuration can violate the constraint slightly. This helps when saving and loading a game. @@ -4178,16 +4460,19 @@ module Box2D.Dynamics.Joints { * Constructor. **/ constructor(); - + /** * Initialize the bodies, anchors, and length using the world anchors. - * @bA Body A. - * @bB Body B. - * @anchorA Anchor A. - * @anchorB Anchor B. + * @param bA Body A. + * @param bB Body B. + * @param anchorA Anchor A. + * @param anchorB Anchor B. **/ public Initialize(bA: b2Body, bB: b2Body, anchorA: b2Math.b2Vec2, anchorB: b2Math.b2Vec2): void; } +} + +module Box2D.Dynamics.Joints { /** * Friction joint. This is used for top-down friction. It provides 2D translational friction and angular friction. @@ -4230,7 +4515,7 @@ module Box2D.Dynamics.Joints { /** * Get the reaction force on body2 at the joint anchor in N. - * @inv_dt + * @param inv_dt * @return Reaction force in N. **/ public GetReactionForce(inv_dt: number): b2Math.b2Vec2; @@ -4243,16 +4528,19 @@ module Box2D.Dynamics.Joints { /** * Sets the max force. - * @force New max force. + * @param force New max force. **/ public SetMaxForce(force: number): void; /** * Sets the max torque. - * @torque New max torque. + * @param torque New max torque. **/ public SetMaxTorque(torque: number): void; } +} + +module Box2D.Dynamics.Joints { /** * Friction joint defintion. @@ -4283,15 +4571,18 @@ module Box2D.Dynamics.Joints { * Constructor. **/ constructor(); - + /** * Initialize the bodies, anchors, axis, and reference angle using the world anchor and world axis. - * @bA Body A. - * @bB Body B. - * @anchor World anchor. + * @param bA Body A. + * @param bB Body B. + * @param anchor World anchor. **/ public Initialize(bA: b2Body, bB: b2Body, anchor: b2Math.b2Vec2): void; } +} + +module Box2D.Dynamics.Joints { /** * A gear joint is used to connect two joints together. Either joint can be a revolute or prismatic joint. You specify a gear ratio to bind the motions together: coordinate1 + ratio coordinate2 = constant The ratio can be negative or positive. If one joint is a revolute joint and the other joint is a prismatic joint, then the ratio will have units of length or units of 1/length. @@ -4319,23 +4610,27 @@ module Box2D.Dynamics.Joints { /** * Get the reaction force on body2 at the joint anchor in N. - * @inv_dt + * @param inv_dt * @return Reaction force in N. **/ public GetReactionForce(inv_dt: number): b2Math.b2Vec2; /** * Get the reaction torque on body 2 in N. + * @param inv_dt * @return Reaction torque in N. **/ public GetReactionTorque(inv_dt: number): number; /** * Set the gear ratio. - * @force New gear ratio. + * @param force New gear ratio. **/ public SetRatio(ratio: number): void; } +} + +module Box2D.Dynamics.Joints { /** * Gear joint definition. This definition requires two existing revolute or prismatic joints (any combination will work). The provided joints must attach a dynamic body to a static body. @@ -4362,142 +4657,9 @@ module Box2D.Dynamics.Joints { **/ constructor(); } +} - /** - * The base joint class. Joints are used to constraint two bodies together in various fashions. Some joints also feature limits and motors. - **/ - export class b2Joint { - - /** - * Get the anchor point on bodyA in world coordinates. - * @return Anchor A point. - **/ - public GetAnchorA(): b2Math.b2Vec2; - - /** - * Get the anchor point on bodyB in world coordinates. - * @return Anchor B point. - **/ - public GetAnchorB(): b2Math.b2Vec2; - - /** - * Get the first body attached to this joint. - * @return Body A. - **/ - public GetBodyA(): b2Body; - - /** - * Get the second body attached to this joint. - * @return Body B. - **/ - public GetBodyB(): b2Body; - - /** - * Get the next joint the world joint list. - * @return Next joint. - **/ - public GetNext(): b2Joint; - - /** - * Get the reaction force on body2 at the joint anchor in Newtons. - * @inv_dt - * @return Reaction force (N) - **/ - public GetReactionForce(inv_dt: number): b2Math.b2Vec2; - - /** - * Get the reaction torque on body2 in N. - * @inv_dt - * @return Reaction torque (N). - **/ - public GetReactionTorque(inv_dt: number): number; - - /** - * Get the type of the concrete joint. - * @return Joint type. - **/ - public GetType(): number; - - /** - * Get the user data pointer. - * @return User data. Cast to your data type. - **/ - public GetUserData(): any; - - /** - * Short-cut function to determine if either body is inactive. - * @return True if active, otherwise false. - **/ - public IsActive(): bool; - - /** - * Set the user data pointer. - * @data Your custom data. - **/ - public SetUserData(data: any); void; - } - - /** - * Joint definitions are used to construct joints. - **/ - export class b2JointDef { - - /** - * The first attached body. - **/ - public bodyA: b2Body; - - /** - * The second attached body. - **/ - public bodyB: b2Body; - - /** - * Set this flag to true if the attached bodies should collide. - **/ - public collideConnected: bool; - - /** - * The joint type is set automatically for concrete joint types. - **/ - public type: number; - - /** - * Use this to attach application specific data to your joints. - **/ - public userData: any; - - /** - * Constructor. - **/ - constructor(); - } - - /** - * A joint edge is used to connect bodies and joints together in a joint graph where each body is a node and each joint is an edge. A joint edge belongs to a doubly linked list maintained in each attached body. Each joint has two joint nodes, one for each attached body. - **/ - export class b2JointEdge { - - /** - * The joint. - **/ - public joint: b2Joint; - - /** - * The next joint edge in the body's joint list. - **/ - public next: b2JointEdge; - - /** - * Provides quick access to the other body attached. - **/ - public other: b2Body; - - /** - * The previous joint edge in the body's joint list. - **/ - public prev: b2JointEdge; - } +module Box2D.Dynamics.Joints { /** * A line joint. This joint provides one degree of freedom: translation along an axis fixed in body1. You can use a joint limit to restrict the range of motion and a joint motor to drive the motion or to model joint friction. @@ -4506,13 +4668,13 @@ module Box2D.Dynamics.Joints { /** * Enable/disable the joint limit. - * @flag True to enable, false to disable limits + * @param flag True to enable, false to disable limits **/ public EnableLimit(flag: bool): void; /** * Enable/disable the joint motor. - * @flag True to enable, false to disable the motor. + * @param flag True to enable, false to disable the motor. **/ public EnableMotor(flag: bool): void; @@ -4566,13 +4728,14 @@ module Box2D.Dynamics.Joints { /** * Get the reaction force on body2 at the joint anchor in N. - * @inv_dt + * @param inv_dt * @return Reaction force in N. **/ public GetReactionForce(inv_dt: number): b2Math.b2Vec2; /** * Get the reaction torque on body 2 in N. + * @param inv_dt * @return Reaction torque in N. **/ public GetReactionTorque(inv_dt: number): number; @@ -4597,23 +4760,26 @@ module Box2D.Dynamics.Joints { /** * Set the joint limits, usually in meters. - * @lower Lower limit. - * @upper Upper limit. + * @param lower Lower limit. + * @param upper Upper limit. **/ public SetLimits(lower: number, upper: number): void; /** * Set the maximum motor force, usually in N. - * @force New max motor force. + * @param force New max motor force. **/ public SetMaxMotorForce(force: number): void; /** * Set the motor speed, usually in meters per second. - * @speed New motor speed. + * @param speed New motor speed. **/ public SetMotorSpeed(speed: number): void; } +} + +module Box2D.Dynamics.Joints { /** * Line joint definition. This requires defining a line of motion using an axis and an anchor point. The definition uses local anchor points and a local axis so that the initial configuration can violate the constraint slightly. The joint translation is zero when the local anchor points coincide in world space. Using local anchors and a local axis helps when saving and loading a game. @@ -4669,16 +4835,19 @@ module Box2D.Dynamics.Joints { * Constructor. **/ constructor(); - + /** * Initialize the bodies, anchors, and length using the world anchors. - * @bA Body A. - * @bB Body B. - * @anchor Anchor. - * @axis Axis. + * @param bA Body A. + * @param bB Body B. + * @param anchor Anchor. + * @param axis Axis. **/ public Initialize(bA: b2Body, bB: b2Body, anchor: b2Math.b2Vec2, axis: b2Math.b2Vec2): void; } +} + +module Box2D.Dynamics.Joints { /** * A mouse joint is used to make a point on a body track a specified world point. This a soft constraint with a maximum force. This allows the constraint to stretch and without applying huge forces. Note: this joint is not fully documented as it is intended primarily for the testbed. See that for more instructions. @@ -4717,13 +4886,14 @@ module Box2D.Dynamics.Joints { /** * Get the reaction force on body2 at the joint anchor in N. - * @inv_dt + * @param inv_dt * @return Reaction force in N. **/ public GetReactionForce(inv_dt: number): b2Math.b2Vec2; /** * Get the reaction torque on body 2 in N. + * @param inv_dt * @return Reaction torque in N. **/ public GetReactionTorque(inv_dt: number): number; @@ -4736,28 +4906,31 @@ module Box2D.Dynamics.Joints { /** * Sets the damping ratio. - * @ratio New damping ratio. + * @param ratio New damping ratio. **/ public SetDampingRatio(ratio: number): void; /** * Sets the frequency. - * @hz New frequency (hertz). + * @param hz New frequency (hertz). **/ public SetFrequency(hz: number): void; /** * Sets the max force. - * @maxForce New max force. + * @param maxForce New max force. **/ public SetMaxForce(maxForce: number): void; /** * Use this to update the target point. - * @target New target. + * @param target New target. **/ public SetTarget(target: b2Math.b2Vec2): void; } +} + +module Box2D.Dynamics.Joints { /** * Mouse joint definition. This requires a world target point, tuning parameters, and the time step. @@ -4784,6 +4957,9 @@ module Box2D.Dynamics.Joints { **/ constructor(); } +} + +module Box2D.Dynamics.Joints { /** * A prismatic joint. This joint provides one degree of freedom: translation along an axis fixed in body1. Relative rotation is prevented. You can use a joint limit to restrict the range of motion and a joint motor to drive the motion or to model joint friction. @@ -4792,13 +4968,13 @@ module Box2D.Dynamics.Joints { /** * Enable/disable the joint limit. - * @flag True to enable, false to disable. + * @param flag True to enable, false to disable. **/ public EnableLimit(flag: bool): void; /** * Enable/disable the joint motor. - * @flag True to enable, false to disable. + * @param flag True to enable, false to disable. **/ public EnableMotor(flag: bool): void; @@ -4846,13 +5022,14 @@ module Box2D.Dynamics.Joints { /** * Get the reaction force on body2 at the joint anchor in N. - * @inv_dt + * @param inv_dt * @return Reaction force in N. **/ public GetReactionForce(inv_dt: number): b2Math.b2Vec2; /** * Get the reaction torque on body 2 in N. + * @param inv_dt * @return Reaction torque in N. **/ public GetReactionTorque(inv_dt: number): number; @@ -4877,23 +5054,26 @@ module Box2D.Dynamics.Joints { /** * Set the joint limits, usually in meters. - * @lower Lower limit. - * @upper Upper limit. + * @param lower Lower limit. + * @param upper Upper limit. **/ public SetLimits(lower: number, upper: number): void; /** * Set the maximum motor force, usually in N. - * @force New max force. + * @param force New max force. **/ public SetMaxMotorForce(force: number): void; /** * Set the motor speed, usually in meters per second. - * @speed New motor speed. + * @param speed New motor speed. **/ public SetMotorSpeed(speed: number): void; } +} + +module Box2D.Dynamics.Joints { /** * Prismatic joint definition. This requires defining a line of motion using an axis and an anchor point. The definition uses local anchor points and a local axis so that the initial configuration can violate the constraint slightly. The joint translation is zero when the local anchor points coincide in world space. Using local anchors and a local axis helps when saving and loading a game. @@ -4954,16 +5134,19 @@ module Box2D.Dynamics.Joints { * Constructor. **/ constructor(); - + /** * Initialize the joint. - * @bA Body A. - * @bB Body B. - * @anchor Anchor. - * @axis Axis. + * @param bA Body A. + * @param bB Body B. + * @param anchor Anchor. + * @param axis Axis. **/ public Initialize(bA: b2Body, bB: b2Body, anchor: b2Math.b2Vec2, axis: b2Math.b2Vec2): void; } +} + +module Box2D.Dynamics.Joints { /** * The pulley joint is connected to two bodies and two fixed ground points. The pulley supports a ratio such that: length1 + ratio length2 <= constant Yes, the force transmitted is scaled by the ratio. The pulley also enforces a maximum length limit on both sides. This is useful to prevent one side of the pulley hitting the top. @@ -5009,17 +5192,21 @@ module Box2D.Dynamics.Joints { /** * Get the reaction force on body2 at the joint anchor in N. - * @inv_dt + * @param inv_dt * @return Reaction force in N. **/ public GetReactionForce(inv_dt: number): b2Math.b2Vec2; /** * Get the reaction torque on body 2 in N. + * @param inv_dt * @return Reaction torque in N. **/ public GetReactionTorque(inv_dt: number): number; } +} + +module Box2D.Dynamics.Joints { /** * Pulley joint definition. This requires two ground anchors, two dynamic body anchor points, max lengths for each side, and a pulley ratio. @@ -5075,18 +5262,21 @@ module Box2D.Dynamics.Joints { * Constructor. **/ constructor(); - + /** * Initialize the bodies, anchors, and length using the world anchors. - * @bA Body A. - * @bB Body B. - * @gaA Ground anchor A. - * @gaB Ground anchor B. - * @anchorA Anchor A. - * @anchorB Anchor B. + * @param bA Body A. + * @param bB Body B. + * @param gaA Ground anchor A. + * @param gaB Ground anchor B. + * @param anchorA Anchor A. + * @param anchorB Anchor B. **/ public Initialize(bA: b2Body, bB: b2Body, gaA: b2Math.b2Vec2, gaB: b2Math.b2Vec2, anchorA: b2Math.b2Vec2, anchorB: b2Math.b2Vec2): void; } +} + +module Box2D.Dynamics.Joints { /** * A revolute joint constrains to bodies to share a common point while they are free to rotate about the point. The relative rotation about the shared point is the joint angle. You can limit the relative rotation with a joint limit that specifies a lower and upper angle. You can use a motor to drive the relative rotation about the shared point. A maximum motor torque is provided so that infinite forces are not generated. @@ -5095,13 +5285,13 @@ module Box2D.Dynamics.Joints { /** * Enable/disable the joint limit. - * @flag True to enable, false to disable. + * @param flag True to enable, false to disable. **/ public EnableLimit(flag: bool): void; /** * Enable/disable the joint motor. - * @flag True to enable, false to diasable. + * @param flag True to enable, false to diasable. **/ public EnableMotor(flag: bool): void; @@ -5149,13 +5339,14 @@ module Box2D.Dynamics.Joints { /** * Get the reaction force on body2 at the joint anchor in N. - * @inv_dt + * @param inv_dt * @return Reaction force in N. **/ public GetReactionForce(inv_dt: number): b2Math.b2Vec2; /** * Get the reaction torque on body 2 in N. + * @param inv_dt * @return Reaction torque in N. **/ public GetReactionTorque(inv_dt: number): number; @@ -5180,23 +5371,26 @@ module Box2D.Dynamics.Joints { /** * Set the joint limits in radians. - * @lower New lower limit. - * @upper New upper limit. + * @param lower New lower limit. + * @param upper New upper limit. **/ public SetLimits(lower: number, upper: number): void; /** * Set the maximum motor torque, usually in N-m. - * @torque New max torque. + * @param torque New max torque. **/ public SetMaxMotorTorque(torque: number): void; /** * Set the motor speed in radians per second. - * @speed New motor speed. + * @param speed New motor speed. **/ public SetMotorSpeed(speed: number); void; } +} + +module Box2D.Dynamics.Joints { /** * Revolute joint definition. This requires defining an anchor point where the bodies are joined. The definition uses local anchor points so that the initial configuration can violate the constraint slightly. You also need to specify the initial relative angle for joint limits. This helps when saving and loading a game. The local anchor points are measured from the body's origin rather than the center of mass because: 1. you might not know where the center of mass will be. 2. if you add/remove shapes from a body and recompute the mass, the joints will be broken. @@ -5252,15 +5446,18 @@ module Box2D.Dynamics.Joints { * Constructor. **/ constructor(); - + /** * Initialize the bodies, achors, and reference angle using the world anchor. - * @bA Body A. - * @bB Body B. - * @anchor Anchor. + * @param bA Body A. + * @param bB Body B. + * @param anchor Anchor. **/ public Initialize(bA: b2Body, bB: b2Body, anchor: b2Math.b2Vec2): void; } +} + +module Box2D.Dynamics.Joints { /** * A weld joint essentially glues two bodies together. A weld joint may distort somewhat because the island constraint solver is approximate. @@ -5281,17 +5478,21 @@ module Box2D.Dynamics.Joints { /** * Get the reaction force on body2 at the joint anchor in N. - * @inv_dt + * @param inv_dt * @return Reaction force in N. **/ public GetReactionForce(inv_dt: number): b2Math.b2Vec2; /** * Get the reaction torque on body 2 in N. + * @param inv_dt * @return Reaction torque in N. **/ public GetReactionTorque(inv_dt: number): number; } +} + +module Box2D.Dynamics.Joints { /** * Weld joint definition. You need to specify local anchor points where they are attached and the relative body angle. The position of the anchor points is important for computing the reaction torque. @@ -5317,13 +5518,15 @@ module Box2D.Dynamics.Joints { * Constructor. **/ constructor(); - + /** * Initialize the bodies, anchors, axis, and reference angle using the world anchor and world axis. - * @bA Body A. - * @bB Body B. - * @anchor Anchor. + * @param bA Body A. + * @param bB Body B. + * @param anchor Anchor. **/ public Initialize(bA: b2Body, bB: b2Body, anchor: b2Math.b2Vec2): void; } } + + diff --git a/breeze/breeze-1.0-tests.ts b/breeze/breeze-1.0-tests.ts new file mode 100644 index 0000000000..6cc115e6f2 --- /dev/null +++ b/breeze/breeze-1.0-tests.ts @@ -0,0 +1,787 @@ +/// + +import breeze = module(Breeze); +import core = module(BreezeCore); + +function test_dataType() { + var typ = breeze.DataType.DateTime; + var nm = typ.getName(); + var isNumber = typ.isNumeric; + var dv = typ.defaultValue; + var symbs = breeze.DataType.getSymbols(); + var x = typ.parentEnum === breeze.DataType; + var isFalse = breeze.DataType.contains(breeze.DataType.Double); + var dt = breeze.DataType.fromName("Decimal"); +} + +function test_dataProperty() { + var lastNameProp = new breeze.DataProperty({ + name: "lastName", + dataType: breeze.DataType.String, + isNullable: true, + maxLength: 20 + }); + var personEntityType: breeze.EntityType; + personEntityType.addProperty(lastNameProp); +} + +function test_dataService() { + var ds = new breeze.DataService({ + serviceName: "api/NorthwindIBModel", + hasServerMetadata: true + }); + var em = new breeze.EntityManager({ + dataService: ds + }); +} + +function test_entityAspect() { + var order: breeze.Entity; + order.entityAspect.acceptChanges(); + var entityKey = order.entityAspect.getKey(); + var valErrors = order.entityAspect.getValidationErrors(); + var orderDateErrors = order.entityAspect.getValidationErrors("OrderDate"); + var orderDateProperty = order.entityType.getProperty("OrderDate"); + var orderDateErrors = order.entityAspect.getValidationErrors(orderDateProperty); + order.entityAspect.loadNavigationProperty("Orders").then(function (data) { + var orders = data.results; + }).fail(function (exception) { }); + order.entityAspect.rejectChanges(); + order.entityAspect.setDeleted(); + order.entityAspect.setModified(); + order.entityAspect.setUnchanged(); + var isOk = order.entityAspect.validateEntity(); + if (!isOk) { + var errors = order.entityAspect.getValidationErrors(); + } + var isOk = order.entityAspect.validateProperty("Order"); + var orderDateProperty = order.entityType.getProperty("OrderDate"); + //var isOk = order.entityAspect.validateProperty(OrderDateProperty); + order.entityAspect.propertyChanged.subscribe(function (propertyChangedArgs) { + var entity = propertyChangedArgs.entity; + var propertyNameChanged = propertyChangedArgs.propertyName; + var oldValue = propertyChangedArgs.oldValue; + var newValue = propertyChangedArgs.newValue; + }); + order.entityAspect.validationErrorsChanged.subscribe(function (validationChangeArgs) { + var entity = validationChangeArgs.entity; + var errorsAdded = validationChangeArgs.added; + var errorsCleared = validationChangeArgs.removed; + }); + +} + +function test_entityKey() { + var em1: breeze.EntityManager; + var employee1: breeze.Entity; + var empType = em1.metadataStore.getEntityType("Employee"); + var entityKey = new breeze.EntityKey( empType, 1); + var empKey = employee1.entityAspect.getKey(); + var empTerrType = em1.metadataStore.getEntityType("EmployeeTerritory"); + var empTerrKey = new breeze.EntityKey( empTerrType, [1, 77]); + var empType = em1.metadataStore.getEntityType("Employee"); + var empKey1 = new breeze.EntityKey( empType, 1); + var empKey2 = employee1.entityAspect.getKey(); + if (empKey1.equals(empKey2)) { } + if (breeze.EntityKey.equals(empKey1, empKey2)) { } +} + +function test_metadataStore() { + var ms = new breeze.MetadataStore(); + var entityManager = new breeze.EntityManager({ + serviceName: "api/NorthwindIBModel", + metadataStore: ms + }); + var em1: breeze.EntityManager; + em1.setProperties({ metadataStore: ms }); + var metadataAsString = ms.exportMetadata(); + window.localStorage.setItem("metadata", metadataAsString); + var metadataFromStorage = window.localStorage.getItem("metadata"); + var newMetadataStore = new breeze.MetadataStore(); + newMetadataStore.importMetadata(metadataFromStorage); + var ms = new breeze.MetadataStore(); + ms.fetchMetadata("api/NorthwindIBModel") + .then(function (rawMetadata) { }) + .fail(function (exception) { }); + var odType = em1.metadataStore.getEntityType("OrderDetail"); + var badType = em1.metadataStore.getEntityType("Foo", false); + var allTypes = em1.metadataStore.getEntityTypes(); + if (!em1.metadataStore.hasMetadataFor("api/NorthwindIBModel")) { } + var metadataAsString = ms.exportMetadata(); + window.localStorage.setItem("metadata", metadataAsString); + var metadataFromStorage = window.localStorage.getItem("metadata"); + var newMetadataStore = breeze.MetadataStore.importMetadata(metadataFromStorage); + var metadataAsString = ms.exportMetadata(); + window.localStorage.setItem("metadata", metadataAsString); + var metadataFromStorage = window.localStorage.getItem("metadata"); + var newMetadataStore = new breeze.MetadataStore(); + newMetadataStore.importMetadata(metadataFromStorage); + if (em1.metadataStore.isEmpty()) { } + var Customer = function () { + this.miscData = "asdf"; + } + em1.metadataStore.registerEntityTypeCtor("Customer", Customer); +} + +function test_entityManager() { + var entityManager = new breeze.EntityManager("api/NorthwindIBModel"); + var entityManager = new breeze.EntityManager({ serviceName: "api/NorthwindIBModel" }); + var metadataStore = new breeze.MetadataStore(); + var entityManager = new breeze.EntityManager({ + serviceName: "api/NorthwindIBModel", + metadataStore: metadataStore + }); + return new breeze.QueryOptions({ + mergeStrategy: null, + fetchStrategy: this.fetchStrategy + }); + var queryOptions = new breeze.QueryOptions({ + mergeStrategy: breeze.MergeStrategy.OverwriteChanges, + fetchStrategy: breeze.FetchStrategy.FromServer + }); + var validationOptions = new breeze.ValidationOptions({ + validateOnAttach: true, + validateOnSave: true, + validateOnQuery: false + }); + var entityManager = new breeze.EntityManager({ + serviceName: "api/NorthwindIBModel", + queryOptions: queryOptions, + validationOptions: validationOptions + }); + var custType = em1.metadataStore.getEntityType("Customer"); + var cust1 = custType.createEntity(); + em1.addEntity(cust1); + em1.attachEntity(cust1, breeze.EntityState.Added); + em1.clear(); + var em2 = em1.createEmptyCopy(); + em1.detachEntity(cust1); + var serviceName: string; + var em = new breeze.EntityManager(serviceName); + var query = new breeze.EntityQuery("Orders"); + em.executeQuery(query) + .then(function (data) { + var orders = data.results; + }).fail(function (err) { + }); + var em = new breeze.EntityManager(serviceName); + var query = new breeze.EntityQuery("Orders"); + em.executeQuery(query, + function (data) { + var orders = data.results; + }, + function (err) { + }); + var em = new breeze.EntityManager(serviceName); + var query = new breeze.EntityQuery("Orders").using(em); + query.execute() + .then(function (data) { + var orders = data.results; + }).fail(function (err) { + }); + var em = new breeze.EntityManager(serviceName); + var query = new breeze.EntityQuery("Orders"); + var orders = em.executeQueryLocally(query); + var em = new breeze.EntityManager(serviceName); + var query = new breeze.EntityQuery("Orders").using(breeze.FetchStrategy.FromLocalCache); + em.executeQuery(query) + .then(function (data) { + var orders = data.results; + }).fail(function (err) { + }); + var bundle = em1.exportEntities(); + window.localStorage.setItem("myEntityManager", bundle); + var bundleFromStorage = window.localStorage.getItem("myEntityManager"); + var em2 = new breeze.EntityManager({ + serviceName: em1.serviceName, + metadataStore: em1.metadataStore + }); + em2.importEntities(bundleFromStorage); + var entitiesToExport: breeze.Entity[]; + var bundle = em1.exportEntities(entitiesToExport); + em2.importEntities(bundle, { mergeStrategy: breeze.MergeStrategy.PreserveChanges }); + var em1 = new breeze.EntityManager("api/NorthwindIBModel"); + em1.fetchMetadata() + .then(function () { + var metadataStore = em1.metadataStore; + }) + .fail(function (exception) { + }); + var employeeType = em1.metadataStore.getEntityType("Employee"); + var employeeKey = new breeze.EntityKey( employeeType, 1); + var employee = em1.fetchEntityByKey(employeeKey); + var emp2 = em1.fetchEntityByKey("Employee", 6); + var emp3 = em1.fetchEntityByKey("Entityee", [6]); + var custType = em1.metadataStore.getEntityType("Customer"); + var custumer = custType.createEntity(); + var customerId = em.generateTempKeyValue(custumer); + em1.saveChanges() + .then(function (data) { + var sameCust1 = data.results[0]; + }); + var changedEntities = em1.getChanges(); + var custType = em1.metadataStore.getEntityType("Customer"); + var changedCustomers = em1.getChanges(custType); + var custType = em1.metadataStore.getEntityType("Customer"); + var orderType = em1.metadataStore.getEntityType("Order"); + var changedCustomersAndOrders = em1.getChanges([custType, orderType]); + var entities = em1.getEntities(); + var custType = em1.metadataStore.getEntityType("Customer"); + var customers = em1.getEntities(custType); + var custType = em1.metadataStore.getEntityType("Customer"); + var orderType = em1.metadataStore.getEntityType("Order"); + var customersAndOrders = em1.getChanges([custType, orderType]); + var custType = em1.metadataStore.getEntityType("Customer"); + var orderType = em1.metadataStore.getEntityType("Order"); + var addedCustomersAndOrders = em1.getEntities([custType, orderType], breeze.EntityState.Added); + if (em1.hasChanges()) { } + var custType = em1.metadataStore.getEntityType("Customer"); + if (em1.hasChanges(custType)) { } + var custType = em1.metadataStore.getEntityType("Customer"); + var orderType = em1.metadataStore.getEntityType("Order"); + if (em1.hasChanges([custType, orderType])) { } + var bundle = em1.exportEntities(); + window.localStorage.setItem("myEntityManager", bundle); + var bundleFromStorage = window.localStorage.getItem("myEntityManager"); + var em2 = breeze.EntityManager.importEntities(bundleFromStorage); + var bundle = em1.exportEntities(); + var em2 = new breeze.EntityManager({ + serviceName: em1.serviceName, + metadataStore: em1.metadataStore + }); + em2.importEntities(bundle); + var bundle = em1.exportEntities(); + em2.importEntities(bundle, { mergeStrategy: breeze.MergeStrategy.PreserveChanges }); + em.saveChanges().then(function (saveResult) { + var savedEntities = saveResult.entities; + var keyMappings = saveResult.keyMappings; + }).fail(function (e) { + }); + var saveOptions = new breeze.SaveOptions({ allowConcurrentSaves: true }); + var entitiesToSave: breeze.Entity[]; + em.saveChanges(entitiesToSave, saveOptions).then(function (saveResult) { + var savedEntities = saveResult.entities; + var keyMappings = saveResult.keyMappings; + }).fail(function (e) { + }); + em.saveChanges(entitiesToSave, null, + function (saveResult) { + var savedEntities = saveResult.entities; + var keyMappings = saveResult.keyMappings; + }, function (e) { } + ); + em1.setProperties({ + serviceName: "api/foo", + }); + var em = new breeze.EntityManager({ serviceName: "api/NorthwindIBModel" }); + em.entityChanged.subscribe(function (changeArgs) { + var action = changeArgs.entityAction; + var entity = changeArgs.entity; + }); + var em = new breeze.EntityManager({ serviceName: "api/NorthwindIBModel" }); + em.hasChangesChanged.subscribe(function (args) { + var hasChangesChanged = args.hasChanges; + var entityManager = args.entityManager; + }); +} + +function test_entityQuery() { + var query = new breeze.EntityQuery("Customers"); + var query = new breeze.EntityQuery("Customers") + .where("CompanyName", "startsWith", "C") + .orderBy("Region"); + var serviceName: string; + var em = new breeze.EntityManager(serviceName); + var query = new breeze.EntityQuery("Orders").using(em); + query.execute() + .then(function (data) { }) + .fail(function (err) { }); + var em = new breeze.EntityManager(serviceName); + var query = new breeze.EntityQuery("Orders").using(em); + query.execute( + function (data) { + var orders = data.results; + }, + function (err) { }); + var em = new breeze.EntityManager(serviceName); + var query = new breeze.EntityQuery("Orders"); + em.executeQuery(query) + .then(function (data) { + var orders = data.results; + }).fail(function (err) { + }); + var query = new breeze.EntityQuery("Orders").using(em); + var orders = query.executeLocally(); + var query = new breeze.EntityQuery("Customers") + .where("CompanyName", "startsWith", "C") + .expand("Orders"); + var query = new breeze.EntityQuery("Orders") + .expand("Customer, Employee"); + var query = new breeze.EntityQuery("Orders") + .expand("Customer, OrderDetails, OrderDetails.Product"); + var query = breeze.EntityQuery.from("Customers"); + var query = new breeze.EntityQuery("Customers"); + var query = new breeze.EntityQuery().from("Customers"); + var customer: breeze.Entity; + var customers: breeze.Entity[]; + var customersQuery = breeze.EntityQuery.fromEntities(customers); + var customersQuery = breeze.EntityQuery.fromEntities(customers) + .where("Region", breeze.FilterQueryOp.NotEquals, null); + var customerQuery = breeze.EntityQuery.fromEntities(customer); + var metadataStore: breeze.MetadataStore; + var empType = metadataStore.getEntityType("Employee"); + var entityKey = new breeze.EntityKey( empType, 1); + var query = breeze.EntityQuery.fromEntityKey(entityKey); + var employee: breeze.Entity; + var entityKey = employee.entityAspect.getKey(); + var query = breeze.EntityQuery.fromEntityKey(entityKey); + var ordersNavProp = employee.entityType.getProperty("Orders"); + var query = breeze.EntityQuery.fromEntityNavigation(employee, ordersNavProp); + var query = new breeze.EntityQuery("Customers") + .orderBy("CompanyName"); + var query = new breeze.EntityQuery("Customers") + .orderBy("Region, CompanyName"); + var query = new breeze.EntityQuery("Products") + .orderBy("Category.CategoryName"); + var query = new breeze.EntityQuery("Customers") + .orderBy("CompanyName desc"); + var query = new breeze.EntityQuery("Customers") + .orderBy("Region desc, CompanyName desc"); + var query = new breeze.EntityQuery("Customers") + .orderByDesc("CompanyName"); + var query = new breeze.EntityQuery("Customers") + .where("CompanyName", "startsWith", "C") + .select("CompanyName"); + var query = new breeze.EntityQuery("Customers") + .where("CompanyName", "startsWith", "C") + .select("Orders"); + var query = new breeze.EntityQuery("Customers") + .where("CompanyName", "startsWith", "C") + .select("CompanyName, Orders"); + var query = new breeze.EntityQuery("Orders") + .where("Customer.CompanyName", "startsWith", "C") + .select("Customer.CompanyName, Customer, OrderDate"); + var query = new breeze.EntityQuery("Customers") + .where("CompanyName", "startsWith", "C") + .skip(5); + var query = new breeze.EntityQuery("Customers") + .take(5); + var query = new breeze.EntityQuery("Customers") + .top(5); + var em = new breeze.EntityManager(serviceName); + var query = new breeze.EntityQuery("Orders") + .using(em); + var em = new breeze.EntityManager(serviceName); + var query = new breeze.EntityQuery("Orders") + .using(breeze.MergeStrategy.PreserveChanges); + var em = new breeze.EntityManager(serviceName); + var query = new breeze.EntityQuery("Orders") + .using(breeze.FetchStrategy.FromLocalCache); + var query = new breeze.EntityQuery("Customers") + .where("CompanyName", "startsWith", "C"); + var query = new breeze.EntityQuery("Customers") + .where("CompanyName", breeze.FilterQueryOp.StartsWith, "C"); + var pred = new breeze.Predicate("CompanyName", breeze.FilterQueryOp.StartsWith, "C"); + var query = new breeze.EntityQuery("Customers") + .where(pred); + var pred = breeze.Predicate.create("CompanyName", "startswith", "C").and("Region", breeze.FilterQueryOp.Equals, null); + var query = new breeze.EntityQuery("Customers") + .where(pred); + var query = new breeze.EntityQuery("Products") + .where("Category.CategoryName", "startswith", "S"); + var query = new breeze.EntityQuery("Customers") + .where("toLower(CompanyName)", "startsWith", "c"); + var query = new breeze.EntityQuery("Customers") + .where("toUpper(substring(CompanyName, 1, 2))", breeze.FilterQueryOp.Equals, "OM"); +} + +function test_entityState() { + var anEntity: breeze.Entity; + var es = anEntity.entityAspect.entityState; + return es.isAdded(); + return es === breeze.EntityState.Added; + var es = anEntity.entityAspect.entityState; + return es.isAddedModifiedOrDeleted(); + return es === breeze.EntityState.Added || es === breeze.EntityState.Modified || es === breeze.EntityState.Deleted; + var es = anEntity.entityAspect.entityState; + return es.isDeleted(); + return es === breeze.EntityState.Deleted; + var es = anEntity.entityAspect.entityState; + return es.isDetached(); + return es === breeze.EntityState.Detached; + var es = anEntity.entityAspect.entityState; + return es.isModified(); + return es === breeze.EntityState.Modified; + var es = anEntity.entityAspect.entityState; + return es.isUnchanged(); + return es === breeze.EntityState.Unchanged; + var es = anEntity.entityAspect.entityState; + return es.isUnchangedOrModified(); + + return es === breeze.EntityState.Unchanged || es === breeze.EntityState.Modified; +} + +function test_entityType() { + var myMetadataStore: breeze.MetadataStore; + var myEntityType: breeze.EntityType; + var dataProperty1, dataProperty2, navigationProperty1: breeze.DataProperty; + var em1: breeze.EntityManager; + var entityManager = new breeze.EntityType({ + metadataStore: myMetadataStore, + serviceName: "api/NorthwindIBModel", + name: "person", + namespace: "myAppNamespace" + }); + myEntityType.addProperty(dataProperty1); + myEntityType.addProperty(dataProperty2); + myEntityType.addProperty(navigationProperty1); + var custType = em1.metadataStore.getEntityType("Customer"); + var countryProp = custType.getProperty("Country"); + var valFn = function (v) { + if (v == null) return true; + return (v.substring(0,2) === "US"); + }; + var countryValidator = new breeze.Validator("countryIsUS", valFn, + { displayName: "Country", messageTemplate: "'%displayName%' must start with 'US'" }); + custType.addValidator(countryValidator, countryProp); + countryProp.validators.push(countryValidator); + var someEntityLevelValidator: breeze.Validator; + custType.addValidator(someEntityLevelValidator); + custType.validators.push(someEntityLevelValidator); + var custType = em1.metadataStore.getEntityType("Customer"); + var cust1 = custType.createEntity(); + em1.addEntity(cust1); + var custType = em1.metadataStore.getEntityType("Customer"); + var customerNameDataProp = custType.getDataProperty("CustomerName"); + var custType = em1.metadataStore.getEntityType("Customer"); + var customerOrdersNavProp = custType.getDataProperty("Orders"); + var custType = em1.metadataStore.getEntityType("Customer"); + var arrayOfProps = custType.getProperties(); + var custType = em1.metadataStore.getEntityType("Customer"); + var companyNameProp = custType.getProperty("CompanyName"); + var orderDetailType = em1.metadataStore.getEntityType("OrderDetail"); + var companyNameProp2 = orderDetailType.getProperty("Order.Customer.CompanyName"); + var custType = em1.metadataStore.getEntityType("Customer"); + var arrayOfPropNames = custType.getPropertyNames(); + var custType = em1.metadataStore.getEntityType("Customer"); + custType.setProperties({ + autoGeneratedKeyType: breeze.AutoGeneratedKeyType.Identity, + defaultResourceName: "CustomersAndIncludedOrders" + }); +} + +//function test_enum() { +// var prototype = { +// nextDay: function () { +// var nextIndex = (this.dayIndex + 1) % 7; +// return DayOfWeek.getSymbols()[nextIndex]; +// } +// }; +// var DayOfWeek = new core.Enum("DayOfWeek", prototype); +// DayOfWeek.Monday = DayOfWeek.addSymbol({ dayIndex: 0 }); +// var symbol = DayOfWeek.Friday; +// if (DayOfWeek.contains(symbol)) { } +// var dayOfWeek = DayOfWeek.from("Thursday"); +// var symbols = DayOfWeek.getNames(); +// var symbols = DayOfWeek.getSymbols(); +// if (core.Enum.isSymbol(DayOfWeek.Wednesday)) { }; +// DayOfWeek.seal(); +// var name = DayOfWeek.Monday.getName(); +// var name = DayOfWeek.Monday.toString(); + + +// var prototype = { +// nextDay: function () { +// var nextIndex = (this.dayIndex + 1) % 7; +// return DayOfWeek.getSymbols()[nextIndex]; +// } +// }; +// var DayOfWeek = new core.Enum("DayOfWeek", prototype); +// DayOfWeek.Monday = DayOfWeek.addSymbol({ dayIndex: 0 }); +// DayOfWeek.Tuesday = DayOfWeek.addSymbol({ dayIndex: 1 }); +// DayOfWeek.Wednesday = DayOfWeek.addSymbol({ dayIndex: 2 }); +// DayOfWeek.Thursday = DayOfWeek.addSymbol({ dayIndex: 3 }); +// DayOfWeek.Friday = DayOfWeek.addSymbol({ dayIndex: 4 }); +// DayOfWeek.Saturday = DayOfWeek.addSymbol({ dayIndex: 5, isWeekend: true }); +// DayOfWeek.Sunday = DayOfWeek.addSymbol({ dayIndex: 6, isWeekend: true }); +// DayOfWeek.seal(); +// DayOfWeek.Monday.nextDay() === DayOfWeek.Tuesday; +// DayOfWeek.Sunday.nextDay() === DayOfWeek.Monday; +// DayOfWeek.Tuesday.isWeekend === undefined; +// DayOfWeek.Saturday.isWeekend == true; +// DayOfWeek instanceof core.Enum; +// core.Enum.isSymbol(DayOfWeek.Wednesday); +// DayOfWeek.contains(DayOfWeek.Thursday); +// DayOfWeek.Tuesday.parentEnum == DayOfWeek; +// DayOfWeek.getSymbols().length === 7; +// DayOfWeek.Friday.toString() === "Friday"; +//} + +function test_event() { + var myEntityManager: breeze.EntityManager; + var myEntity, person: breeze.Entity; + var salaryEvent = new core.Event("salaryEvent", person); + core.Event.enable("propertyChanged", myEntityManager, false); + core.Event.enable("propertyChanged", myEntityManager, true); + core.Event.enable("propertyChanged", myEntity.entityAspect, false); + core.Event.enable("propertyChanged", myEntity.entityAspect, null); + core.Event.enable("validationErrorsChanged", myEntityManager, function (em) { + return em.customTag === "blue"; + }); + core.Event.isEnabled("propertyChanged", myEntityManager); + salaryEvent.publish({ eventType: "payRaise", amount: 100 }); + salaryEvent.publish({ eventType: "payRaise", amount: 100 }, true); + salaryEvent.publish({ eventType: "payRaise", amount: 100 }, true, function (error) { }); + salaryEvent.publishAsync({ eventType: "payRaise", amount: 100 }); + salaryEvent.publishAsync({ eventType: "payRaise", amount: 100 }, function (error) { }); + salaryEvent.subscribe(function (eventArgs) { + if (eventArgs.eventType === "payRaise") { } + }); + var order: breeze.Entity; + order.entityAspect.propertyChanged.subscribe(function (pcEvent) { + if (pcEvent.propertyName === "OrderDate") { } + }); + var token = order.entityAspect.propertyChanged.subscribe(function (pcEvent) { }); + order.entityAspect.propertyChanged.unsubscribe(token); +} + +function test_localQueryComparisonOptions() { + var lqco = new breeze.LocalQueryComparisonOptions({ + name: "caseSensitive-nonSQL", + isCaseSensitive: true, + usesSql92CompliantStringComparison: false + }); + lqco.setAsDefault(); + var ms = new breeze.MetadataStore({ localQueryComparisonOptions: lqco }); + var em = new breeze.EntityManager({ metadataStore: ms }); + var lqco = new breeze.LocalQueryComparisonOptions({ + isCaseSensitive: false, + usesSql92CompliantStringComparison: true + }); + lqco.setAsDefault(); +} + +function test_namingConventions() { + var namingConv = new breeze.NamingConvention({ + serverPropertyNameToClient: function (serverPropertyName) { + return serverPropertyName.substr(0, 1).toLowerCase() + serverPropertyName.substr(1); + }, + clientPropertyNameToServer: function (clientPropertyName) { + return clientPropertyName.substr(0, 1).toUpperCase() + clientPropertyName.substr(1); + } + }); + var nc = new breeze.NamingConvention({ + serverPropertyNameToClient: function (x) { + return "xxx"; + } + }); + var ms = new breeze.MetadataStore({ namingConvention: namingConv }); + var em = new breeze.EntityManager({ metadataStore: ms }); + var namingConv = new breeze.NamingConvention({ + serverPropertyNameToClient: function (serverPropertyName) { + return serverPropertyName.substr(0, 1).toLowerCase() + serverPropertyName.substr(1); + }, + clientPropertyNameToServer: function (clientPropertyName) { + return clientPropertyName.substr(0, 1).toUpperCase() + clientPropertyName.substr(1); + } + }); + namingConv.setAsDefault(); +} + +function test_navigationProperty() { + var homeAddressProp = new breeze.NavigationProperty({ + name: "homeAddress", + entityTypeName: "Address:#myNamespace", + isScalar: true, + associationName: "address_person", + foreignKeyNames: ["homeAddressId"] + }); + var homeAddressIdProp = new breeze.DataProperty({ + name: "homeAddressId", + dataType: breeze.DataType.Int32 + }); + var personEntityType: breeze.EntityType; + personEntityType.addProperty(homeAddressProp); + personEntityType.addProperty(homeAddressIdProp); +} + +function test_predicate() { + var p1 = new breeze.Predicate("CompanyName", "StartsWith", "B"); + var p1a = breeze.Predicate.create("CompanyName", "==", "City"); + var p2a = p1a.and(p1a.not()); + var query = new breeze.EntityQuery("Customers").where(p1); + var p2 = new breeze.Predicate("Region", breeze.FilterQueryOp.Equals, null); + var query = new breeze.EntityQuery("Customers").where(p2); + var dt = new Date(88, 9, 12); + var p1 = breeze.Predicate.create("OrderDate", "ne", dt); + var p2 = breeze.Predicate.create("ShipCity", "startsWith", "C"); + var p3 = breeze.Predicate.create("Freight", ">", 100); + var newPred = p1.and(p2, p3); + var preds = [p2, p3]; + var newPred = p1.and(preds); + var p4 = breeze.Predicate.create("ShipCity", "startswith", "F") + .and("Size", "gt", 2000); + var dt = new Date(88, 9, 12); + var p1 = breeze.Predicate.create("OrderDate", "ne", dt); + var p2 = breeze.Predicate.create("ShipCity", "startsWith", "C"); + var p3 = breeze.Predicate.create("Freight", ">", 100); + var newPred = breeze.Predicate.and(p1, p2, p3); + var preds = [p1, p2, p3]; + var newPred = breeze.Predicate.and(preds); + var p1 = breeze.Predicate.create("Freight", "gt", 100); + var predArgs: any[] = ["Freight", "gt", 100]; + var p1 = breeze.Predicate.create(predArgs); + var p1 = new breeze.Predicate("Freight", "gt", 100); + var p1 = new breeze.Predicate("CompanyName", "StartsWith", "B"); + if (breeze.Predicate.isPredicate(p1)) { } + var p1 = breeze.Predicate.create("Freight", "gt", 100); + var not_p1 = breeze.Predicate.not(p1); + var not_p1 = p1.not(); + var not_p1 = breeze.Predicate.create("Freight", "le", 100); + var dt = new Date(88, 9, 12); + var p1 = breeze.Predicate.create("OrderDate", "ne", dt); + var p2 = breeze.Predicate.create("ShipCity", "startsWith", "C"); + var p3 = breeze.Predicate.create("Freight", ">", 100); + var newPred = breeze.Predicate.or(p1, p2, p3); + var preds = [p1, p2, p3]; + var newPred = breeze.Predicate.or(preds); + var dt = new Date(88, 9, 12); + var p1 = breeze.Predicate.create("OrderDate", "ne", dt); + var p2 = breeze.Predicate.create("ShipCity", "startsWith", "C"); + var p3 = breeze.Predicate.create("Freight", ">", 100); + var newPred = p1.and(p2, p3); + var preds = [p2, p3]; + var newPred = p1.and(preds); + var p4 = breeze.Predicate.create("ShipCity", "startswith", "F") + .or("Size", "gt", 2000); +} + +function test_queryOptions() { + var em1: breeze.EntityManager; + var newQo = new breeze.QueryOptions({ mergeStrategy: breeze.MergeStrategy.OverwriteChanges }); + em1.setProperties({ queryOptions: newQo }); + var newQo = new breeze.QueryOptions({ mergeStrategy: breeze.MergeStrategy.OverwriteChanges }); + newQo.setAsDefault(); + var queryOptions = em1.queryOptions.using(breeze.MergeStrategy.PreserveChanges); + var queryOptions = em1.queryOptions.using(breeze.FetchStrategy.FromLocalCache); + var queryOptions = em1.queryOptions.using({ mergeStrategy: breeze.MergeStrategy.OverwriteChanges }); +} + +function test_validationOptions() { + var newVo = new breeze.ValidationOptions({ validateOnSave: false, validateOnAttach: false }); + var em1: breeze.EntityManager; + em1.setProperties({ validationOptions: newVo }); + var validationOptions = new breeze.ValidationOptions() + var newOptions = validationOptions.using({ validateOnQuery: true, validateOnSave: false }); + newOptions.setAsDefault(); + var validationOptions = new breeze.ValidationOptions(); + var newOptions = validationOptions.using({ validateOnQuery: true, validateOnSave: false }); +} + +function test_validator() { + var valFn = function (v) { + if (v == null) return true; + return ( v.substr(0,2)=== "US"); + }; + var countryValidator = new breeze.Validator("countryIsUS", valFn, { + displayName: "Country", + messageTemplate: "'%displayName%' must start with 'US'" + }); + var metadataStore: breeze.MetadataStore; + var custType = metadataStore.getEntityType("Customer"); + var countryProp = custType.getProperty("Country"); + countryProp.validators.push(countryValidator); + function isValidZipCode(value) { + var re = /^\d{5}([\-]\d{4})?$/; + return (re.test(value)); + } + var valFn = function (v) { + if (v.getProperty("Country") === "USA") { + var postalCode = v.getProperty("PostalCode"); + return isValidZipCode(postalCode); + } + return true; + }; + var zipCodeValidator = new breeze.Validator("zipCodeValidator", valFn, + { messageTemplate: "For the US, this is not a valid PostalCode" }); + var em1: breeze.EntityManager; + var custType = em1.metadataStore.getEntityType("Customer"); + custType.validators.push(zipCodeValidator); + var numericRangeValidator = function (context) { + var valFn = function (v, ctx) { + if (v == null) return true; + if (typeof (v) !== "number") return false; + if (ctx.min != null && v < ctx.min) return false; + if (ctx.max != null && v > ctx.max) return false; + return true; + }; + return new breeze.Validator("numericRange", valFn, { + messageTemplate: "'%displayName%' must be an integer between the values of %min% and %max%", + min: context.min, + max: context.max + }); + }; + freightProperty.validators.push(numericRangeValidator({ min: 100, max: 500 })); + var productType = em1.metadataStore.getEntityType("Product"); + var discontinuedProperty = productType.getProperty("Discontinued"); + discontinuedProperty.validators.push(breeze.Validator.bool()); + var orderType = em1.metadataStore.getEntityType("Order"); + var freightProperty = orderType.getProperty("Freight"); + regionProperty.validators.push(breeze.Validator.byte()); + var orderType = em1.metadataStore.getEntityType("Order"); + var orderDateProperty = orderType.getProperty("OrderDate"); + orderDateProperty.validators.push(breeze.Validator.date()); + var v0 = breeze.Validator.maxLength({ maxLength: 5, displayName: "City" }); + v0.validate("adasdfasdf"); + var errMessage = v0.getMessage(); + var custType = em1.metadataStore.getEntityType("Customer"); + var customerIdProperty = custType.getProperty("CustomerID"); + customerIdProperty.validators.push(breeze.Validator.guid()); + var orderType = em1.metadataStore.getEntityType("Order"); + var freightProperty = orderType.getProperty("Freight"); + freightProperty.validators.push(breeze.Validator.int16()); + var orderType = em1.metadataStore.getEntityType("Order"); + var freightProperty = orderType.getProperty("Freight"); + freightProperty.validators.push(breeze.Validator.int32()); + var orderType = em1.metadataStore.getEntityType("Order"); + var freightProperty = orderType.getProperty("Freight"); + freightProperty.validators.push(breeze.Validator.int64()); + var custType = em1.metadataStore.getEntityType("Customer"); + var regionProperty = custType.getProperty("Region"); + regionProperty.validators.push(breeze.Validator.maxLength({ maxLength: 5 })); + var orderType = em1.metadataStore.getEntityType("Order"); + var freightProperty = orderType.getProperty("Freight"); + freightProperty.validators.push(breeze.Validator.number()); + var custType = em1.metadataStore.getEntityType("Customer"); + var regionProperty = custType.getProperty("Region"); + regionProperty.validators.push(breeze.Validator.required()); + var custType = em1.metadataStore.getEntityType("Customer"); + var regionProperty = custType.getProperty("Region"); + regionProperty.validators.push(breeze.Validator.string()); + var custType = em1.metadataStore.getEntityType("Customer"); + var regionProperty = custType.getProperty("Region"); + regionProperty.validators.push(breeze.Validator.stringLength({ minLength: 2, maxLength: 5 })); + var validator = breeze.Validator.maxLength({ maxLength: 5, displayName: "City" }); + var result = validator.validate("asdf"); + var ok = result === null; + result = validator.validate("adasdfasdf"); + var errMsg = result.errorMessage; + var context = result.context; + var sameValidator = result.validator; + var valFn = function (v) { + if (v == null) return true; + return (v.substr(0,2) === "US"); + }; + var countryValidator = new breeze.Validator("countryIsUS", valFn, { displayName: "Country" }); + breeze.Validator.messageTemplates["countryIsUS"] = "'%displayName%' must start with 'US'"; +} + +function test_demo() { + + var manager = new breeze.EntityManager('api/northwind'); + + var query = new breeze.EntityQuery() + .from("Employees"); + + manager.executeQuery(query).then(function (data) { }); +} diff --git a/breeze/breeze-1.0.d.ts b/breeze/breeze-1.0.d.ts new file mode 100644 index 0000000000..8a6458498d --- /dev/null +++ b/breeze/breeze-1.0.d.ts @@ -0,0 +1,731 @@ +// Type definitions for Breeze 1.0 +// Project: http://www.breezejs.com/ +// Definitions by: Boris Yankov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// Updated Jan 14 2011 - Jay Traband (www.ideablade.com) + + +declare module BreezeCore { + + interface ErrorCallback { + (error: Error): void; + } + + interface IEnum { + contains(object: any): bool; + fromName(name: string): EnumSymbol; + getNames(): string[]; + getSymbols(): EnumSymbol[]; + } + + class Enum implements IEnum { + constructor (name: string, methodObj?: any); + + addSymbol(propertiesObj?: any): EnumSymbol; + contains(object: any): bool; + fromName(name: string): EnumSymbol; + getNames(): string[]; + getSymbols(): EnumSymbol[]; + static isSymbol(object: any): bool; + seal(): void; + } + + class EnumSymbol { + parentEnum: IEnum; + + getName(): string; + toString(): string; + } + + class Event { + constructor (name: string, publisher: any, defaultErrorCallback?: ErrorCallback); + + static enable(eventName: string, target: any): void; + static enable(eventName: string, target: any, isEnabled: bool): void; + static enable(eventName: string, target: any, isEnabled: Function): void; + + static isEnabled(eventName: string, target: any): bool; + publish(data: any, publishAsync?: bool, errorCallback?: ErrorCallback): void; + publishAsync(data: any, errorCallback?: ErrorCallback): void; + subscribe(callback?: (data: any) => void ): number; + unsubscribe(unsubKey: number): bool; + } +} + +declare module Breeze { + + interface Entity { + entityAspect: EntityAspect; + entityType: EntityType; + } + + interface ComplexObject { + complexAspect: ComplexAspect; + complexType: ComplexType; + } + + interface IProperty { + name: string; + parentEntityType: EntityType; + validators: Validator[]; + isDataProperty: bool; + isNavigationProperty: bool; + } + + interface IStructuralType { + complexProperties: DataProperty[]; + dataProperties: DataProperty[]; + name: string; + namespace: string; + shortName: string; + unmappedProperties: DataProperty[]; + validators: Validator[]; + } + + class AutoGeneratedKeyType { + static Identity: AutoGeneratedKeyType; + static KeyGenerator: AutoGeneratedKeyType; + static None: AutoGeneratedKeyType; + } + + class ComplexAspect { + complexObject: ComplexObject; + entityAspect: EntityAspect; + parent: Object; + parentProperty: DataProperty; + propertyPath: string; + originalValues: Object; + } + + class ComplexType implements IStructuralType { + complexProperties: DataProperty[]; + dataProperties: DataProperty[]; + name: string; + namespace: string; + shortName: string; + unmappedProperties: DataProperty[]; + validators: Validator[]; + addProperty(dataProperty: DataProperty); + getProperties(): DataProperty[]; + } + + class DataProperty implements IProperty { + complexTypeName: string; + concurrencyMode: string; + dataType: DataTypeSymbol; + defaultValue: any; + fixedLength: bool; + isComplexProperty: bool; + isDataProperty: bool; + isNavigationProperty: bool; + isNullable: bool; + isPartOfKey: bool; + isUnmapped: bool; + + maxLength: number; + name: string; + nameOnServer: string; + parentEntityType: EntityType; + relatedNavigationProperty: NavigationProperty; + validators: Validator[]; + constructor (config: DataPropertyOptions); + } + + interface DataPropertyOptions { + complexTypeName?: string; + concurrencyMode?: string; + dataType?: DataTypeSymbol; + defaultValue?: any; + fixedLength?: bool; + isNullable?: bool; + isPartOfKey?: bool; + isUnmapped?: bool; + maxLength?: number; + name?: string; + nameOnServer?: string; + validators?: Validator[]; + } + + class DataService { + adapterName: string; + hasServerMetadata: bool; + serviceName: string; + constructor(config: DataServiceOptions); + } + + interface DataServiceOptions { + adapterName?: string; + hasServerMetadata?: bool; + serviceName?: string; + } + + class DataTypeSymbol extends BreezeCore.EnumSymbol { + defaultValue: any; + isNumeric: bool; + } + interface DataType extends BreezeCore.IEnum { + Binary: DataTypeSymbol; + Boolean: DataTypeSymbol; + Byte: DataTypeSymbol; + DateTime: DataTypeSymbol; + Decimal: DataTypeSymbol; + Double: DataTypeSymbol; + Guid: DataTypeSymbol; + Int16: DataTypeSymbol; + Int32: DataTypeSymbol; + Int64: DataTypeSymbol; + Single: DataTypeSymbol; + String: DataTypeSymbol; + Time: DataTypeSymbol; + Undefined: DataTypeSymbol; + toDataType(typeName: string): DataTypeSymbol; + parseDateFromServer(date: any): Date; + + } + declare var DataType: DataType; + + class EntityActionSymbol extends BreezeCore.EnumSymbol { + } + interface EntityAction extends BreezeCore.IEnum { + AcceptChanges: EntityActionSymbol; + Attach: EntityActionSymbol; + AttachOnImport: EntityActionSymbol; + AttachOnQuery: EntityActionSymbol; + Clear: EntityActionSymbol; + Detach: EntityActionSymbol; + EntityStateChange: EntityActionSymbol; + MergeOnImport: EntityActionSymbol; + MergeOnSave: EntityActionSymbol; + MergeOnQuery: EntityActionSymbol; + PropertyChange: EntityActionSymbol; + RejectChanges: EntityActionSymbol; + } + var EntityAction: EntityAction; + + class EntityAspect { + entity: Entity; + entityManager: EntityManager; + entityState: EntityStateSymbol; + isBeingSaved: bool; + originalValues: any; + + propertyChanged: PropertyChangedEvent; + validationErrorsChanged: ValidationErrorsChangedEvent; + + acceptChanges(): void; + addValidationError(validationError: ValidationError): void; + clearValidationErrors(): void; + getKey(forceRefresh?: bool): EntityKey; + + getValidationErrors(): ValidationError[]; + getValidationErrors(property: string): ValidationError[]; + getValidationErrors(property: IProperty): ValidationError[]; + + loadNavigationProperty(navigationProperty: string, callback?: Function, errorCallback?: Function): Promise; + loadNavigationProperty(navigationProperty: NavigationProperty, callback?: Function, errorCallback?: Function): Promise; + + rejectChanges(): void; + + removeValidationError(validator: Validator): void; + removeValidationError(validator: Validator, property: DataProperty): void; + removeValidationError(validator: Validator, property: NavigationProperty): void; + + setDeleted(): void; + setModified(): void; + setUnchanged(): void; + validateEntity(): bool; + + validateProperty(property: string, context?: any): bool; + validateProperty(property: DataProperty, context?: any): bool; + validateProperty(property: NavigationProperty, context?: any): bool; + } + + class PropertyChangedEventArgs { + entity: Entity; + propertyName: string; + oldValue: any; + newValue: any; + } + + class PropertyChangedEvent extends BreezeCore.Event { + subscribe(callback?: (data: PropertyChangedEventArgs) => void ): number; + } + + class ValidationErrorsChangedEventArgs { + entity: Entity; + added: ValidationError[]; + removed: ValidationError[]; + } + + class ValidationErrorsChangedEvent extends BreezeCore.Event { + subscribe(callback?: (data: ValidationErrorsChangedEventArgs) => void ): number; + } + + class EntityKey { + constructor (entityType: EntityType, keyValue: any); + constructor (entityType: EntityType, keyValues: any[]); + + equals(entityKey: EntityKey): bool; + static equals(k1: EntityKey, k2: EntityKey): bool; + } + + class EntityManager { + dataService: DataService; + keyGeneratorCtor: Function; + metadataStore: MetadataStore; + queryOptions: QueryOptions; + saveOptions: SaveOptions; + serviceName: string; + validationOptions: ValidationOptions; + + entityChanged: EntityChangedEvent; + hasChangesChanged: BreezeCore.Event; + + constructor (config?: EntityManagerOptions); + constructor (config?: string); + + addEntity(entity: Entity): Entity; + attachEntity(entity: Entity, entityState?: EntityStateSymbol): Entity; + clear(): void; + createEmptyCopy(): EntityManager; + detachEntity(entity: Entity): bool; + createEntity(entityTypeName: string, propertyInitializer: {}): Entity; + + executeQuery(query: string, callback?: ExecuteQuerySuccessCallback, errorCallback?: ExecuteQueryErrorCallback): Promise; + executeQuery(query: EntityQuery, callback?: ExecuteQuerySuccessCallback, errorCallback?: ExecuteQueryErrorCallback): Promise; + + executeQueryLocally(query: EntityQuery): Entity[]; + exportEntities(entities?: Entity[]): string; + fetchEntityByKey(typeName: string, keyValue: any, checkLocalCacheFirst?: bool): Entity; + fetchEntityByKey(typeName: string, keyValues: any[], checkLocalCacheFirst?: bool): Entity; + fetchEntityByKey(entityKey: EntityKey): Entity; + fetchMetadata(callback?: (schema: any) => void , errorCallback?: BreezeCore.ErrorCallback): Promise; + generateTempKeyValue(entity: Entity): any; + getChanges(): Entity[]; + getChanges(entityTypeName: string): Entity[]; + getChanges(entityTypeNames: string[]): Entity[]; + getChanges(entityType: EntityType): Entity[]; + getChanges(entityTypes: EntityType[]): Entity[]; + + getEntities(entityTypeName: string, entityState?: EntityStateSymbol): Entity[]; + getEntities(entityTypeNames?: string[], entityState?: EntityStateSymbol): Entity[]; + getEntities(entityTypeName?: string, entityStates?: EntityStateSymbol[]): Entity[]; + getEntities(entityTypeNames?: string[], entityStates?: EntityStateSymbol[]): Entity[]; + + getEntities(entityType: EntityType, entityState?: EntityStateSymbol): Entity[]; + getEntities(entityTypes?: EntityType[], entityState?: EntityStateSymbol): Entity[]; + getEntities(entityType?: EntityType, entityStates?: EntityStateSymbol[]): Entity[]; + getEntities(entityTypes?: EntityType[], entityStates?: EntityStateSymbol[]): Entity[]; + + getEntityByKey(typeName: string, keyValue: any): Entity; + getEntityByKey(typeName: string, keyValues: any[]): Entity; + getEntityByKey(entityKey: EntityKey): Entity; + + hasChanges(): bool; + hasChanges(entityTypeName: string): bool; + hasChanges(entityTypeNames: string[]): bool; + hasChanges(entityType: EntityType): bool; + hasChanges(entityTypes: EntityType[]): bool; + + static importEntities(exportedString: string, config?: { mergeStrategy?: MergeStrategySymbol; }): EntityManager; + importEntities(exportedString: string, config?: { mergeStrategy?: MergeStrategySymbol; }): EntityManager; + + rejectChanges(): Entity[]; + saveChanges(entities?: Entity[], saveOptions?: SaveOptions, callback?: SaveChangesSuccessCallback, errorCallback?: SaveChangesErrorCallback): Promise; + setProperties(config: EntityManagerProperties): void; + } + + interface EntityManagerOptions { + serviceName?: string; + dataService?: DataService; + metadataStore?: MetadataStore; + queryOptions?: QueryOptions; + saveOptions?: SaveOptions; + validationOptions?: ValidationOptions; + keyGeneratorCtor?: Function; + } + + interface EntityManagerProperties { + serviceName?: string; + dataService?: DataService; + queryOptions?: QueryOptions; + saveOptions?: SaveOptions; + validationOptions?: ValidationOptions; + keyGeneratorCtor?: Function; + } + + interface ExecuteQuerySuccessCallback { + (data: { results: Entity[]; query: EntityQuery; XHR: XMLHttpRequest; }): void; + } + + interface ExecuteQueryErrorCallback { + (error: { query: EntityQuery; XHR: XMLHttpRequest; }): void; + } + + interface SaveChangesSuccessCallback { + (saveResult: { entities: Entity[]; keyMappings: any; XHR: XMLHttpRequest; }): void; + } + + interface SaveChangesErrorCallback { + (error: { XHR: XMLHttpRequest; }): void; + } + + class EntityChangedEventArgs { + entity: Entity; + entityAction: EntityActionSymbol; + args: Object; + } + + class EntityChangedEvent extends BreezeCore.Event { + subscribe(callback?: (data: EntityChangedEventArgs) => void ): number; + } + + class EntityQuery { + entityManager: EntityManager; + orderByClause: OrderByClause; + parameters: Object; + queryOptions: QueryOptions; + resourceName: string; + skipCount: number; + takeCount: number; + wherePredicate: Predicate; + + constructor (resourceName?: string); + + execute(callback?: ExecuteQuerySuccessCallback, errorCallback?: ExecuteQueryErrorCallback): Promise; + executeLocally(): Entity[]; + expand(propertyPaths: string[]): EntityQuery; + expand(propertyPaths: string): EntityQuery; + static from(resourceName: string): EntityQuery; + from(resourceName: string): EntityQuery; + static fromEntities(entity: Entity): EntityQuery; + static fromEntities(entities: Entity[]): EntityQuery; + static fromEntityKey(entityKey: EntityKey): EntityQuery; + static fromEntityNavigation(entity: Entity, navigationProperty: NavigationProperty): EntityQuery; + inlineCount(enabled?: bool): EntityQuery; + orderBy(propertyPaths: string): EntityQuery; + orderBy(propertyPaths: string[]): EntityQuery; + orderByDesc(propertyPaths: string): EntityQuery; + orderByDesc(propertyPaths: string[]): EntityQuery; + select(propertyPaths: string): EntityQuery; + select(propertyPaths: string[]): EntityQuery; + skip(count: number): EntityQuery; + take(count: number): EntityQuery; + top(count: number): EntityQuery; + + using(obj: EntityManager): EntityQuery; + using(obj: MergeStrategySymbol): EntityQuery; + using(obj: FetchStrategySymbol): EntityQuery; + + where(predicate: Predicate): EntityQuery; + where(property: string, operator: string, value: any): EntityQuery; + where(property: string, operator: FilterQueryOpSymbol, value: any): EntityQuery; + where(predicate: FilterQueryOpSymbol): EntityQuery; + withParameters(params: Object): EntityQuery; + } + + interface OrderByClause { + } + + class EntityStateSymbol extends BreezeCore.EnumSymbol { + isAdded(): bool; + isAddedModifiedOrDeleted(): bool; + isDeleted(): bool; + isDetached(): bool; + isModified(): bool; + isUnchanged(): bool; + isUnchangedOrModified(): bool; + } + interface EntityState extends BreezeCore.IEnum { + Added: EntityStateSymbol; + Deleted: EntityStateSymbol; + Detached: EntityStateSymbol; + Modified: EntityStateSymbol; + Unchanged: EntityStateSymbol; + } + var EntityState: EntityState; + + class EntityType implements IStructuralType { + autoGeneratedKeyType: AutoGeneratedKeyType; + complexProperties: DataProperty[]; + concurrencyProperties: DataProperty[]; + dataProperties: DataProperty[]; + defaultResourceName: string; + foreignKeyProperties: DataProperty[]; + keyProperties: DataProperty[]; + metadataStore: MetadataStore; + name: string; + namespace: string; + navigationProperties: NavigationProperty[]; + shortName: string; + unmappedProperties: DataProperty[]; + validators: Validator[]; + + constructor (config: MetadataStore); + constructor (config: EntityTypeOptions); + + addProperty(property: IProperty): void; + addValidator(validator: Validator, property?: IProperty): void; + createEntity(initialValues?: Object): Entity; + getDataProperty(propertyName: string): DataProperty; + getEntityCtor(): Function; + getNavigationProperty(propertyName: string): NavigationProperty; + getProperties(): IProperty[]; + getProperty(propertyPath: string, throwIfNotFound?: bool): IProperty; + getPropertyNames(): string[]; + setProperties(config: EntityTypeProperties): void; + toString(): string; + } + + interface EntityTypeOptions { + shortName?: string; + namespace?: string; + autogeneratedKeyType?: AutoGeneratedKeyType; + defaultResourceName?: string; + } + + interface EntityTypeProperties { + autogeneratedKeyType?: AutoGeneratedKeyType; + defaultResourceName?: string; + } + + class FetchStrategySymbol extends BreezeCore.EnumSymbol { + } + interface FetchStrategy extends BreezeCore.IEnum { + FromLocalCache: FetchStrategySymbol; + FromServer: FetchStrategySymbol; + } + var FetchStrategy: FetchStrategy; + + class FilterQueryOpSymbol extends BreezeCore.EnumSymbol { + } + interface FilterQueryOp extends BreezeCore.IEnum { + Contains: FilterQueryOpSymbol; + EndsWith: FilterQueryOpSymbol; + Equals: FilterQueryOpSymbol; + GreaterThan: FilterQueryOpSymbol; + GreaterThanOrEqual: FilterQueryOpSymbol; + LessThan: FilterQueryOpSymbol; + LessThanOrEqual: FilterQueryOpSymbol; + NotEquals: FilterQueryOpSymbol; + StartsWith: FilterQueryOpSymbol; + } + var FilterQueryOp: FilterQueryOp; + + class LocalQueryComparisonOptions { + static caseInsensitiveSQL: LocalQueryComparisonOptions; + static defaultInstance: LocalQueryComparisonOptions; + + constructor (config: { name?: string; isCaseSensitive?: bool; usesSql92CompliantStringComparison?: bool; }); + + setAsDefault(): void; + } + + class MergeStrategySymbol extends BreezeCore.EnumSymbol { + } + interface MergeStrategy extends BreezeCore.IEnum { + OverwriteChanges: MergeStrategySymbol; + PreserveChanges: MergeStrategySymbol; + } + var MergeStrategy: MergeStrategy; + + class MetadataStore { + namingConvention: NamingConvention; + + constructor (config?: MetadataStoreOptions); + addDataService(dataService: DataService): void; + addEntityType(structuralType: IStructuralType): void; + exportMetadata(): string; + fetchMetadata(dataService: string, callback?: (data) => void , errorCallback?: BreezeCore.ErrorCallback): Promise; + fetchMetadata(dataService: DataService, callback?: (data) => void , errorCallback?: BreezeCore.ErrorCallback): Promise; + getDataService(serviceName: string): DataService; + getEntityType(entityTypeName: string, okIfNotFound?: bool): IStructuralType; + getEntityTypes(): IStructuralType[]; + hasMetadataFor(serviceName: string): bool; + static importMetadata(exportedString: string): MetadataStore; + importMetadata(exportedString: string): MetadataStore; + isEmpty(): bool; + registerEntityTypeCtor(entityTypeName: string, entityCtor: Function, initializationFn?: (entity: Entity) =>void ): void; + trackUnmappedType(entityCtor: Function, interceptor?: Function); + } + + interface MetadataStoreOptions { + namingConvention?: NamingConvention; + localQueryComparisonOptions?: LocalQueryComparisonOptions; + } + + class NamingConvention { + static camelCase: NamingConvention; + static defaultInstance: NamingConvention; + static none: NamingConvention; + + constructor (config: NamingConventionOptions); + + clientPropertyNameToServer(clientPropertyName: string): string; + clientPropertyNameToServer(clientPropertyName: string, property: IProperty): string; + + serverPropertyNameToClient(serverPropertyName: string): string; + serverPropertyNameToClient(serverPropertyName: string, property: IProperty): string; + + setAsDefault(); + } + + interface NamingConventionOptions { + serverPropertyNameToClient?: (name: string) => string; + clientPropertyNameToServer?: (name: string) => string; + } + + class NavigationProperty implements IProperty { + associationName: string; + entityType: EntityType; + foreignKeyNames: string[]; + inverse: NavigationProperty; + isDataProperty: bool; + isNavigationProperty: bool; + isScalar: bool; + name: string; + parentEntityType: EntityType; + relatedDataProperties: DataProperty[]; + validators: Validator[]; + + constructor (config: NavigationPropertyOptions); + } + + interface NavigationPropertyOptions { + name?: string; + nameOnServer?: string; + entityTypeName: string; + isScalar?: bool; + associationName?: string; + foreignKeyNames?: string[]; + foreignKeyNamesOnServer?: string[]; + validators?: Validator[]; + } + + class Predicate { + constructor (property: string, operator: string, value: any, valueIsLiteral?: bool); + constructor (property: string, operator: FilterQueryOpSymbol, value: any, valueIsLiteral?: bool); + + and: PredicateMethod; + static and: PredicateMethod; + + static create: PredicateMethod; + + static isPredicate(o: any): bool; + + static not(predicate: Predicate): Predicate; + not(): Predicate; + + static or: PredicateMethod; + or: PredicateMethod; + + toFunction(): Function; + toString(): string; + validate(entityType: EntityType): void; + } + + interface PredicateMethod { + (predicates: Predicate[]): Predicate; + (...predicates: Predicate[]): Predicate; + (property: string, operator: string, value: any, valueIsLiteral?: bool): Predicate; + (property: string, operator: FilterQueryOpSymbol, value: any, valueIsLiteral?: bool): Predicate; + } + + class Promise { + fail(errorCallback: Function): Promise; + fin(finallyCallback: Function): Promise; + then(callback: Function): Promise; + } + + class QueryOptions { + static defaultInstance: QueryOptions; + fetchStrategy: FetchStrategySymbol; + mergeStrategy: MergeStrategySymbol; + + constructor (config?: QueryOptionsConfiguration); + + setAsDefault(): void; + using(config: QueryOptionsConfiguration): QueryOptions; + using(config: MergeStrategySymbol): QueryOptions; + using(config: FetchStrategySymbol): QueryOptions; + } + + interface QueryOptionsConfiguration { + fetchStrategy?: FetchStrategySymbol; + mergeStrategy?: MergeStrategySymbol; + } + + class SaveOptions { + allowConcurrentSaves: bool; + static defaultInstance: SaveOptions; + + constructor (config?: { allowConcurrentSaves?: bool; }); + + setAsDefault(): SaveOptions; + } + + class ValidationError { + context: any; + errorMessage: string; + property: IProperty; + propertyName: string; + validator: Validator; + + constructor (validator: Validator, context: any, errorMessage: string); + } + + class ValidationOptions { + static defaultInstance: ValidationOptions; + validateOnAttach: bool; + validateOnPropertyChange: bool; + validateOnQuery: bool; + validateOnSave: bool; + + constructor (config?: ValidationOptionsConfiguration); + + setAsDefault(): ValidationOptions; + using(config: ValidationOptionsConfiguration): ValidationOptions; + } + + interface ValidationOptionsConfiguration { + validateOnAttach?: bool; + validateOnSave?: bool; + validateOnQuery?: bool; + validateOnPropertyChange?: bool; + } + + class Validator { + static messageTemplates: any; + + constructor (name: string, validatorFn: ValidatorFunction, context?: any); + + static bool(): Validator; + static byte(): Validator; + static date(): Validator; + static duration(): Validator; + getMessage(): string; + static guid(): Validator; + static int16(): Validator; + static int32(): Validator; + static int64(): Validator; + static maxLength(context: { maxLength: number; }): Validator; + static number(): Validator; + static required(): Validator; + static string(): Validator; + static stringLength(context: { maxLength: number; minLength: number; }): Validator; + validate(value: any, context?: any): ValidationError; + } + + interface ValidatorFunction { + (value: any, context: ValidatorFunctionContext): void; + } + + interface ValidatorFunctionContext { + value: any; + validatorName: string; + displayName: string; + messageTemplate: string; + message?: string; + } +} diff --git a/breeze/breeze-tests.ts b/breeze/breeze-tests.ts index 06a50b3fcb..4275475742 100644 --- a/breeze/breeze-tests.ts +++ b/breeze/breeze-tests.ts @@ -1,7 +1,6 @@ /// -import breeze = module(Breeze); -import core = module(BreezeCore); +import core = module(breezeCore); function test_dataType() { var typ = breeze.DataType.DateTime; @@ -9,9 +8,10 @@ function test_dataType() { var isNumber = typ.isNumeric; var dv = typ.defaultValue; var symbs = breeze.DataType.getSymbols(); - var x = typ.parentEnum === breeze.DataType; + var x = typ.parentEnum === breeze.DataType; var isFalse = breeze.DataType.contains(breeze.DataType.Double); var dt = breeze.DataType.fromName("Decimal"); + } function test_dataProperty() { @@ -33,6 +33,7 @@ function test_dataService() { var em = new breeze.EntityManager({ dataService: ds }); + } function test_entityAspect() { @@ -125,12 +126,13 @@ function test_metadataStore() { function test_entityManager() { var entityManager = new breeze.EntityManager("api/NorthwindIBModel"); - var entityManager = new breeze.EntityManager({ serviceName: "api/NorthwindIBModel" }); + var em1 = new breeze.EntityManager({ serviceName: "api/NorthwindIBModel" }); var metadataStore = new breeze.MetadataStore(); var entityManager = new breeze.EntityManager({ serviceName: "api/NorthwindIBModel", metadataStore: metadataStore }); + return new breeze.QueryOptions({ mergeStrategy: null, fetchStrategy: this.fetchStrategy @@ -152,6 +154,10 @@ function test_entityManager() { var custType = em1.metadataStore.getEntityType("Customer"); var cust1 = custType.createEntity(); em1.addEntity(cust1); + + var cust2 = em1.createEntity("Customer", { companyName: "foo" }); + var cust3 = em1.createEntity("foo", { xxx: 3 }, breeze.EntityState.Added); + em1.attachEntity(cust1, breeze.EntityState.Added); em1.clear(); var em2 = em1.createEmptyCopy(); @@ -239,7 +245,8 @@ function test_entityManager() { if (em1.hasChanges(custType)) { } var custType = em1.metadataStore.getEntityType("Customer"); var orderType = em1.metadataStore.getEntityType("Order"); - if (em1.hasChanges([custType, orderType])) { } + if (em1.hasChanges([custType, orderType])) { }; + var bundle = em1.exportEntities(); window.localStorage.setItem("myEntityManager", bundle); var bundleFromStorage = window.localStorage.getItem("myEntityManager"); @@ -279,10 +286,10 @@ function test_entityManager() { var entity = changeArgs.entity; }); var em = new breeze.EntityManager({ serviceName: "api/NorthwindIBModel" }); - //em.hasChanges.subscribe(function (args) { - // var hasChanges = args.hasChanges; - // var entityManager = args.entityManager; - //}); + em.hasChangesChanged.subscribe(function (args) { + var hasChanges = args.hasChanges; + var entityManager = args.entityManager; + }); } function test_entityQuery() { @@ -377,6 +384,8 @@ function test_entityQuery() { var em = new breeze.EntityManager(serviceName); var query = new breeze.EntityQuery("Orders") .using(breeze.FetchStrategy.FromLocalCache); + var adapter = new breeze.JsonResultsAdapter({ name: "foo", visitNode: function (x) { return x; } }); + var q2 = query.using(adapter); var query = new breeze.EntityQuery("Customers") .where("CompanyName", "startsWith", "C"); var query = new breeze.EntityQuery("Customers") @@ -393,6 +402,7 @@ function test_entityQuery() { .where("toLower(CompanyName)", "startsWith", "c"); var query = new breeze.EntityQuery("Customers") .where("toUpper(substring(CompanyName, 1, 2))", breeze.FilterQueryOp.Equals, "OM"); + var q2 = query.toType("foo").orderBy("foo2"); } function test_entityState() { diff --git a/breeze/breeze.d.ts b/breeze/breeze.d.ts index da8f043772..3f45329759 100644 --- a/breeze/breeze.d.ts +++ b/breeze/breeze.d.ts @@ -1,12 +1,13 @@ -// Type definitions for Breeze 1.0 +// Type definitions for Breeze 1.2.7 // Project: http://www.breezejs.com/ -// Definitions by: Boris Yankov -// Definitions: https://github.com/borisyankov/DefinitelyTyped +// Definitions by: Boris Yankov , +// IdeaBlade +// Definitions: https://github.com/borisyankov/DefinitelyTyped -// Updated Jan 14 2011 - Jay Traband (www.ideablade.com) +// Updated March 27 2013 - John Lantz (www.ideablade.com) -declare module BreezeCore { +declare module breezeCore { interface ErrorCallback { (error: Error): void; @@ -53,7 +54,7 @@ declare module BreezeCore { } } -declare module Breeze { +declare module breeze { interface Entity { entityAspect: EntityAspect; @@ -151,6 +152,7 @@ declare module Breeze { adapterName: string; hasServerMetadata: bool; serviceName: string; + jsonResultsAdapter: JsonResultsAdapter; constructor(config: DataServiceOptions); } @@ -158,13 +160,38 @@ declare module Breeze { adapterName?: string; hasServerMetadata?: bool; serviceName?: string; + jsonResultsAdapter?: JsonResultsAdapter; } - class DataTypeSymbol extends BreezeCore.EnumSymbol { + class JsonResultsAdapter { + name: string; + extractResults: (data: {}) => {}; + visitNode: (node: {}, queryContext: QueryContext, nodeContext: NodeContext) => { entityType?: EntityType; nodeId?: any; nodeRefId?: any; ignore?: bool; }; + constructor(config: { + name: string; + extractResults?: (data: {}) => {}; + visitNode: (node: {}, queryContext: QueryContext, nodeContext: NodeContext) => { entityType?: EntityType; nodeId?: any; nodeRefId?: any; ignore?: bool; }; + }); + } + + interface QueryContext { + query: any; // how to also say it could be an EntityQuery or a string + entityManager: EntityManager; + jsonResultsAdapter: JsonResultsAdapter; + mergeStrategy: MergeStrategy; + } + + interface NodeContext { + nodeType: string; + } + + + + class DataTypeSymbol extends breezeCore.EnumSymbol { defaultValue: any; isNumeric: bool; } - interface DataType extends BreezeCore.IEnum { + interface DataType extends breezeCore.IEnum { Binary: DataTypeSymbol; Boolean: DataTypeSymbol; Byte: DataTypeSymbol; @@ -185,9 +212,9 @@ declare module Breeze { } declare var DataType: DataType; - class EntityActionSymbol extends BreezeCore.EnumSymbol { + class EntityActionSymbol extends breezeCore.EnumSymbol { } - interface EntityAction extends BreezeCore.IEnum { + interface EntityAction extends breezeCore.IEnum { AcceptChanges: EntityActionSymbol; Attach: EntityActionSymbol; AttachOnImport: EntityActionSymbol; @@ -248,7 +275,7 @@ declare module Breeze { newValue: any; } - class PropertyChangedEvent extends BreezeCore.Event { + class PropertyChangedEvent extends breezeCore.Event { subscribe(callback?: (data: PropertyChangedEventArgs) => void ): number; } @@ -258,7 +285,7 @@ declare module Breeze { removed: ValidationError[]; } - class ValidationErrorsChangedEvent extends BreezeCore.Event { + class ValidationErrorsChangedEvent extends breezeCore.Event { subscribe(callback?: (data: ValidationErrorsChangedEventArgs) => void ): number; } @@ -280,7 +307,7 @@ declare module Breeze { validationOptions: ValidationOptions; entityChanged: EntityChangedEvent; - // hasChanges: BreezeCore.Event; + hasChangesChanged: HasChangesChangedEvent; constructor (config?: EntityManagerOptions); constructor (config?: string); @@ -289,17 +316,17 @@ declare module Breeze { attachEntity(entity: Entity, entityState?: EntityStateSymbol): Entity; clear(): void; createEmptyCopy(): EntityManager; + createEntity(typeName: string, config?: {}, entityState?: EntityStateSymbol) : Entity; detachEntity(entity: Entity): bool; - executeQuery(query: string, callback?: ExecuteQuerySuccessCallback, errorCallback?: ExecuteQueryErrorCallback): Promise; executeQuery(query: EntityQuery, callback?: ExecuteQuerySuccessCallback, errorCallback?: ExecuteQueryErrorCallback): Promise; executeQueryLocally(query: EntityQuery): Entity[]; exportEntities(entities?: Entity[]): string; - fetchEntityByKey(typeName: string, keyValue: any, checkLocalCacheFirst?: bool): Entity; - fetchEntityByKey(typeName: string, keyValues: any[], checkLocalCacheFirst?: bool): Entity; - fetchEntityByKey(entityKey: EntityKey): Entity; - fetchMetadata(callback?: (schema: any) => void , errorCallback?: BreezeCore.ErrorCallback): Promise; + fetchEntityByKey(typeName: string, keyValue: any, checkLocalCacheFirst?: bool): Promise; + fetchEntityByKey(typeName: string, keyValues: any[], checkLocalCacheFirst?: bool): Promise; + fetchEntityByKey(entityKey: EntityKey): Promise; + fetchMetadata(callback?: (schema: any) => void , errorCallback?: breezeCore.ErrorCallback): Promise; generateTempKeyValue(entity: Entity): any; getChanges(): Entity[]; getChanges(entityTypeName: string): Entity[]; @@ -376,10 +403,19 @@ declare module Breeze { args: Object; } - class EntityChangedEvent extends BreezeCore.Event { + class EntityChangedEvent extends breezeCore.Event { subscribe(callback?: (data: EntityChangedEventArgs) => void ): number; } + class HasChangesChangedEventArgs { + entityManager: EntityManager; + hasChanges: bool; + } + + class HasChangesChangedEvent extends breezeCore.Event { + subscribe(callback?: (data: HasChangesChangedEventArgs) => void ): number; + } + class EntityQuery { entityManager: EntityManager; orderByClause: OrderByClause; @@ -412,10 +448,13 @@ declare module Breeze { skip(count: number): EntityQuery; take(count: number): EntityQuery; top(count: number): EntityQuery; + toType(typeName: string): EntityQuery; + toType(type: EntityType): EntityQuery; using(obj: EntityManager): EntityQuery; using(obj: MergeStrategySymbol): EntityQuery; - using(obj: FetchStrategySymbol): EntityQuery; + using(obj: FetchStrategySymbol): EntityQuery; + using(obj: JsonResultsAdapter): EntityQuery; where(predicate: Predicate): EntityQuery; where(property: string, operator: string, value: any): EntityQuery; @@ -427,7 +466,7 @@ declare module Breeze { interface OrderByClause { } - class EntityStateSymbol extends BreezeCore.EnumSymbol { + class EntityStateSymbol extends breezeCore.EnumSymbol { isAdded(): bool; isAddedModifiedOrDeleted(): bool; isDeleted(): bool; @@ -436,7 +475,7 @@ declare module Breeze { isUnchanged(): bool; isUnchangedOrModified(): bool; } - interface EntityState extends BreezeCore.IEnum { + interface EntityState extends breezeCore.IEnum { Added: EntityStateSymbol; Deleted: EntityStateSymbol; Detached: EntityStateSymbol; @@ -489,17 +528,17 @@ declare module Breeze { defaultResourceName?: string; } - class FetchStrategySymbol extends BreezeCore.EnumSymbol { + class FetchStrategySymbol extends breezeCore.EnumSymbol { } - interface FetchStrategy extends BreezeCore.IEnum { + interface FetchStrategy extends breezeCore.IEnum { FromLocalCache: FetchStrategySymbol; FromServer: FetchStrategySymbol; } var FetchStrategy: FetchStrategy; - class FilterQueryOpSymbol extends BreezeCore.EnumSymbol { + class FilterQueryOpSymbol extends breezeCore.EnumSymbol { } - interface FilterQueryOp extends BreezeCore.IEnum { + interface FilterQueryOp extends breezeCore.IEnum { Contains: FilterQueryOpSymbol; EndsWith: FilterQueryOpSymbol; Equals: FilterQueryOpSymbol; @@ -521,9 +560,9 @@ declare module Breeze { setAsDefault(): void; } - class MergeStrategySymbol extends BreezeCore.EnumSymbol { + class MergeStrategySymbol extends breezeCore.EnumSymbol { } - interface MergeStrategy extends BreezeCore.IEnum { + interface MergeStrategy extends breezeCore.IEnum { OverwriteChanges: MergeStrategySymbol; PreserveChanges: MergeStrategySymbol; } @@ -536,8 +575,8 @@ declare module Breeze { addDataService(dataService: DataService): void; addEntityType(structuralType: IStructuralType): void; exportMetadata(): string; - fetchMetadata(dataService: string, callback?: (data) => void , errorCallback?: BreezeCore.ErrorCallback): Promise; - fetchMetadata(dataService: DataService, callback?: (data) => void , errorCallback?: BreezeCore.ErrorCallback): Promise; + fetchMetadata(dataService: string, callback?: (data) => void , errorCallback?: breezeCore.ErrorCallback): Promise; + fetchMetadata(dataService: DataService, callback?: (data) => void , errorCallback?: breezeCore.ErrorCallback): Promise; getDataService(serviceName: string): DataService; getEntityType(entityTypeName: string, okIfNotFound?: bool): IStructuralType; getEntityTypes(): IStructuralType[]; diff --git a/casperjs/casperjs.d.ts b/casperjs/casperjs.d.ts new file mode 100644 index 0000000000..b1f7550225 --- /dev/null +++ b/casperjs/casperjs.d.ts @@ -0,0 +1,267 @@ +// Type definitions for CasperJS v1.0.0 API +// Project: http://casperjs.org/ +// Definitions by: Jed Hunsaker +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface Casper { + + constructor (options: CasperOptions); + + // Properties + __utils__: ClientUtils; + + // Methods + back(); + base64encode(url: string, method?: string, data?: any); + click(selector: string); + clickLabel(label: string, tag?: string); + capture(targetFilePath: string, clipRect: ClipRect); + captureBase64(format: string); + captureBase64(format: string, area: string); + captureBase64(format: string, area: ClipRect); + captureBase64(format: string, area: any); + captureSelector(targetFile: string, selector: string); + clear(); + debugHTML(selector?: string, outer?: bool); + debugPage(); + die(message: string, status?: number); + download(url: string, target?: string, method?: string, data?: any); + each(array: Array, fn: (self, link) => void); + echo(message: string, style?: string); + evaluate(fn: Function, ...args: any[]); + evaluateOrDie(fn: Function, message?: string); + exit(status?: number); + exists(selector: string); + fetchText(selector: string); + forward(); + log(message: string, level?: string, space?: string); + fill(selector: string, values: any, submit?: bool); + getCurrentUrl(): string; + getElementAttribute(selector: string, attribute: string): string; + getElementBounds(selector: string): ElementBounds; + getElementsBounds(selector: string): ElementBounds[]; + getElementInfo(selector: string): ElementInfo; + getFormValues(selector: string): any; + getGlobal(name: string): any; + getHTML(selector?: string, outer?: bool): string; + getPageContent(): string; + getTitle(): string; + mouseEvent(type: string, selector: string); + open(location: string, settings: OpenSettings): Casper; + reload(then?: (response: HttpResponse) => void); + repeat(times: number, then: Function); + resourceExists(test: Function); + resourceExists(test: string); + run(onComplete: Function, time?: number); + sendKeys(selector: string, keys: string, options?: any); + setHttpAuth(username: string, password: string); + start(url?: string, then?: (response: HttpResponse) => void): Casper; + status(asString: bool): any; + then(fn: (self?: Casper) => void); + thenClick(selector: string); + thenEvaluate(fn: Function, ...args: any[]); + thenOpen(location: string, then?: (response: HttpResponse) => void); + thenOpen(location: string, options?: OpenSettings, then?: (response: HttpResponse) => void); + thenOpenAndEvaluate(location: string, then?: Function, ...args: any[]); + toString(); + userAgent(agent: string); + viewport(width: number, height: number); + visible(selector: string); + wait(timeout: number, then?: Function); + waitFor(testFx: Function, then?: Function, onTimeout?: Function, timeout?: number); + waitForPopup(urlPattern: string, then?: Function, onTimeout?: Function, timeout?: number); + waitForPopup(urlPattern: RegExp, then?: Function, onTimeout?: Function, timeout?: number); + waitForSelector(selector: string, then?: Function, onTimeout?: Function, timeout?: number); + waitWhileSelector(selector: string, then?: Function, onTimeout?: Function, timeout?: number); + waitForResource(testFx: Function, then?: Function, onTimeout?: Function, timeout?: number); + waitForText(pattern: string, then?: Function, onTimeout?: Function, timeout?: number); + waitForText(pattern: RegExp, then?: Function, onTimeout?: Function, timeout?: number); + waitUntilVisible(selector: string, then?: Function, onTimeout?: Function, timeout?: number); + waitWhileVisible(selector: string, then?: Function, onTimeout?: Function, timeout?: number); + warn(message: string); + withFrame(frameInfo: string, then: Function); + withFrame(frameInfo: number, then: Function); + withPopup(popupInfo: string, step: Function); + withPopup(popupInfo: RegExp, step: Function); + zoom(factor: number); +} + +interface HttpResponse { + contentType: string; + headers: any[]; + id: number; + redirectURL: string; + stage: string; + status: number; + statusText: string; + time: string; + url: string; +} + +interface OpenSettings { + method: string; + data: any; + headers: any; +} + +interface ElementBounds { + top: number; + left: number; + width: number; + height: number; +} + +interface ElementInfo { + nodeName: string; + attributes: any; + tag: string; + html: string; + text: string; + x: number; + y: number; + width: number; + height: number; + visible: bool; +} + +interface CasperOptions { + clientScripts: Array; + exitOnError: bool; + httpStatusHandlers: any; + logLevel: string; + onAlert: Function; + onDie: Function; + onError: Function; + onLoadError: Function; + onPageInitialized: Function; + onResourceReceived: Function; + onResourceRequested: Function; + onStepComplete: Function; + onStepTimeout: Function; + onTimeout: Function; + onWaitTimeout: Function; + page: WebPage; + pageSettings: any; + remoteScripts: Array; + safeLogs: bool; + stepTimeout: number; + timeout: number; + verbose: bool; + viewportSize: any; + waitTimeout: number; +} + +interface ClientUtils { + echo(message: string); + encode(contents: string); + exists(selector: string); + findAll(selector: string); + findOne(selector: string); + getBase64(url: string, method?: string, data?: any); + getBinary(url: string, method?: string, data?: any); + getDocumentHeight(); + getElementBounds(selector: string); + getElementsBounds(selector: string); + getElementByXPath(expression: string, scope?: HTMLElement); + getElementsByXPath(expression: string, scope?: HTMLElement); + getFieldValue(inputName: string); + getFormValues(selector: string); + mouseEvent(type: string, selector: string); + removeElementsByXPath(expression: string); + sendAJAX(url: string, method?: string, data?: any, async?: bool); + visible(selector: string); +} + +interface Colorizer { + colorize(text: string, styleName: string); + format(text: string, style: any); +} + +interface Tester { + assert(condition: bool, message?: string); + assertDoesntExist(selector: string, message?: string); + assertEquals(testValue: any, expected: any, message?: string); + assertEval(fn: Function, message: string, arguments: any); + assertEvalEquals(fn: Function, expected: any, message?: string, arguments?: any); + assertExists(selector: string, message?: string); + assertFalsy(subject: any, message?: string); + assertField(inputName: string, expected: string, message?: string); + assertHttpStatus(status: number, message?: string); + assertMatch(subject: any, pattern: RegExp, message?: string); + assertNot(subject: any, message?: string); + assertNotEquals(testValue: any, expected: any, message?: string); + assertNotVisible(selector: string, message?: string); + assertRaises(fn: Function, args: Array, message?: string); + assertSelectorDoesntHaveText(selector: string, text: string, message?: string); + assertSelectorExists(selector: string, message?: string); + assertSelectorHasText(selector: string, text: string, message?: string); + assertResourceExists(testFx: Function, message?: string); + assertTextExists(expected: string, message?: string); + assertTextDoesntExist(unexpected: string, message: string); + assertTitle(expected: string, message?: string); + assertTitleMatch(pattern: RegExp, message?: string); + assertTruthy(subject: any, message?: string); + assertType(input: any, type: string, message?: string); + assertUrlMatch(pattern: RegExp, message?: string); + assertVisible(selector: string, message?: string); + colorize(message: string, style: string); + comment(message: string); + done(expected?: number); + error(message: string); + fail(message: string); + formatMessage(message: string, style: string); + getFailures(): Cases; + getPasses(): Cases; + info(message: string); + pass(message: string); + renderResults(exit: bool, status: number, save: string); +} + +interface Cases { + length: number; + cases: Case[]; +} + +interface Case { + success: bool; + type: string; + standard: string; + file: string; + values: CaseValues; +} + +interface CaseValues { + subject: bool; + expected: bool; +} + +interface Utils { + betterTypeOf(input: any); + dump(value: any); + fileExt(file: string); + fillBlanks(text: string, pad: number); + format(f: string, ...args: any[]); + getPropertyPath(obj: any, path: string); + inherits(ctor: any, superCtor: any); + isArray(value: any); + isCasperObject(value: any); + isClipRect(value: any); + isFalsy(subject: any); + isFunction(value: any); + isJsFile(file: string); + isNull(value: any); + isNumber(value: any); + isObject(value: any); + isRegExp(value: any); + isString(value: any); + isTruthy(subject: any); + isType(what: any, type: string); + isUndefined(value: any); + isWebPage(what: any); + mergeObjects(origin: any, add: any); + node(name: string, attributes: any); + serialize(value: any); + unique(array: Array); +} diff --git a/cheerio/cheerio.d.ts b/cheerio/cheerio.d.ts index d3416a74f8..cbf9e12daf 100644 --- a/cheerio/cheerio.d.ts +++ b/cheerio/cheerio.d.ts @@ -1,75 +1,81 @@ -declare interface Cheerio { - - addClass(classNames: string): Cheerio; - hasClass(className: string): bool; - removeClass(className?: any): Cheerio; - - attr(attributeName: string, value: any): Cheerio; - attr(attributeName: string): string; - removeAttr(attributeName: any): Cheerio; - - find(selector: string): Cheerio; - - parent(): Cheerio; - - next(): Cheerio; - prev(): Cheerio; - - siblings(): Cheerio; - - children(selector?: any): Cheerio; - - each(func: (index: any, elem: any) => Cheerio); - - map(callback: (index: any, domElement: Element) =>any): Cheerio; - - filter(selector: string): Cheerio; - filter(func: (index: any) =>any): Cheerio; - - first(): Cheerio; - last(): Cheerio; - - eq(index: number): Cheerio; - - append(...content: any[]): Cheerio; - prepend(...content: any[]): Cheerio; - after(...content: any[]): Cheerio; - before(...content: any[]): Cheerio; - remove(selector: string): Cheerio; - replaceWith(content: string): Cheerio; - empty(): Cheerio; - - html(htmlString: string): Cheerio; - html(): string; - - text(textString: string): Cheerio; - text(): string; - - toArray(): any[]; - - clone() : Cheerio; - root() : Cheerio; - dom(): any; - - contains(container: Element, contained: Element): bool; - isArray(obj: any): bool; - inArray(value: any, array: any[], fromIndex?: number): number; - merge(first: any[], second: any[]): any[]; - - -} - -declare interface CheerioOptionsInterface { - ignoreWhitespace?: bool; - xmlMode?: bool; - lowerCaseTags?: bool; -} - -declare interface CheerioStatic { - (...selectors: any[]): Cheerio; - (): Cheerio; -} - -declare module "cheerio" { - export function load (html : string, options?: CheerioOptionsInterface) : CheerioStatic; -} +// Type definitions for Cheerio +// Project: https://github.com/MatthewMueller/cheerio +// Definitions by: Bret Little +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +declare interface Cheerio { + + addClass(classNames: string): Cheerio; + hasClass(className: string): bool; + removeClass(className?: any): Cheerio; + + attr(attributeName: string, value: any): Cheerio; + attr(attributeName: string): string; + removeAttr(attributeName: any): Cheerio; + + find(selector: string): Cheerio; + + parent(): Cheerio; + + next(): Cheerio; + prev(): Cheerio; + + siblings(): Cheerio; + + children(selector?: any): Cheerio; + + each(func: (index: any, elem: any) => Cheerio); + + map(callback: (index: any, domElement: Element) =>any): Cheerio; + + filter(selector: string): Cheerio; + filter(func: (index: any) =>any): Cheerio; + + first(): Cheerio; + last(): Cheerio; + + eq(index: number): Cheerio; + + append(...content: any[]): Cheerio; + prepend(...content: any[]): Cheerio; + after(...content: any[]): Cheerio; + before(...content: any[]): Cheerio; + remove(selector: string): Cheerio; + replaceWith(content: string): Cheerio; + empty(): Cheerio; + + html(htmlString: string): Cheerio; + html(): string; + + text(textString: string): Cheerio; + text(): string; + + toArray(): any[]; + + clone() : Cheerio; + root() : Cheerio; + dom(): any; + + contains(container: Element, contained: Element): bool; + isArray(obj: any): bool; + inArray(value: any, array: any[], fromIndex?: number): number; + merge(first: any[], second: any[]): any[]; + + +} + +declare interface CheerioOptionsInterface { + ignoreWhitespace?: bool; + xmlMode?: bool; + lowerCaseTags?: bool; +} + +declare interface CheerioStatic { + (...selectors: any[]): Cheerio; + (): Cheerio; +} + +declare module "cheerio" { + export function load (html : string, options?: CheerioOptionsInterface) : CheerioStatic; +} diff --git a/commander/commander-tests.ts b/commander/commander-tests.ts new file mode 100644 index 0000000000..e9e99b988f --- /dev/null +++ b/commander/commander-tests.ts @@ -0,0 +1,50 @@ +/// + +// +// TODO: improve tests +// [the code below was extracted from the documentation and examples, but does not seem to cover all cases] +// + +import program = module("commander"); + +program + .version('0.0.1') + .option('-C, --chdir ', 'change the working directory') + .option('-c, --config ', 'set config path [./deploy.conf]') + .option('-T, --no-tests', 'ignore test hook') + +// $ deploy setup stage +// $ deploy setup +program + .command('setup [env]') + .description('run setup commands for all envs') + .action(function (env) { + env = env || 'all'; + console.log('setup for %s env(s)', env); + }); + +// $ deploy stage +// $ deploy production +program + .command('*') + .action(function (env) { + console.log('deploying "%s"', env); + }); + +program.option('-p, --pepper', 'add pepper'); + +program.option('-C, --chdir ', 'change the working directory'); + +program.prompt('Username: ', function (name) { + console.log('hi %s', name); +}); + +program.prompt('Description:', function (desc) { + console.log('description was "%s"', desc.trim()); +}); + +program.promptForNumber("Enter a number:", (n) => { }); + +program.confirm("Confirm? ", (f) => { }); + +program.choose(["a", "b", "c"], (i) => { }); \ No newline at end of file diff --git a/commander/commander.d.ts b/commander/commander.d.ts new file mode 100644 index 0000000000..3413950269 --- /dev/null +++ b/commander/commander.d.ts @@ -0,0 +1,228 @@ +// Type definitions for commanderjs 1.1.1 +// Project: https://github.com/visionmedia/commander.js +// Definitions by: Marcelo Dezem +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "commander" { + export interface Command { + /** + * The command name. + */ + name: string; + + // + // + // NOTE: the methods below are COPIED to the module + // as functions exports. If changes need to be made here, + // remember to re-paste the definitions in the module. + // Read below to know why such ugly thing is required. + // + // + + /** + * Register callback fn for the command. + */ + action(fn: (...args: any[]) => any): Command; + + /** + * Define option with flags, description and optional coercion function and default value. + * The flags string should contain both the short and long flags + * separated by comma, a pipe or space. The following are all valid + * all will output this way when --help is used. + * + * "-p, --pepper" + * "-p|--pepper" + * "-p --pepper" + * + * @param flags the option flags. + * @param description the option description. The description is printed when "--help" is used. + * @param coerceFn (optional) specifies a callback function to coerce the option arg. + * @param defaultValue (optional) specifies a default value. + */ + option(flags: string, description: string, coerceFn?: (value: string) => any, defaultValue?: any): Command; + + + /** + * Sets the command version + */ + version(version: string): Command; + + /** + * Parse the arguments array and invokes the commands passing the parsed options. + * @param argv the arguments array. + */ + parse(argv: string[]): Command; + + /** + * Gets or sets the command description. + * @param description the new description for the command. When ommited this returns the current description, otherwise returns the current Command. + */ + description(description: string): Command; + description(): string; + + /** + * Gets or sets the usage help string. + */ + usage(usage: string): Command; + usage(): string; + + /* + * Prompt the user for a value, calling the callback function. + * + * Supports single-line and multi-line prompts. + * To issue a single-line prompt simply add a whitespace + * to the end of label, something like "name: ", whereas + * for a multi-line prompt omit this "description:". + * @param label the label string to be printed in console. + * @param callback a callback function to handle the inputed string. + */ + prompt(label: string, callback: (value: string) => any): void; + + promptForNumber(label: string, callback: (value: number) => any): void; + promptForDate(label: string, callback: (value: Date) => any): void; + promptSingleLine(label: string, callback: (value: string) => any): void; + promptMultiLine(label: string, callback: (value: string) => any): void; + + /** + * Prompt for password with a label, a optional mask char and callback function. + * The mask string defaults to '', aka no output is written while typing, you may want to use "*" etc. + */ + password(label: string, mask: string, callback: (value: string) => any): void; + password(label: string, callback: (value: string) => any): void; + + /** + * Prompts the user for a confirmation. + */ + confirm(label: string, callback: (flag: bool) => any): void; + + /** + * Prompt for password with str, mask char and callback fn(val). + * The mask string defaults to '', aka no output is written while typing, you may want to use "*" etc. + */ + choose(options: string[], callback: (idx: number) => any): void; + choose(options: any[], callback: (idx: number) => any): void; + + /** + * Add command with the specified name. Returns a new instance of Command. + * + * The .action() callback is invoked when the + * command name is specified via ARGV, + * and the remaining arguments are applied to the + * function for access. + + * When the name is "*" an un-matched command + * will be passed as the first arg, followed by + * the rest of ARGV remaining. + * + * @param name the name of the command. Pass "*" to trap un-matched commands. + */ + command(name: string): Command; + } + + // + // + // since TypeScript (and ECMA6) does not supports module.exports, + // there is no way to set the default Command instance as the module itself. + // It's ugly but the only way is to copy all the methods from Command + // and paste it in the module as functions exports. + // + // + + /** + * Register callback fn for the command. + */ + export function action(fn: (...args: any[]) => any): Command; + + /** + * Define option with flags, description and optional coercion function and default value. + * The flags string should contain both the short and long flags + * separated by comma, a pipe or space. The following are all valid + * all will output this way when --help is used. + * + * "-p, --pepper" + * "-p|--pepper" + * "-p --pepper" + * + * @param flags the option flags. + * @param description the option description. The description is printed when "--help" is used. + * @param coerceFn (optional) specifies a callback function to coerce the option arg. + * @param defaultValue (optional) specifies a default value. + */ + export function option(flags: string, description: string, coerceFn?: (value: string) => any, defaultValue?: any): Command; + + + /** + * Sets the command version + */ + export function version(version: string): Command; + + /** + * Parse the arguments array and invokes the commands passing the parsed options. + * @param argv the arguments array. + */ + export function parse(argv: string[]): Command; + + /** + * Gets or sets the command description. + * @param description the new description for the command. When ommited this returns the current description, otherwise returns the current Command. + */ + export function description(description: string): Command; + export function description(): string; + + /** + * Gets or sets the usage help string. + */ + export function usage(usage: string): Command; + export function usage(): string; + + /* + * Prompt the user for a value, calling the callback function. + * + * Supports single-line and multi-line prompts. + * To issue a single-line prompt simply add a whitespace + * to the end of label, something like "name: ", whereas + * for a multi-line prompt omit this "description:". + * @param label the label string to be printed in console. + * @param callback a callback function to handle the inputed string. + */ + export function prompt(label: string, callback: (value: string) => any): void; + + export function promptForNumber(label: string, callback: (value: number) => any): void; + export function promptForDate(label: string, callback: (value: Date) => any): void; + export function promptSingleLine(label: string, callback: (value: string) => any): void; + export function promptMultiLine(label: string, callback: (value: string) => any): void; + /** + * Prompt for password with a label, a optional mask char and callback function. + * The mask string defaults to '', aka no output is written while typing, you may want to use "*" etc. + */ + export function password(label: string, mask: string, callback: (value: string) => any): void; + export function password(label: string, callback: (value: string) => any): void; + + /** + * Prompts the user for a confirmation. + */ + export function confirm(label: string, callback: (flag: bool) => any): void; + + /** + * Prompt for password with str, mask char and callback fn(val). + * The mask string defaults to '', aka no output is written while typing, you may want to use "*" etc. + */ + export function choose(options: string[], callback: (idx: number) => any): void; + export function choose(options: any[], callback: (idx: number) => any): void; + + /** + * Add command with the specified name. Returns a new instance of Command. + * + * The .action() callback is invoked when the + * command name is specified via ARGV, + * and the remaining arguments are applied to the + * function for access. + + * When the name is "*" an un-matched command + * will be passed as the first arg, followed by + * the rest of ARGV remaining. + * + * @param name the name of the command. Pass "*" to trap un-matched commands. + */ + export function command(name: string): Command; +} \ No newline at end of file diff --git a/d3/d3-tests.ts b/d3/d3-tests.ts index 5990b92d8a..1581cdb71b 100644 --- a/d3/d3-tests.ts +++ b/d3/d3-tests.ts @@ -1,29 +1,731 @@ -/// - -d3.selectAll("p").style("color", "white"); -d3.select("body").style("background-color", "black"); -d3.selectAll("p").style("color", function () { - return "hsl(" + Math.random() * 360 + ",100%,50%)"; -}); -d3.selectAll("p").style("color", function (d, i) { - return i % 2 ? "#fff" : "#eee"; -}); -d3.selectAll("p") - .data([4, 8, 15, 16, 23, 42]) - .style("font-size", function (d) { return d + "px"; }); -d3.select("body").selectAll("p") - .data([4, 8, 15, 16, 23, 42]) - .enter().append("p") - .text(function (d) { return "Im number " + d + "!"; }); -var p = d3.select("body").selectAll("p") - .data([4, 8, 15, 16, 23, 42]) - .text(String); -p.enter().append("p") - .text(String); -p.exit().remove(); -d3.select("body").transition() - .style("background-color", "black"); -d3.selectAll("circle").transition() - .duration(750) - .delay(function (d, i) { return i * 10; }) - .attr("r", function (d) { return Math.sqrt(d * scale); }); \ No newline at end of file +/// + +//Example from http://bl.ocks.org/3887235 +function testPieChart() { + var width = 960, + height = 500, + radius = Math.min(width, height) / 2; + + var color = d3.scale.ordinal() + .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]); + + var arc = d3.svg.arc() + .outerRadius(radius - 10) + .innerRadius(0); + + var pie = d3.layout.pie() + .sort(null) + .value(function (d) { return d.population; }); + + var svg = d3.select("body").append("svg") + .attr("width", width) + .attr("height", height) + .append("g") + .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")"); + + d3.csv("data.csv", function (error, data) { + + data.forEach(function (d) { + d.population = +d.population; + }); + + var g = svg.selectAll(".arc") + .data(pie(data)) + .enter().append("g") + .attr("class", "arc"); + + g.append("path") + .attr("d", arc) + .style("fill", function (d) { return color(d.data.age); }); + + g.append("text") + .attr("transform", function (d) { return "translate(" + arc.centroid(d) + ")"; }) + .attr("dy", ".35em") + .style("text-anchor", "middle") + .text(function (d) { return d.data.age; }); + + }); +} + +//Example from http://bl.ocks.org/3887051 +function groupedBarChart() => { + var margin = { top: 20, right: 20, bottom: 30, left: 40 }, + width = 960 - margin.left - margin.right, + height = 500 - margin.top - margin.bottom; + + var x0 = d3.scale.ordinal() + .rangeRoundBands([0, width], .1); + + var x1 = d3.scale.ordinal(); + + var y = d3.scale.linear() + .range([height, 0]); + + var color = d3.scale.ordinal() + .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]); + + var xAxis = d3.svg.axis() + .scale(x0) + .orient("bottom"); + + var yAxis = d3.svg.axis() + .scale(y) + .orient("left") + .tickFormat(d3.format(".2s")); + + var svg = d3.select("body").append("svg") + .attr("width", width + margin.left + margin.right) + .attr("height", height + margin.top + margin.bottom) + .append("g") + .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); + + d3.csv("data.csv", function (error, data) { + var ageNames = d3.keys(data[0]).filter(function (key) { return key !== "State"; }); + + data.forEach(function (d) { + d.ages = ageNames.map(function (name) { return { name: name, value: +d[name] }; }); + }); + + x0.domain(data.map(function (d) { return d.State; })); + x1.domain(ageNames).rangeRoundBands([0, x0.rangeBand()]); + y.domain([0, d3.max(data, function (d) { return d3.max(d.ages, function (d) { return d.value; }); })]); + + svg.append("g") + .attr("class", "x axis") + .attr("transform", "translate(0," + height + ")") + .call(xAxis); + + svg.append("g") + .attr("class", "y axis") + .call(yAxis) + .append("text") + .attr("transform", "rotate(-90)") + .attr("y", 6) + .attr("dy", ".71em") + .style("text-anchor", "end") + .text("Population"); + + var state = svg.selectAll(".state") + .data(data) + .enter().append("g") + .attr("class", "g") + .attr("transform", function (d) { return "translate(" + x0(d.State) + ",0)"; }); + + state.selectAll("rect") + .data(function (d) { return d.ages; }) + .enter().append("rect") + .attr("width", x1.rangeBand()) + .attr("x", function (d) { return x1(d.name); }) + .attr("y", function (d) { return y(d.value); }) + .attr("height", function (d) { return height - y(d.value); }) + .style("fill", function (d) { return color(d.name); }); + + var legend = svg.selectAll(".legend") + .data(ageNames.reverse()) + .enter().append("g") + .attr("class", "legend") + .attr("transform", function (d, i) { return "translate(0," + i * 20 + ")"; }); + + legend.append("rect") + .attr("x", width - 18) + .attr("width", 18) + .attr("height", 18) + .style("fill", color); + + legend.append("text") + .attr("x", width - 24) + .attr("y", 9) + .attr("dy", ".35em") + .style("text-anchor", "end") + .text(function (d) { return d; }); + + }); +} + +//Example from http://bl.ocks.org/3886208 +function stackedBarChart() { + var margin = { top: 20, right: 20, bottom: 30, left: 40 }, + width = 960 - margin.left - margin.right, + height = 500 - margin.top - margin.bottom; + + var x = d3.scale.ordinal() + .rangeRoundBands([0, width], .1); + + var y = d3.scale.linear() + .rangeRound([height, 0]); + + var color = d3.scale.ordinal() + .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]); + + var xAxis = d3.svg.axis() + .scale(x) + .orient("bottom"); + + var yAxis = d3.svg.axis() + .scale(y) + .orient("left") + .tickFormat(d3.format(".2s")); + + var svg = d3.select("body").append("svg") + .attr("width", width + margin.left + margin.right) + .attr("height", height + margin.top + margin.bottom) + .append("g") + .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); + + d3.csv("data.csv", function (error, data) { + color.domain(d3.keys(data[0]).filter(function (key) { return key !== "State"; })); + + data.forEach(function (d) { + var y0 = 0; + d.ages = color.domain().map(function (name) { return { name: name, y0: y0, y1: y0 += +d[name] }; }); + d.total = d.ages[d.ages.length - 1].y1; + }); + + data.sort(function (a, b) { return b.total - a.total; }); + + x.domain(data.map(function (d) { return d.State; })); + y.domain([0, d3.max(data, function (d) { return d.total; })]); + + svg.append("g") + .attr("class", "x axis") + .attr("transform", "translate(0," + height + ")") + .call(xAxis); + + svg.append("g") + .attr("class", "y axis") + .call(yAxis) + .append("text") + .attr("transform", "rotate(-90)") + .attr("y", 6) + .attr("dy", ".71em") + .style("text-anchor", "end") + .text("Population"); + + var state = svg.selectAll(".state") + .data(data) + .enter().append("g") + .attr("class", "g") + .attr("transform", function (d) { return "translate(" + x(d.State) + ",0)"; }); + + state.selectAll("rect") + .data(function (d) { return d.ages; }) + .enter().append("rect") + .attr("width", x.rangeBand()) + .attr("y", function (d) { return y(d.y1); }) + .attr("height", function (d) { return y(d.y0) - y(d.y1); }) + .style("fill", function (d) { return color(d.name); }); + + var legend = svg.selectAll(".legend") + .data(color.domain().reverse()) + .enter().append("g") + .attr("class", "legend") + .attr("transform", function (d, i) { return "translate(0," + i * 20 + ")"; }); + + legend.append("rect") + .attr("x", width - 18) + .attr("width", 18) + .attr("height", 18) + .style("fill", color); + + legend.append("text") + .attr("x", width - 24) + .attr("y", 9) + .attr("dy", ".35em") + .style("text-anchor", "end") + .text(function (d) { return d; }); + + }); +} + +// example from http://bl.ocks.org/3886394 +function normalizedBarChart() { + var margin = { top: 20, right: 100, bottom: 30, left: 40 }, + width = 960 - margin.left - margin.right, + height = 500 - margin.top - margin.bottom; + + var x = d3.scale.ordinal() + .rangeRoundBands([0, width], .1); + + var y = d3.scale.linear() + .rangeRound([height, 0]); + + var color = d3.scale.ordinal() + .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]); + + var xAxis = d3.svg.axis() + .scale(x) + .orient("bottom"); + + var yAxis = d3.svg.axis() + .scale(y) + .orient("left") + .tickFormat(d3.format(".0%")); + + var svg = d3.select("body").append("svg") + .attr("width", width + margin.left + margin.right) + .attr("height", height + margin.top + margin.bottom) + .append("g") + .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); + + d3.csv("data.csv", function (error, data) { + color.domain(d3.keys(data[0]).filter(function (key) { return key !== "State"; })); + + data.forEach(function (d) { + var y0 = 0; + d.ages = color.domain().map(function (name) { return { name: name, y0: y0, y1: y0 += +d[name] }; }); + d.ages.forEach(function (d) { d.y0 /= y0; d.y1 /= y0; }); + }); + + data.sort(function (a, b) { return b.ages[0].y1 - a.ages[0].y1; }); + + x.domain(data.map(function (d) { return d.State; })); + + svg.append("g") + .attr("class", "x axis") + .attr("transform", "translate(0," + height + ")") + .call(xAxis); + + svg.append("g") + .attr("class", "y axis") + .call(yAxis); + + var state = svg.selectAll(".state") + .data(data) + .enter().append("g") + .attr("class", "state") + .attr("transform", function (d) { return "translate(" + x(d.State) + ",0)"; }); + + state.selectAll("rect") + .data(function (d) { return d.ages; }) + .enter().append("rect") + .attr("width", x.rangeBand()) + .attr("y", function (d) { return y(d.y1); }) + .attr("height", function (d) { return y(d.y0) - y(d.y1); }) + .style("fill", function (d) { return color(d.name); }); + + var legend = svg.select(".state:last-child").selectAll(".legend") + .data(function (d) { return d.ages; }) + .enter().append("g") + .attr("class", "legend") + .attr("transform", function (d) { return "translate(" + x.rangeBand() / 2 + "," + y((d.y0 + d.y1) / 2) + ")"; }); + + legend.append("line") + .attr("x2", 10); + + legend.append("text") + .attr("x", 13) + .attr("dy", ".35em") + .text(function (d) { return d.name; }); + + }); +} + +// example from http://bl.ocks.org/3885705 +function sortablebarChart() { + var margin = { top: 20, right: 20, bottom: 30, left: 40 }, + width = 960 - margin.left - margin.right, + height = 500 - margin.top - margin.bottom; + + var formatPercent = d3.format(".0%"); + + var x = d3.scale.ordinal() + .rangeRoundBands([0, width], .1, 1); + + var y = d3.scale.linear() + .range([height, 0]); + + var xAxis = d3.svg.axis() + .scale(x) + .orient("bottom"); + + var yAxis = d3.svg.axis() + .scale(y) + .orient("left") + .tickFormat(formatPercent); + + var svg = d3.select("body").append("svg") + .attr("width", width + margin.left + margin.right) + .attr("height", height + margin.top + margin.bottom) + .append("g") + .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); + + d3.tsv("data.tsv", function (error, data) { + + data.forEach(function (d) { + d.frequency = +d.frequency; + }); + + x.domain(data.map(function (d) { return d.letter; })); + y.domain([0, d3.max(data, function (d) { return d.frequency; })]); + + svg.append("g") + .attr("class", "x axis") + .attr("transform", "translate(0," + height + ")") + .call(xAxis); + + svg.append("g") + .attr("class", "y axis") + .call(yAxis) + .append("text") + .attr("transform", "rotate(-90)") + .attr("y", 6) + .attr("dy", ".71em") + .style("text-anchor", "end") + .text("Frequency"); + + svg.selectAll(".bar") + .data(data) + .enter().append("rect") + .attr("class", "bar") + .attr("x", function (d) { return x(d.letter); }) + .attr("width", x.rangeBand()) + .attr("y", function (d) { return y(d.frequency); }) + .attr("height", function (d) { return height - y(d.frequency); }); + + d3.select("input").on("change", change); + + var sortTimeout = setTimeout(function () { + d3.select("input").property("checked", true).each(change); + }, 2000); + + function change() { + clearTimeout(sortTimeout); + + var x0 = x.domain(data.sort(this.checked + ? function (a, b) { return b.frequency - a.frequency; } + : function (a, b) { return d3.ascending(a.letter, b.letter); }) + .map(function (d) { return d.letter; })) + .copy(); + + var transition = svg.transition().duration(750), + delay = function (d, i) { return i * 50; }; + + transition.selectAll(".bar") + .delay(delay) + .attr("x", function (d) { return x0(d.letter); }); + + transition.select(".x.axis") + .call(xAxis) + .selectAll("g") + .delay(delay); + } + }); +} + +//example from http://bl.ocks.org/4063318 +function callenderView() { + var width = 960, + height = 136, + cellSize = 17; // cell size + + var day = d3.time.format("%w"), + week = d3.time.format("%U"), + percent = d3.format(".1%"), + format = d3.time.format("%Y-%m-%d"); + + var color = d3.scale.quantize() + .domain([-.05, .05]) + .range(d3.range(11).map(function (d) { return "q" + d + "-11"; })); + + var svg = d3.select("body").selectAll("svg") + .data(d3.range(1990, 2011)) + .enter().append("svg") + .attr("width", width) + .attr("height", height) + .attr("class", "RdYlGn") + .append("g") + .attr("transform", "translate(" + ((width - cellSize * 53) / 2) + "," + (height - cellSize * 7 - 1) + ")"); + + svg.append("text") + .attr("transform", "translate(-6," + cellSize * 3.5 + ")rotate(-90)") + .style("text-anchor", "middle") + .text(function (d) { return d; }); + + var rect = svg.selectAll(".day") + .data(function (d) { return d3.time.days(new Date(d, 0, 1), new Date(d + 1, 0, 1)); }) + .enter().append("rect") + .attr("class", "day") + .attr("width", cellSize) + .attr("height", cellSize) + .attr("x", function (d) { return parseInt(week(d)) * cellSize; }) + .attr("y", function (d) { return parseInt(day(d)) * cellSize; }) + .datum(format); + + rect.append("title") + .text(function (d) { return d; }); + + svg.selectAll(".month") + .data(function (d) { return d3.time.months(new Date(d, 0, 1), new Date(d + 1, 0, 1)); }) + .enter().append("path") + .attr("class", "month") + .attr("d", monthPath); + + d3.csv("dji.csv", function (error, csv) { + var data = d3.nest() + .key(function (d) { return d.Date; }) + .rollup(function (d) { return (d[0].Close - d[0].Open) / d[0].Open; }) + .map(csv); + + rect.filter(function (d) { return d in data; }) + .attr("class", function (d) { return "day " + color(data[d]); }) + .select("title") + .text(function (d) { return d + ": " + percent(data[d]); }); + }); + + function monthPath(t0) { + var t1 = new Date(t0.getFullYear(), t0.getMonth() + 1, 0), + d0 = +day(t0), w0 = +week(t0), + d1 = +day(t1), w1 = +week(t1); + return "M" + (w0 + 1) * cellSize + "," + d0 * cellSize + + "H" + w0 * cellSize + "V" + 7 * cellSize + + "H" + w1 * cellSize + "V" + (d1 + 1) * cellSize + + "H" + (w1 + 1) * cellSize + "V" + 0 + + "H" + (w0 + 1) * cellSize + "Z"; + } + + d3.select(self.frameElement).style("height", "2910px"); +} + +// example from http://bl.ocks.org/3883245 +function lineChart { + var margin = { top: 20, right: 20, bottom: 30, left: 50 }, + width = 960 - margin.left - margin.right, + height = 500 - margin.top - margin.bottom; + + var parseDate = d3.time.format("%d-%b-%y").parse; + + var x = d3.time.scale() + .range([0, width]); + + var y = d3.scale.linear() + .range([height, 0]); + + var xAxis = d3.svg.axis() + .scale(x) + .orient("bottom"); + + var yAxis = d3.svg.axis() + .scale(y) + .orient("left"); + + var line = d3.svg.line() + .x(function (d) { return x(d.date); }) + .y(function (d) { return y(d.close); }); + + var svg = d3.select("body").append("svg") + .attr("width", width + margin.left + margin.right) + .attr("height", height + margin.top + margin.bottom) + .append("g") + .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); + + d3.tsv("data.tsv", function (error, data) { + data.forEach(function (d) { + d.date = parseDate(d.date); + d.close = +d.close; + }); + + x.domain(d3.extent(data, function (d) { return d.date; })); + y.domain(d3.extent(data, function (d) { return d.close; })); + + svg.append("g") + .attr("class", "x axis") + .attr("transform", "translate(0," + height + ")") + .call(xAxis); + + svg.append("g") + .attr("class", "y axis") + .call(yAxis) + .append("text") + .attr("transform", "rotate(-90)") + .attr("y", 6) + .attr("dy", ".71em") + .style("text-anchor", "end") + .text("Price ($)"); + + svg.append("path") + .datum(data) + .attr("class", "line") + .attr("d", line); + }); +} + +//example from http://bl.ocks.org/3884914 +function bivariateAreaChart { + var margin = { top: 20, right: 20, bottom: 30, left: 50 }, + width = 960 - margin.left - margin.right, + height = 500 - margin.top - margin.bottom; + + var parseDate = d3.time.format("%Y%m%d").parse; + + var x = d3.time.scale() + .range([0, width]); + + var y = d3.scale.linear() + .range([height, 0]); + + var xAxis = d3.svg.axis() + .scale(x) + .orient("bottom"); + + var yAxis = d3.svg.axis() + .scale(y) + .orient("left"); + + var area = d3.svg.area() + .x(function (d) { return x(d.date); }) + .y0(function (d) { return y(d.low); }) + .y1(function (d) { return y(d.high); }); + + var svg = d3.select("body").append("svg") + .attr("width", width + margin.left + margin.right) + .attr("height", height + margin.top + margin.bottom) + .append("g") + .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); + + d3.tsv("data.tsv", function (error, data) { + data.forEach(function (d) { + d.date = parseDate(d.date); + d.low = +d.low; + d.high = +d.high; + }); + + x.domain(d3.extent(data, function (d) { return d.date; })); + y.domain([d3.min(data, function (d) { return d.low; }), d3.max(data, function (d) { return d.high; })]); + + svg.append("path") + .datum(data) + .attr("class", "area") + .attr("d", area); + + svg.append("g") + .attr("class", "x axis") + .attr("transform", "translate(0," + height + ")") + .call(xAxis); + + svg.append("g") + .attr("class", "y axis") + .call(yAxis) + .append("text") + .attr("transform", "rotate(-90)") + .attr("y", 6) + .attr("dy", ".71em") + .style("text-anchor", "end") + .text("Temperature (F)"); + }); +} + +//Example from http://bl.ocks.org/mbostock/1557377 +function dragMultiples { + var width = 238, + height = 123, + radius = 20; + + var drag = d3.behavior.drag() + .origin(Object) + .on("drag", dragmove); + + var svg = d3.select("body").selectAll("svg") + .data(d3.range(16).map(function () { return { x: width / 2, y: height / 2 }; })) + .enter().append("svg") + .attr("width", width) + .attr("height", height); + + svg.append("circle") + .attr("r", radius) + .attr("cx", function (d) { return d.x; }) + .attr("cy", function (d) { return d.y; }) + .call(drag); + + function dragmove(d) { + d3.select(this) + .attr("cx", d.x = Math.max(radius, Math.min(width - radius, d3.event.x))) + .attr("cy", d.y = Math.max(radius, Math.min(height - radius, d3.event.y))); + } +} + +//Example from http://bl.ocks.org/mbostock/3892919 +function panAndZoom { + var margin = { top: 20, right: 20, bottom: 30, left: 40 }, + width = 960 - margin.left - margin.right, + height = 500 - margin.top - margin.bottom; + + var x = d3.scale.linear() + .domain([-width / 2, width / 2]) + .range([0, width]); + + var y = d3.scale.linear() + .domain([-height / 2, height / 2]) + .range([height, 0]); + + var xAxis = d3.svg.axis() + .scale(x) + .orient("bottom") + .tickSize(-height); + + var yAxis = d3.svg.axis() + .scale(y) + .orient("left") + .ticks(5) + .tickSize(-width); + + var zoom = d3.behavior.zoom() + .x(x) + .y(y) + .scaleExtent([1, 10]) + .on("zoom", zoomed); + + var svg = d3.select("body").append("svg") + .attr("width", width + margin.left + margin.right) + .attr("height", height + margin.top + margin.bottom) + .append("g") + .attr("transform", "translate(" + margin.left + "," + margin.top + ")") + .call(zoom); + + svg.append("rect") + .attr("width", width) + .attr("height", height); + + svg.append("g") + .attr("class", "x axis") + .attr("transform", "translate(0," + height + ")") + .call(xAxis); + + svg.append("g") + .attr("class", "y axis") + .call(yAxis); + + function zoomed() { + svg.select(".x.axis").call(xAxis); + svg.select(".y.axis").call(yAxis); + } +} + +//Example from http://bl.ocks.org/mbostock/1125997 +function chainedTransitions() { + var w = 960, + h = 500, + y = d3.scale.ordinal().domain(d3.range(50)).rangePoints([20, h - 20]), + t = Date.now(); + + var svg = d3.select("body").append("svg:svg") + .attr("width", w) + .attr("height", h); + + var circle = svg.selectAll("circle") + .data(y.domain()) + .enter().append("svg:circle") + .attr("r", 16) + .attr("cx", 20) + .attr("cy", y) + .each(slide(20, w - 20)); + + function slide(x0, x1) { + t += 50; + return function() { + d3.select(this).transition() + .duration(t - Date.now()) + .attr("cx", x1) + .each("end", slide(x1, x0)); + }; + } +} diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 081ae2d511..de3491de4f 100644 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -1,305 +1,1356 @@ -interface ID3Selectors { - select: (selector: string) => ID3Selection; - selectAll: (selector: string) => ID3Selection; -} - -interface ID3behavior -{ - drag: () => any; - zoom: () => any; -} - -interface ID3event -{ - dx: number; - dy: number; - clientX: number; - clientY: number; - translate:number[]; - scale: number; - sourceEvent: ID3event; -} - -interface ID3Base extends ID3Selectors { - // behavior - behavior: ID3behavior; - event: ID3event; - // Array Helpers - ascending: (a: number, b: number) => number; - descending: (a: number, b: number) => number; - min: (arr: any[], map?: (v: any) => any ) => any; - max: (arr: any[], map?: (v: any) => any ) => any; - extent: (arr: any[], map?: (v: any) => any ) => any[]; - quantile: (arr: number[], p: number) => number; - bisectLeft: (arr: any[], x: any, low?: number, high?: number) => number; - bisect: (arr: any[], x: any, low?: number, high?: number) => number; - bisectRight: (arr: any[], x: any, low?: number, high?: number) => number; - first: (arr: any[], comparator: (a: any, b: any) => any ) => any; - last: (arr: any[], comparator: (a: any, b:any) => any ) => any; - - // Loading resources - xhr: { - (url: string, callback: (xhr: XMLHttpRequest) => void): void; - (url: string, mime: string, callback: (xhr: XMLHttpRequest) => void): void; - }; - text: { - (url: string, callback: (response: string) => void): void; - (url: string, mime: string, callback: (response: string) => void): void; - }; - json: (url: string, callback: (response: any) => void) => void; - xml: { - (url: string, callback: (response: Document) => void): void; - (url: string, mime: string, callback: (response: Document) => void): void; - }; - html: (url: string, callback: (response: DocumentFragment) => void) => void; - csv: { - (url: string, callback: (response: any[]) => void); - parse(string: string): any[]; - parseRows(string: string, accessor: (row: any[], index: number) => any): any; - format(rows: any[]): string; - }; - - time: ID3Time; - scale: { - linear(): ID3LinearScale; - }; - interpolate: ID3BaseInterpolate; - interpolateNumber: ID3BaseInterpolate; - interpolateRound: ID3BaseInterpolate; - interpolateString: ID3BaseInterpolate; - interpolateRgb: ID3BaseInterpolate; - interpolateHsl: ID3BaseInterpolate; - interpolateArray: ID3BaseInterpolate; - interpolateObject: ID3BaseInterpolate; - interpolateTransform: ID3BaseInterpolate; - layout: ID3Layout; - svg: ID3Svg; - random: ID3Random; -} - -interface ID3Selection extends ID3Selectors { - attr: { - (name: string): string; - (name: string, value: any): ID3Selection; - (name: string, valueFunction: (data: any, index: number) => any): ID3Selection; - }; - - classed: { - (name: string): string; - (name: string, value: any): ID3Selection; - (name: string, valueFunction: (data: any, index: number) => any): ID3Selection; - }; - - style: { - (name: string): string; - (name: string, value: any, priority?: string): ID3Selection; - (name: string, valueFunction: (data: any, index: number) => any, priority?: string): ID3Selection; - }; - - property: { - (name: string): void; - (name: string, value: any): ID3Selection; - (name: string, valueFunction: (data: any, index: number) => any): ID3Selection; - }; - - text: { - (): string; - (value: any): ID3Selection; - (valueFunction: (data: any, index: number) => any): ID3Selection; - }; - - html: { - (): string; - (value: any): ID3Selection; - (valueFunction: (data: any, index: number) => any): ID3Selection; - }; - - append: (name: string) => ID3Selection; - insert: (name: string, before: string) => ID3Selection; - remove: () => ID3Selection; - - data: { - (values: (data: any, index: number) => any) : any; - (values: any[], key?: (data: any, index: number) => any): ID3UpdateSelection; - }; - - call(callback: (selection: ID3Selection) => void): ID3Selection; -} - -interface ID3EnterSelection { - append: (name: string) => ID3Selection; - insert: (name: string, before: string) => ID3Selection; - select: (selector: string) => ID3Selection; - empty: () => bool; - node: () => Node; -} - -interface ID3UpdateSelection extends ID3Selection { - enter: () => ID3EnterSelection; - update: () => ID3Selection; - exit: () => ID3Selection; -} - -interface ID3Time { - second: ID3Interval; - minute: ID3Interval; - hour: ID3Interval; - day: ID3Interval; - week: ID3Interval; - sunday: ID3Interval; - monday: ID3Interval; - tuesday: ID3Interval; - wednesday: ID3Interval; - thursday: ID3Interval; - friday: ID3Interval; - saturday: ID3Interval; - month: ID3Interval; - year: ID3Interval; - - seconds: ID3Range; - minutes: ID3Range; - hours: ID3Range; - days: ID3Range; - weeks: ID3Range; - months: ID3Range; - years: ID3Range; - - sundays: ID3Range; - mondays: ID3Range; - tuesdays: ID3Range; - wednesdays: ID3Range; - thursdays: ID3Range; - fridays: ID3Range; - saturdays: ID3Range; - format: { - - (specifier: string): ID3TimeFormat; - utc: (specifier: string) => ID3TimeFormat; - iso: ID3TimeFormat; - }; - - scale(): ID3TimeScale; -} - -interface ID3Range { - (start: Date, end: Date, step?: number): Date[]; -} - -interface ID3Interval { - (date: Date): Date; - floor: (date: Date) => Date; - round: (date: Date) => Date; - ceil: (date: Date) => Date; - range: ID3Range; - offset: (date: Date, step: number) => Date; - utc: ID3Interval; -} - -interface ID3TimeFormat { - (date: Date): string; - parse: (string: string) => Date; -} - -interface ID3LinearScale { - (value: number): number; - invert(value: number): number; - domain(numbers: any[]): ID3LinearScale; - range: { - (values: any[]): ID3LinearScale; - (): any[]; - }; - rangeRound: (values: any[]) => ID3LinearScale; - interpolate: { - (): ID3Interpolate; - (factory: ID3Interpolate): ID3LinearScale; - }; - clamp(clamp: bool): ID3LinearScale; - nice(): ID3LinearScale; - ticks(count: number): any[]; - tickFormat(count: number): (n: number) => string; - copy: ID3LinearScale; -} - -interface ID3TimeScale { - (value: Date): number; - invert(value: number): Date; - domain(numbers: any[]): ID3TimeScale; - range: { - (values: any[]): ID3TimeScale; - (): any[]; - }; - rangeRound: (values: any[]) => ID3TimeScale; - interpolate: { - (): ID3Interpolate; - (factory: ID3InterpolateFactory): ID3TimeScale; - }; - clamp(clamp: bool): ID3TimeScale; - ticks: { - (count: number): any[]; - (range: ID3Range, count: number): any[]; - }; - tickFormat(count: number): (n: number) => string; - copy(): ID3TimeScale; -} - -interface ID3InterpolateFactory { - (a: any, b: any): ID3BaseInterpolate; -} -interface ID3BaseInterpolate { - (a: any, b: any): ID3Interpolate; -} - -interface ID3Interpolate { - (t: number): number; -} - -interface ID3Layout { - stack(): ID3StackLayout; -} - -interface ID3StackLayout { - (layers: any[], index?: number): any[]; - values(accessor?: (d: any) => any): ID3StackLayout; - offset(offset: string): ID3StackLayout; -} - - - -interface ID3SVGSymbol -{ - type: (string) => ID3SVGSymbol; - size: (number) => ID3SVGSymbol; -} - -interface ID3Svg { - symbol: ()=> ID3SVGSymbol; - axis(): ID3SvgAxis; -} - -interface ID3SvgAxis { - (selection: ID3Selection): void; - scale: { - (): any; - (scale: any): ID3SvgAxis; - }; - - orient: { - (): string; - (orientation: string): ID3SvgAxis; - }; - - ticks: { - (count: number): ID3SvgAxis; - (range: ID3Range, count?: number): ID3SvgAxis; - }; - - tickSubdivide(count: number): ID3SvgAxis; - tickSize(major?: number, minor?: number, end?: number): ID3SvgAxis; - tickFormat(formatter: (value: any) => string): ID3SvgAxis; -} - -interface ID3Random { - normal(mean?: number, deviation?: number): () => number; -} - -declare var d3: ID3Base; +// Type definitions for d3JS +// Project: http://d3js.org/ +// Definitions by: TypeScript samples +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +module D3 { + interface Selectors { + /** + * Select an element from the current document + */ + select: { + /** + * Selects the first element that matches the specified selector string + * + * @param selector Selection String to match + */ + (selector: string): Selection; + /** + * Selects the specified node + * + * @param element Node element to select + */ + (element: EventTarget): Selection; + }; + + /** + * Select multiple elements from the current document + */ + selectAll: { + /** + * Selects all elements that match the specified selector + * + * @param selector Selection String to match + */ + (selector: string): Selection; + /** + * Selects the specified array of elements + * + * @param elements Array of node elements to select + */ + (elements: EventTarget[]): Selection; + }; + } + + interface Behavior { + /** + * Constructs a new drag behaviour + */ + drag: () => Drag; + /** + * Constructs a new zoom behaviour + */ + zoom: () => Zoom; + } + + interface Zoom { + /** + * Execute zoom method + */ + (): any; + + /** + * Registers a listener to receive events + * + * @param type Enent name to attach the listener to + * @param listener Function to attach to event + */ + on: (type: string, listener: (data: any, index?: number) => any) => Zoom; + + /** + * Gets or set the current zoom scale + */ + scale: { + /** + * Get the current current zoom scale + */ + (): number; + /** + * Set the current current zoom scale + * + * @param origin Zoom scale + */ + (scale: number): Zoom; + }; + + /** + * Gets or set the current zoom translation vector + */ + translate: { + /** + * Get the current zoom translation vector + */ + (): number[]; + /** + * Set the current zoom translation vector + * + * @param translate Tranlation vector + */ + (translate: number[]): Zoom; + }; + + /** + * Gets or set the allowed scale range + */ + scaleExtent: { + /** + * Get the current allowed zoom range + */ + (): number[]; + /** + * Set the allowable zoom range + * + * @param extent Allowed zoom range + */ + (extent: number[]): Zoom; + }; + + /** + * Gets or set the X-Scale that should be adjusted when zooming + */ + x: { + /** + * Get the X-Scale + */ + (): Scale; + /** + * Set the X-Scale to be adjusted + * + * @param x The X Scale + */ + (x: Scale): Zoom; + + }; + + /** + * Gets or set the Y-Scale that should be adjusted when zooming + */ + y: { + /** + * Get the Y-Scale + */ + (): Scale; + /** + * Set the Y-Scale to be adjusted + * + * @param y The Y Scale + */ + (y: Scale): Zoom; + }; + } + + interface Drag { + /** + * Execute drag method + */ + (): any; + + /** + * Registers a listener to receive events + * + * @param type Enent name to attach the listener to + * @param listener Function to attach to event + */ + on: (type: string, listener: (data: any, index?: number) => any) => Drag; + + /** + * Gets or set the current origin accessor function + */ + origin: { + /** + * Get the current origin accessor function + */ + (): any; + /** + * Set the origin accessor function + * + * @param origin Accessor function + */ + (origin?: any): Drag; + }; + } + + interface Event { + dx: number; + dy: number; + clientX: number; + clientY: number; + translate: number[]; + scale: number; + sourceEvent: Event; + x: number; + y: number; + } + + interface Base extends Selectors { + /** + * Create a behaviour + */ + behavior: Behavior; + /** + * Access the current user event for interaction + */ + event: Event; + + /** + * Compare two values for sorting. + * Returns -1 if a is less than b, or 1 if a is greater than b, or 0 + * + * @param a First number + * @param b Second number + */ + ascending: (a: number, b: number) => number; + /** + * Compare two values for sorting. + * Returns -1 if a is greater than b, or 1 if a is less than b, or 0 + * + * @param a First number + * @param b Second number + */ + descending: (a: number, b: number) => number; + /** + * Find the minimum value in an array + * + * @param arr Array to search + * @param map Accsessor function + */ + min: (arr: number[], map?: (v: any) => any) => number; + /** + * Find the maximum value in an array + * + * @param arr Array to search + * @param map Accsessor function + */ + max: (arr: number[], map?: (v: any) => any) => number; + /** + * Find the minimum and maximum value in an array + * + * @param arr Array to search + * @param map Accsessor function + */ + extent: (arr: number[], map?: (v: any) => any) => number[]; + /** + * Compute the sum of an array of numbers + * + * @param arr Array to search + * @param map Accsessor function + */ + sum: (arr: number[], map?: (v: any) => any) => number; + /** + * Compute the arithmetic mean of an array of numbers + * + * @param arr Array to search + * @param map Accsessor function + */ + mean: (arr: number[], map?: (v: any) => any) => number; + /** + * Compute the median of an array of numbers (the 0.5-quantile). + * + * @param arr Array to search + * @param map Accsessor function + */ + median: (arr: number[], map?: (v: any) => any) => number; + /** + * Compute a quantile for a sorted array of numbers. + * + * @param arr Array to search + * @param p The quantile to return + */ + quantile: (arr: number[], p: number) => number; + /** + * Locate the insertion point for x in array to maintain sorted order + * + * @param arr Array to search + * @param x Value to serch for insertion point + * @param low Minimum value of array subset + * @param hihg Maximum value of array subset + */ + bisect: (arr: any[], x: any, low?: number, high?: number) => number; + /** + * Locate the insertion point for x in array to maintain sorted order + * + * @param arr Array to search + * @param x Value to serch for insertion point + * @param low Minimum value of array subset + * @param high Maximum value of array subset + */ + bisectLeft: (arr: any[], x: any, low?: number, high?: number) => number; + /** + * Locate the insertion point for x in array to maintain sorted order + * + * @param arr Array to search + * @param x Value to serch for insertion point + * @param low Minimum value of array subset + * @param high Maximum value of array subset + */ + bisectRight: (arr: any[], x: any, low?: number, high?: number) => number; + /** + * Bisect using an accessor. + * + * @param accessor Accessor function + */ + bisector(accessor: (data: any, index: number) => any): any; + /** + * Randomize the order of an array. + * + * @param arr Array to randomise + */ + shuffle(arr: any[]): any[]; + /** + * Reorder an array of elements according to an array of indexes + * + * @param arr Array to reorder + * @param indexes Array containing the order the elements should be returned in + */ + permute(arr: any[], indexes: any[]): any[]; + /** + * Transpose a variable number of arrays. + * + * @param arrs Arrays to transpose + */ + zip(...arrs: any[]): any[]; + /** + * Transpose an array of arrays. + * + * @param matrix Two dimensional array to transpose + */ + transpose(matrix: any[]): any[]; + /** + * List the keys of an associative array. + * + * @param map Array of objects to get the key values from + */ + keys(map: any[]): any[]; + /** + * List the values of an associative array. + * + * @param map Array of objects to get the values from + */ + values(map: any[]): any[]; + /** + * List the key-value entries of an associative array. + * + * @param map Array of objects to get the key-value pairs from + */ + entries(map: any[]): any[]; + /** + * merge multiple arrays into one array + * + * @param map Arrays to merge + */ + merge(...map: any[]): any[]; + /** + * Generate a range of numeric values. + */ + range: { + /** + * Generate a range of numeric values from 0. + * + * @param stop Value to generate the range to + * @param step Step between each value + */ + (stop: number, step?: number): number[]; + /** + * Generate a range of numeric values. + * + * @param start Value to start + * @param stop Value to generate the range to + * @param step Step between each value + */ + (start: number, stop?: number, step?: number): number[]; + }; + /** + * Create new nest operator + */ + nest(): Nest; + + /** + * Request a resource using XMLHttpRequest. + */ + xhr: { + /** + * Creates an asynchronous request for specified url + * + * @param url Url to request + * @param callback Function to invoke when resource is loaded or the request fails + */ + (url: string, callback?: (xhr: XMLHttpRequest) => void ): Xhr; + /** + * Creates an asynchronous request for specified url + * + * @param url Url to request + * @param mime MIME type to request + * @param callback Function to invoke when resource is loaded or the request fails + */ + (url: string, mime: string, callback?: (xhr: XMLHttpRequest) => void ): Xhr; + }; + /** + * Request a text file + */ + text: { + /** + * Request a text file + * + * @param url Url to request + * @param callback Function to invoke when resource is loaded or the request fails + */ + (url: string, callback?: (response: string) => void ): Xhr; + /** + * Request a text file + * + * @param url Url to request + * @param mime MIME type to request + * @param callback Function to invoke when resource is loaded or the request fails + */ + (url: string, mime: string, callback?: (response: string) => void ): Xhr; + }; + /** + * Request a JSON blob + * + * @param url Url to request + * @param callback Function to invoke when resource is loaded or the request fails + */ + json: (url: string, callback?: (response: any) => void ) => Xhr; + /** + * Request an HTML document fragment. + */ + xml: { + /** + * Request an HTML document fragment. + * + * @param url Url to request + * @param callback Function to invoke when resource is loaded or the request fails + */ + (url: string, callback?: (response: Document) => void ): Xhr; + /** + * Request an HTML document fragment. + * + * @param url Url to request + * @param mime MIME type to request + * @param callback Function to invoke when resource is loaded or the request fails + */ + (url: string, mime: string, callback?: (response: Document) => void ): Xhr; + }; + /** + * Request an XML document fragment. + * + * @param url Url to request + * @param callback Function to invoke when resource is loaded or the request fails + */ + html: (url: string, callback?: (response: DocumentFragment) => void ) => Xhr; + /** + * Request a comma-separated values (CSV) file. + */ + csv: { + /** + * Request a comma-separated values (CSV) file. + * + * @param url Url to request + * @param callback Function to invoke when resource is loaded or the request fails + */ + (url: string, callback?: (error: any, response: any[]) => void ): Xhr; + /** + * Parse a CSV string into objects using the header row. + * + * @param string CSV formatted string to parse + */ + parse(string: string): any[]; + /** + * Parse a CSV string into tuples, ignoring the header row. + * + * @param string CSV formatted string to parse + */ + parseRows(string: string, accessor: (row: any[], index: number) => any): any; + /** + * Format an array of tuples into a CSV string. + * + * @param rows Array to convert to a CSV string + */ + format(rows: any[]): string; + }; + /** + * Request a tab-separated values (TSV) file + */ + tsv: { + /** + * Request a tab-separated values (TSV) file + * + * @param url Url to request + * @param callback Function to invoke when resource is loaded or the request fails + */ + (url: string, callback?: (error: any, response: any[]) => void ): Xhr; + /** + * Parse a TSV string into objects using the header row. + * + * @param string TSV formatted string to parse + */ + parse(string: string): any[]; + /** + * Parse a TSV string into tuples, ignoring the header row. + * + * @param string TSV formatted string to parse + */ + parseRows(string: string, accessor: (row: any[], index: number) => any): any; + /** + * Format an array of tuples into a TSV string. + * + * @param rows Array to convert to a TSV string + */ + format(rows: any[]): string; + }; + + /** + * Time Functions + */ + time: Time; + + /** + * Scales + */ + scale: { + /** + * Construct a linear quantitative scale. + */ + linear(): LinearScale; + /* + * Construct an ordinal scale. + */ + ordinal(): OrdinalScale; + /** + * Construct a linear quantitative scale with a discrete output range. + */ + quantize(): QuantizeScale; + /* + * Construct an ordinal scale with ten categorical colors. + */ + category10(): OrdinalScale; + /* + * Construct an ordinal scale with twenty categorical colors + */ + category20(): OrdinalScale; + /* + * Construct an ordinal scale with twenty categorical colors + */ + category20b(): OrdinalScale; + /* + * Construct an ordinal scale with twenty categorical colors + */ + category20c(): OrdinalScale; + }; + /* + * Interpolate two values + */ + interpolate: BaseInterpolate; + /* + * Interpolate two numbers + */ + interpolateNumber: BaseInterpolate; + /* + * Interpolate two integers + */ + interpolateRound: BaseInterpolate; + /* + * Interpolate two strings + */ + interpolateString: BaseInterpolate; + /* + * Interpolate two RGB colours + */ + interpolateRgb: BaseInterpolate; + /* + * Interpolate two HSL colours + */ + interpolateHsl: BaseInterpolate; + /* + * Interpolate two arrays of values + */ + interpolateArray: BaseInterpolate; + /* + * Interpolate two arbitary objects + */ + interpolateObject: BaseInterpolate; + /* + * Interpolate two 2D matrix transforms + */ + interpolateTransform: BaseInterpolate; + + /** + * Layouts + */ + layout: Layout; + + /** + * Svg's + */ + svg: Svg; + + /** + * Random number generators + */ + random: Random; + + /** + * Create a function to format a number as a string + * + * @param specifier The format specifier to use + */ + format(specifier: string): (value: number) => string; + } + + interface Xhr { + /** + * Get or set request header + */ + header: { + /** + * Get the value of specified request header + * + * @param name Name of header to get the value for + */ + (name: string): string; + /** + * Set the value of specified request header + * + * @param name Name of header to set the value for + * @param value Value to set the header to + */ + (name: string, value: string): Xhr; + }; + /** + * Get or set MIME Type + */ + mimeType: { + /** + * Get the current MIME Type + */ + (): string; + /** + * Set the MIME Type for the request + * + * @param type The MIME type for the request + */ + (type: string): Xhr; + }; + /* + * Get or Set the function used to map the response to the associated data value + */ + response: { + /** + * Get function used to map the response to the associated data value + */ + (): (xhr: XMLHttpRequest) => any; + /** + * Set function used to map the response to the associated data value + * + * @param value The function used to map the response to a data value + */ + (value: (xhr: XMLHttpRequest) => any ): Xhr; + }; + /** + * Issue the request using the GET method + * + * @param callback Function to invoke on completion of request + */ + get (callback?: (xhr: XMLHttpRequest) => void ): Xhr; + /** + * Issue the request using the POST method + */ + post: { + /** + * Issue the request using the POST method + * + * @param callback Function to invoke on completion of request + */ + (callback?: (xhr: XMLHttpRequest) => void ): Xhr; + /** + * Issue the request using the POST method + * + * @param data Data to post back in the request + * @param callback Function to invoke on completion of request + */ + (data: any, callback?: (xhr: XMLHttpRequest) => void ): Xhr; + }; + /** + * Issues this request using the specified method + */ + send: { + /** + * Issues this request using the specified method + * + * @param method Method to use to make the request + * @param callback Function to invoke on completion of request + */ + (method: string, callback?: (xhr: XMLHttpRequest) => void ): Xhr; + /** + * Issues this request using the specified method + * + * @param method Method to use to make the request + * @param data Data to post back in the request + * @param callback Function to invoke on completion of request + */ + (method: string, data: any, callback?: (xhr: XMLHttpRequest) => void ): Xhr; + }; + /** + * Aborts this request, if it is currently in-flight + */ + abort(): Xhr; + /** + * Registers a listener to receive events + * + * @param type Enent name to attach the listener to + * @param listener Function to attach to event + */ + on: (type: string, listener: (data: any, index?: number) => any) => Xhr; + } + + interface Selection extends Selectors { + attr: { + (name: string): string; + (name: string, value: any): Selection; + (name: string, valueFunction: (data: any, index: number) => any): Selection; + }; + + classed: { + (name: string): string; + (name: string, value: any): Selection; + (name: string, valueFunction: (data: any, index: number) => any): Selection; + }; + + style: { + (name: string): string; + (name: string, value: any, priority?: string): Selection; + (name: string, valueFunction: (data: any, index: number) => any, priority?: string): Selection; + }; + + property: { + (name: string): void; + (name: string, value: any): Selection; + (name: string, valueFunction: (data: any, index: number) => any): Selection; + }; + + text: { + (): string; + (value: any): Selection; + (valueFunction: (data: any, index: number) => any): Selection; + }; + + html: { + (): string; + (value: any): Selection; + (valueFunction: (data: any, index: number) => any): Selection; + }; + + append: (name: string) => Selection; + insert: (name: string, before: string) => Selection; + remove: () => Selection; + + data: { + (values: (data: any, index: number) => any): UpdateSelection; + (values: any[], key?: (data: any, index: number) => any): UpdateSelection; + }; + + datum: { + (values: (data: any, index: number) => any): UpdateSelection; + (values: any): UpdateSelection; + }; + + filter: { + (filter: (data: any, index: number) => bool): UpdateSelection; + (filter: string): UpdateSelection; + }; + + call(callback: (selection: Selection) => void ): Selection; + each(eachFunction: (data: any, index: number) => any): Selection; + on: { + (type: string): (data: any, index: number) => any; + (type: string, listener: (data: any, index: number) => any, capture?: bool): Selection; + }; + + transition: () => Transition; + } + + interface EnterSelection { + append: (name: string) => Selection; + insert: (name: string, before: string) => Selection; + select: (selector: string) => Selection; + empty: () => bool; + node: () => Node; + } + + interface UpdateSelection extends Selection { + enter: () => EnterSelection; + update: () => Selection; + exit: () => Selection; + } + + interface Transition { + duration: { + (duration: number): Transition; + (duration: (data: any, index: number) => any): Transition; + }; + delay: { + (delay: number): Transition; + (delay: (data: any, index: number) => any): Transition; + }; + attr: { + (name: string): string; + (name: string, value: any): Transition; + (name: string, valueFunction: (data: any, index: number) => any): Transition; + }; + call(callback: (selection: Selection) => void ): Transition; + + select: (selector: string) => Transition; + selectAll: (selector: string) => Transition; + + each: (type?: string, eachFunction?: (data: any, index: number) => any) => Transition; + transition: () => Transition; + ease: (value: string, ...arrs: any[]) => Transition; + } + + interface Nest { + key(keyFunction: (data: any, index: number) => any): Nest; + rollup(rollupFunction: (data: any, index: number) => any): Nest; + map(values: any[]): Nest; + } + + interface Time { + second: Interval; + minute: Interval; + hour: Interval; + day: Interval; + week: Interval; + sunday: Interval; + monday: Interval; + tuesday: Interval; + wednesday: Interval; + thursday: Interval; + friday: Interval; + saturday: Interval; + month: Interval; + year: Interval; + + seconds: Range; + minutes: Range; + hours: Range; + days: Range; + weeks: Range; + months: Range; + years: Range; + + sundays: Range; + mondays: Range; + tuesdays: Range; + wednesdays: Range; + thursdays: Range; + fridays: Range; + saturdays: Range; + format: { + + (specifier: string): TimeFormat; + utc: (specifier: string) => TimeFormat; + iso: TimeFormat; + }; + + scale(): TimeScale; + } + + interface Range { + (start: Date, end: Date, step?: number): Date[]; + } + + interface Interval { + (date: Date): Date; + floor: (date: Date) => Date; + round: (date: Date) => Date; + ceil: (date: Date) => Date; + range: Range; + offset: (date: Date, step: number) => Date; + utc: Interval; + } + + interface TimeFormat { + (date: Date): string; + parse: (string: string) => Date; + } + + interface Scale { + (value: any): any; + domain: { + (values: any[]): Scale; + (): any[]; + }; + range: { + (values: any[]): Scale; + (): any[]; + }; + copy: Scale; + } + + interface LinearScale extends Scale { + (value: number): number; + invert(value: number): number; + domain(numbers: any[]): LinearScale; + range: { + (values: any[]): LinearScale; + (): any[]; + }; + rangeRound: (values: any[]) => LinearScale; + interpolate: { + (): Interpolate; + (factory: Interpolate): LinearScale; + }; + clamp(clamp: bool): LinearScale; + nice(): LinearScale; + ticks(count: number): any[]; + tickFormat(count: number): (n: number) => string; + copy: LinearScale; + } + + interface OrdinalScale extends Scale { + (value: any): any; + domain: { + (values: any[]): OrdinalScale; + (): any[]; + }; + range: { + (values: any[]): OrdinalScale; + (): any[]; + }; + rangePoints(interval: any[], padding?: number): OrdinalScale; + rangeBands(interval: any[], padding?: number, outerPadding?: number): OrdinalScale; + rangeRoundBands(interval: any[], padding?: number, outerPadding?: number): OrdinalScale; + rangeBand(): number; + rangeExtent(): any[]; + copy: OrdinalScale; + } + + interface QuantizeScale extends Scale { + (value: any): any; + domain: { + (values: number[]): QuantizeScale; + (): any[]; + }; + range: { + (values: any[]): QuantizeScale; + (): any[]; + }; + copy: QuantizeScale; + } + + interface TimeScale extends Scale { + (value: Date): number; + invert(value: number): Date; + domain(numbers: any[]): TimeScale; + range: { + (values: any[]): TimeScale; + (): any[]; + }; + rangeRound: (values: any[]) => TimeScale; + interpolate: { + (): Interpolate; + (factory: InterpolateFactory): TimeScale; + }; + clamp(clamp: bool): TimeScale; + ticks: { + (count: number): any[]; + (range: Range, count: number): any[]; + }; + tickFormat(count: number): (n: number) => string; + copy(): TimeScale; + } + + interface InterpolateFactory { + (a: any, b: any): BaseInterpolate; + } + interface BaseInterpolate { + (a: any, b: any): Interpolate; + } + + interface Interpolate { + (t: number): number; + } + + interface Layout { + stack(): StackLayout; + pie(): PieLayout; + } + + interface StackLayout { + (layers: any[], index?: number): any[]; + values(accessor?: (d: any) => any): StackLayout; + offset(offset: string): StackLayout; + } + + interface PieLayout { + (values: any[], index?: number): ArcDescriptor[]; + value: { + (): (d: any, index: number) => number; + (accessor: (d: any, index: number) => number): PieLayout; + }; + sort: { + (): (d1: any, d2: any) => number; + (comparator: (d1: any, d2: any) => number): PieLayout; + }; + startAngle: { + (): number; + (angle: number): Arc; + (angle: () => number): Arc; + }; + endAngle: { + (): number; + (angle: number): Arc; + (angle: () => number): Arc; + }; + } + + interface ArcDescriptor { + value: any; + data: any; + startAngle: number; + endAngle: number; + } + + interface Symbol { + type: (string) => Symbol; + size: (number) => Symbol; + } + + interface Svg { + /** + * Create a new symbol generator + */ + symbol: () => Symbol; + /** + * Create a new axis generator + */ + axis(): Axis; + /** + * Create a new arc generator + */ + arc(): Arc; + /** + * Create a new line generator + */ + line(): Line; + /** + * Create a new area generator + */ + area(): Area; + } + + interface Axis { + (selection: Selection): void; + scale: { + (): any; + (scale: any): Axis; + }; + + orient: { + (): string; + (orientation: string): Axis; + }; + + ticks: { + (count: number): Axis; + (range: Range, count?: number): Axis; + }; + + tickSubdivide(count: number): Axis; + tickSize(major?: number, minor?: number, end?: number): Axis; + tickFormat(formatter: (value: any) => string): Axis; + } + + interface Arc { + (options?: ArcOptions): string; + innerRadius: { + (): number; + (radius: number): Arc; + (radius: () => number): Arc; + }; + outerRadius: { + (): number; + (radius: number): Arc; + (radius: () => number): Arc; + }; + startAngle: { + (): number; + (angle: number): Arc; + (angle: () => number): Arc; + }; + endAngle: { + (): number; + (angle: number): Arc; + (angle: () => number): Arc; + }; + centroid(options?: ArcOptions): number[]; + } + + interface ArcOptions { + innerRadius?: number; + outerRadius?: number; + startAngle?: number; + endAngle?: number; + } + + interface Line { + /** + * Returns the path data string + * + * @param data Array of data elements + * @param index Optional index + */ + (data: any[], index?: number): string; + /** + * Get or set the x-coordinate accessor. + */ + x: { + /** + * Get the x-coordinate accessor. + */ + (): (data: any) => any; + /** + * Set the x-coordinate accessor. + * + * @param accessor The new accessor function + */ + (accessor: (data: any) => any): Line; + }; + /** + * Get or set the y-coordinate accessor. + */ + y: { + /** + * Get the y-coordinate accessor. + */ + (): (data: any) => any; + /** + * Set the y-coordinate accessor. + * + * @param accessor The new accessor function + */ + (accessor: (data: any) => any): Line; + }; + /** + * Get or set the interpolation mode. + */ + interpolate: { + /** + * Get the interpolation accessor. + */ + (): string; + /** + * Set the interpolation accessor. + * + * @param interpolate The interpolation mode + */ + (interpolate: string): Line; + }; + /** + * Get or set the cardinal spline tension. + */ + tension: { + /** + * Get the cardinal spline accessor. + */ + (): number; + /** + * Set the cardinal spline accessor. + * + * @param tension The Cardinal spline interpolation tension + */ + (tension: number): Line; + }; + /** + * Control whether the line is defined at a given point. + */ + defined: { + /** + * Get the accessor function that controls where the line is defined. + */ + (): (data: any) => any; + /** + * Set the accessor function that controls where the area is defined. + * + * @param defined The new accessor function + */ + (defined: (data: any) => any): Line; + }; + } + + interface Area { + /** + * Generate a piecewise linear area, as in an area chart. + */ + (data: any[], index?: number): string; + /** + * Get or set the x-coordinate accessor. + */ + x: { + /** + * Get the x-coordinate accessor. + */ + (): (data: any) => any; + /** + * Set the x-coordinate accessor. + * + * @param accessor The new accessor function + */ + (accessor: (data: any) => any): Area; + }; + /** + * Get or set the x0-coordinate (baseline) accessor. + */ + x0: { + /** + * Get the x0-coordinate (baseline) accessor. + */ + (): (data: any) => any; + /** + * Set the x0-coordinate (baseline) accessor. + * + * @param accessor The new accessor function + */ + (accessor: (data: any) => any): Area; + }; + /** + * Get or set the x1-coordinate (topline) accessor. + */ + x1: { + /** + * Get the x1-coordinate (topline) accessor. + */ + (): (data: any) => any; + /** + * Set the x1-coordinate (topline) accessor. + * + * @param accessor The new accessor function + */ + (accessor: (data: any) => any): Area; + }; + /** + * Get or set the y-coordinate accessor. + */ + y: { + /** + * Get the y-coordinate accessor. + */ + (): (data: any) => any; + /** + * Set the y-coordinate accessor. + * + * @param accessor The new accessor function + */ + (accessor: (data: any) => any): Area; + }; + /** + * Get or set the y0-coordinate (baseline) accessor. + */ + y0: { + /** + * Get the y0-coordinate (baseline) accessor. + */ + (): (data: any) => any; + /** + * Set the y0-coordinate (baseline) accessor. + * + * @param accessor The new accessor function + */ + (accessor: (data: any) => any): Area; + }; + /** + * Get or set the y1-coordinate (topline) accessor. + */ + y1: { + /** + * Get the y1-coordinate (topline) accessor. + */ + (): (data: any) => any; + /** + * Set the y1-coordinate (topline) accessor. + * + * @param accessor The new accessor function + */ + (accessor: (data: any) => any): Area; + }; + /** + * Get or set the interpolation mode. + */ + interpolate: { + /** + * Get the interpolation accessor. + */ + (): string; + /** + * Set the interpolation accessor. + * + * @param interpolate The interpolation mode + */ + (interpolate: string): Area; + }; + /** + * Get or set the cardinal spline tension. + */ + tension: { + /** + * Get the cardinal spline accessor. + */ + (): number; + /** + * Set the cardinal spline accessor. + * + * @param tension The Cardinal spline interpolation tension + */ + (tension: number): Area; + }; + /** + * Control whether the area is defined at a given point. + */ + defined: { + /** + * Get the accessor function that controls where the area is defined. + */ + (): (data: any) => any; + /** + * Set the accessor function that controls where the area is defined. + * + * @param defined The new accessor function + */ + (defined: (data: any) => any): Area; + }; + } + + interface Random { + /** + * Returns a function for generating random numbers with a normal distribution + * + * @param mean The expected value of the generated pseudorandom numbers + * @param deviation The given standard deviation + */ + normal(mean?: number, deviation?: number): () => number; + /** + * Returns a function for generating random numbers with a log-normal distribution + * + * @param mean The expected value of the generated pseudorandom numbers + * @param deviation The given standard deviation + */ + logNormal(mean?: number, deviation?: number): () => number; + /** + * Returns a function for generating random numbers with an Irwin-Hall distribution + * + * @param count The number of independent variables + */ + irwinHall(count: number): () => number; + } +} + +declare var d3: D3.Base; diff --git a/durandal/durandal.d.ts b/durandal/durandal.d.ts new file mode 100644 index 0000000000..a5369261a6 --- /dev/null +++ b/durandal/durandal.d.ts @@ -0,0 +1,438 @@ +// Type definitions for durandal 1.1.1 +// Project: http://durandaljs.com +// Definitions by: Evan Larsen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module "durandal/system" { + /** + * Returns the module id associated with the specified object + */ + export var getModuleId: (obj: any) => string; + /** + * Sets the module id on the module. + */ + export var setModuleId: (obj, id: string) => void; + /** + * Call this function to enable or disable Durandal's debug mode. Calling it with no parameters will return true if the framework is currently in debug mode, false otherwise. + */ + export var debug: (debug?: bool) => bool; + /** + * Checks if the obj is an array + */ + export var isArray: (obj: any) => bool; + /** + * Logs data to the console. Pass any number of parameters to be logged. Log output is not processed if the framework is not running in debug mode. + */ + export var log: (...msgs: any[]) => void; + /** + * Creates a deferred object which can be used to create a promise. Optionally pass a function action to perform which will be passed an object used in resolving the promise. + */ + export var defer: (action?: Function) => JQueryDeferred; + /** + * Creates a simple V4 UUID. This should not be used as a PK in your database. It can be used to generate internal, unique ids. + */ + export var guid: () => string; + /** + * Uses require.js to obtain a module. This function returns a promise which resolves with the module instance. You can pass more than one module id to this function. If more than one is passed, then the promise will resolve with one callback parameter per module. + */ + export var acquire: (...modules: string[]) => JQueryPromise; +} + +declare module "durandal/app" { + /** + * Sets the title for the app. You must set this before calling start. This will set the document title and the default message box header. It is also used internally by the router to set the document title when pages change. + */ + export var title: string; + /** + * simple helper function that wraps a call to modalDialog.show() + */ + export var showModal: (obj, activationData?, context?) => JQueryPromise; + /** + * A simple helper function that translates to return modalDialog.show(new MessageBox(message, title, options)); + */ + export var showMessage: (message: string, title?: string, options?: any) => JQueryPromise; + /** + * Call this function to bootstrap the Durandal framework. It returns a promise which is resolved when the framework is configured and the dom is ready. At that point you are ready to set your root. + */ + export var start: () => JQueryPromise; + /** + * This sets the root view or view model and displays the composed application in the specified application host. + * @param root parameter is required and can be anything that the composition module understands as a view or view model. This includes strings and objects. + * @param transition If you have a splash screen, you may want to specify an optional transition to animate from the splash to your main shell. + * @param applicationHost parameter is optional. If provided it should be an element id for the node into which the UI should be composed. If it is not provided the default is to look for an element with an id of "applicationHost". + */ + export var setRoot: (root: any, transition: string, applicationHost?: string) => void; + /** + * If you intend to run on mobile, you should also call app.adaptToDevice() before setting the root. + */ + export var adaptToDevice: () => void; + /** + * The events parameter is a space delimited string containing one or more event identifiers. When one of these events is triggered, the callback is called and passed the event data provided by the trigger. The special events value of "all" binds all events on the object to the callback. If a context is provided, it will be bound to this for the callback. If the callback is omitted, then a promise-like object is returned from on. This object represents a subscription and has a then function used to register callbacks. + */ + export var on: (events: string, callback: Function, context?) => any; + /** + * Unwires callbacks from events. If no context is specified, all callbacks with different contexts will be removed. If no callback is specified, all callbacks for the event will be removed. If no event is specified, all event callbacks on the object will be removed. + */ + export var off: (events: string, callback: Function, context?) => any; + /** + * Triggers an event, or space-delimited list of events. Subsequent arguments to trigger will be passed along to the event callbacks. + */ + export var trigger: (events: string, ...args: any[]) => any; + /** + * Provides a function which can be used as a callback to trigger the events. This is useful in combination with jQuery events which may need to trigger the aggregator's events. + */ + export var proxy: (events) => Function; +} + +declare module "durandal/composition" { + /** + * sets activate: true on every compose binding + */ + export var activateDuringComposition: bool; + /** + * changes the convention for finding where transitions are located + */ + export var convertTransitionToModuleId: (name: string) => string; + /** + * sets a default transition for all compositions + */ + export var defaultTransitionName: string; + /** + * the default implementation for switching the content during composition + */ + export var switchContent: (parent: HTMLElement, newChild: HTMLElement, settings: any) => void; + /** + * the default implementation on binding and showing content during composition + */ + export var bindAndShow: (element: HTMLElement, view: HTMLElement, settings: any) => void; + /** + * the default strategy which is: return viewLocator.locateViewForObject(settings.model, settings.viewElements); + */ + export var defaultStrategy: (settings: any) => JQueryPromise; + /** + * the default method for getting settings from the binding handler compose. + */ + export var getSettings: (valueAccessor: any) => any; + /** + * the default method for executing a strategy during composition + */ + export var executeStrategy: (element: HTMLElement, settings: any) => void; + /** + * the default method for injecting during composition + */ + export var inject: (element: HTMLElement, settings: any) => void; + /** + * the default method for composing + */ + export var compose: (element: HTMLElement, settings: any, bindingContext: any) => void; +} + +declare module "durandal/http" { + /** + * the default is 'callback' + */ + export var defaultJSONPCallbackParam: string; + /** + * Performs an HTTP GET request on the specified URL. This function returns a promise which resolves with the returned response data. You can optionally return a query object whose properties will be used to construct a query string. + */ + export var get: (url: string, query: Object) => JQueryPromise; + /** + * Performs a JSONP request to the specified url. You can optionally include a query object whose properties will be used to construct the query string. Also, you can pass the name of the API's callback parameter. If none is specified, it defaults to "callback". This api returns a promise. If you are using a callback parameter other than "callback" consistently throughout your application, then you may want to set the http module's defaultJSONPCallbackParam so that you don't need to specify it on every request. + */ + export var jsonp: (url: string, query: Object, callbackParam: string) => JQueryPromise; + /** + * Performs an HTTP POST request on the specified URL with the supplied data. The data object is converted to JSON and the request is sent with an application/json content type. Thie function returns a promise which resolves with the returned response data. + */ + export var post: (url: string, data: Object) => JQueryPromise; +} + +declare module "durandal/modalDialog" { + /** + * the default is 1050 + */ + export var currentZIndex: number; + /** + * This is a helper function which can be used in the creation of custom modal contexts. Each time it is called, it returns a successively higher zIndex value than the last time. + */ + export var getNextZIndex: () => number; + /** + * This is a helper function which will tell you if any modals are currently open. + */ + export var isModalOpen: () => bool; + /** + * You may wish to customize modal displays or add additional contexts in order to display modals in different ways. To alter the default context, you would acquire it by calling getContext() and then alter it's pipeline. If you don't provide a value for name it returns the default context. + */ + export var getContext: (name: string) => any; + /** + * Pass a name and an object which defines the proper modal display pipeline via the functions described in the next section. This creates a new modal context or "modal style." + */ + export var addContext: (name: string, modalContext: any) => JQueryPromise; + /** + * creates a settings obj from the supplied params + */ + export var createCompositionSettings: (obj: any, modalContext: any) => any; + /** + * This API uses the composition module to compose your obj into a modal popover. It also uses the viewModel module to check and enforce any screen lifecycle needs that obj may have. A promise is returned which will be resolved when the modal dialog is dismissed. The obj is the view model for your modal dialog, or a moduleId for the view model to load. Your view model instance will have a single property added to it by this mechanism called modal which represents the dialog infrastructure itself. This modal object has a single function called close which can be invoked to close the modal. You may also pass data to close which will be returned via the promise mechanism. The modal object also references it's owner, activator, the composition settings it was created with and its display context. Speaking of context, this parameter represents the display context or modal style. By default, there is one context registered with the system, named 'default'. If no context is specified, the default context with be used to display the modal. You can also specify activationData which is an arbitrary object that will be passed to your modal's activate function, if it has one. + */ + export var show: (obj: any, activationData: any, context: any) => JQueryPromise; +} + +declare module "durandal/viewEngine" { + /** + * The file extension that view source files are expected to have. + */ + export var viewExtension: string; + /** + * The name of the RequireJS loader plugin used by the viewLocator to obtain the view source. (Use requirejs to map the plugin's full path). + */ + export var viewPlugin: string; + /** + * Returns true if the potential string is a url for a view, according to the view engine. + */ + export var isViewUrl: (url: string) => bool; + /** + * Converts a view url into a view id. + */ + export var convertViewUrlToViewId: (url: string) => string; + /** + * Converts a view id into a full RequireJS path. + */ + export var convertViewIdToRequirePath: (viewId: string) => string; + /** + * Parses some markup and turns it into a dom element. + */ + export var parseMarkup: (markup: string) => HTMLElement; + /** + * Returns a promise for a dom element identified by the viewId parameter. + */ + export var createView: (viewId: string) => JQueryPromise; +} + +declare module "durandal/viewLocator" { + /** + * Allows you to set up a convention for mapping module folders to view folders. modulesPath is a string in the path that will be replaced by viewsPath. Partial views will be mapped to the "views" folder unless an areasPath is specified. All parameters are optional. If none are specified, the convention will map modules in a "viewmodels" folder to views in a "views" folder. + */ + export var useConvention: (modulesPath?: string, viewsPath?: string, areasPath?: string) => string; + /** + * This function takes in an object instance, which it then maps to a view id. That id is then passed to the locateView function and it is processed as above. If elementsToSearch are provided, those are passed along to locateView. Following is a description of how locateViewForObject determines the view for a given object instance. + */ + export var locateViewForObject: (obj: {}, elementsToSearch: HTMLElement[]) => JQueryPromise; + /** + * This function does nothing by default which is why editCustomer.js is mapped to editCustomer.html (both have the same underlying id of editCustomer). Replace this function with your own implementation to easily create your own mapping logic based on moduleId. + */ + export var convertModuleIdToViewId: (moduleId: string) => string; + /** + * As mentioned above, if no view id can be determined, the system falls back to attempting to determine the object's type and then uses that. This function contains the implementation of that fallback behavior. Replace it if you desire something different. Under normal usage however, this function should not be called. + */ + export var determineFallbackViewId: (obj: any) => string; + /** + * When a view area is specified, it along with the requested view id will be passed to this function, allowing you to customize the path of your view. You can specify area as part of the locateView call, but more commonly you would specify it as part of a compose binding. Any compose binding that does not include a model, but only a view, has a default area of 'partial'. + */ + export var translateViewIdToArea: (viewId: string, area?: string) => string; + /** + * The viewOrUrlOrId parameter represents a url/id for the view. The file extension is not necessary (ie. .html). When this function is called, the viewEngine will be used to construct the view. The viewEngine is passed the finalized id and returns a constructed DOM sub-tree, which is returned from this function. If the viewOrUrlOrId is not a string but is actually a DOM node, then the DOM node will be immediately returned. Optionally, you can pass an area string and it along with the url will be passed to the view locator's translateViewIdToArea before constructing the final id to pass to the view engine. If you provide an array of DOM elements for elementsToSearch, before we call the view engine, we will search the existing array for a match and return it if found. + */ + export var locateView: (viewOrUrlOrId: any, area: string, elementsToSearch: HTMLElement[]) => JQueryPromise; +} + +declare module "durandal/viewModel" { + /** + * A property which is the home to some basic settings and functions that control how all activators work. These are used to create the instance settings object for each activator. They can be overriden on a per-instance-basis by passing a settings object when creating an activator or by accessing the settings property of the activator. To change them for all activators, change them on the defaults property. The two most common customizations are presented below. See the source for additional information. + */ + export var defaults: IViewModelDefaults; + /** + * This creates a computed observable which enforces a lifecycle on all values the observable is set to. When creating the activator, you can specify an initialActiveItem to activate. You can also specify a settings object. Use of the settings object is for advanced scenarios and will not be detailed much here. + */ + export var activator: { + (): IDurandalViewModelActiveItem; + (initialActiveItem: any, settings?: IViewModelDefaults): IDurandalViewModelActiveItem; + } +} + +declare module "durandal/viewModelBinder" { + /** + * Applies bindings to a view using a pre-existing bindingContext. This is used by the composition module when a view is supplied without a model. It allows the parent binding context to be preserved. If the optional obj parameter is supplied, a new binding context will be created that is a child of bindingContext with its model set to obj. This is used by the widget framework to provide the widget binding while allowing templated parts to access their surrounding scope. + */ + export var bindContext: (bindingContext: KnockoutBindingContext, view: HTMLElement, obj?: any) => void; + /** + * Databinds obj, which can be an arbitrary object, to view which is a dom sub-tree. If obj has a function called setView, then, following binding, this function will be called, providing obj with an opportunity to interact directly with the dom fragment that it is bound to. + */ + export var bind: (obj: any, view: HTMLElement) => void; +} + +interface IViewModelDefaults { + /** + * When the activator attempts to activate an item as described below, it will only activate the new item, by default, if it is a different instance than the current. Overwrite this function to change that behavior. + */ + areSameItem(currentItem, newItem, activationData): bool; + /** + * default is true + */ + closeOnDeactivate: bool; + /** + * Interprets values returned from guard methods like canActivate and canDeactivate by transforming them into bools. The default implementation translates string values "Yes" and "Ok" as true...and all other string values as false. Non string values evaluate according to the truthy/falsey values of JavaScript. Replace this function with your own to expand or set up different values. This transformation is used by the activator internally and allows it to work smoothly in the common scenario where a deactivated item needs to show a message box to prompt the user before closing. Since the message box returns a promise that resolves to the button option the user selected, it can be automatically processed as part of the activator's guard check. + */ + interpretResponse(value: any): bool; + /** + * called before activating a module + */ + beforeActivate(newItem: any): any; + /** + * called after deactivating a module + */ + afterDeactivate(): any; +}; + +interface IDurandalViewModelActiveItem { + /** + * knockout observable + */ + (val?): any; + /** + * A property which is the home to some basic settings and functions that control how all activators work. These are used to create the instance settings object for each activator. They can be overriden on a per-instance-basis by passing a settings object when creating an activator or by accessing the settings property of the activator. To change them for all activators, change them on the defaults property. The two most common customizations are presented below. See the source for additional information. + */ + settings: IViewModelDefaults; + /** + * This observable is set internally by the activator during the activation process. It can be used to determine if an activation is currently happening. + */ + isActivating(val?: bool): bool; + /** + * Pass a specific item as well as an indication of whether it should be closed, and this function will tell you the answer. + */ + canDeactivateItem(item, close): JQueryPromise; + /** + * Deactivates the specified item (optionally closing it). Deactivation follows the lifecycle and thus only works if the item can be deactivated. + */ + deactivateItem(item, close): JQueryDeferred; + /** + * Determines if a specific item can be activated. You can pass an arbitrary object to this function, which will be passed to the item's canActivate function , if present. This is useful if you are manually controlling activation and you want to provide some context for the operation. + */ + canActivateItem(newItem, activationData?): JQueryPromise; + /** + * Activates a specific item. Activation follows the lifecycle and thus only occurs if possible. activationData functions as stated above. + */ + activateItem(newItem, activationData?): JQueryPromise; + /** + * Checks whether or not the activator itself can be activated...that is whether or not it's current item or initial value can be activated. + */ + canActivate(): JQueryPromise; + /** + * Activates the activator...that is..it activates it's current item or initial value. + */ + activate(): JQueryPromise; + /** + * Checks whether or not the activator itself can be deactivated...that is whether or not it's current item can be deactivated. + */ + canDeactivate(): JQueryPromise; + /** + * Deactivates the activator...interpreted as deactivating its current item. + */ + deactivate(): JQueryDeferred; + /** + * Adds canActivate, activate, canDeactivate and deactivate functions to the provided model which pass through to the corresponding functions on the activator. + */ + includeIn(includeIn: any): JQueryPromise; + /** + * Sets up a collection representing a pool of objects which the activator will activate. See below for details. Activators without an item bool always close their values on deactivate. Activators with an items pool only deactivate, but do not close them. + */ + forItems(items): IDurandalViewModelActiveItem; +}; + +declare module "durandal/plugins/router" { + interface routeInfo { + url: string; + moduleId: string; + name: string; + visible: bool; + }; + /** + * observable that is called when the router is ready + */ + export var ready: KnockoutObservableBool; + /** + * An observable array containing all route info objects. + */ + export var allRoutes: KnockoutObservableArray; + /** + * An observable array containing route info objects configured with visible:true (or by calling the mapNav function). + */ + export var visibleRoutes: KnockoutObservableArray; + /** + * An observable boolean which is true while navigation is in process; false otherwise. + */ + export var isNavigating: KnockoutObservableBool; + /** + * An observable whose value is the currently active item/module/page. + */ + export var activeItem: IDurandalViewModelActiveItem; + /** + * An observable whose value is the currently active route. + */ + export var activeRoute: KnockoutObservableAny; + /** + * called after an a new module is composed + */ + export var afterCompose: () => void; + /** + * Causes the router to move backwards in page history. + */ + export var navigateBack: () => void; + /** + * Use router default convention. + */ + export var useConvention: () => void; + /** + * Causes the router to navigate to a specific url. + */ + export var navigateTo: (url: string) => void; + /** + * replaces the windows.location w/ the url + */ + export var replaceLocation: (url: string) => void; + /** + * akes a route in and returns a calculated name. + */ + export var convertRouteToName: (route: string) => string; + /** + * Takes a route in and returns a calculated moduleId. Simple transformations of this can be done via the useConvention function above. For more advanced transformations, you can override this function. + */ + export var convertRouteToModuleId: (url: string) => string; + /** + * This can be overwritten to provide your own convention for automatically converting routes to module ids. + */ + export var autoConvertRouteToModuleId: (url: string) => string; + /** + * This should not normally be overwritten. But advanced users can override this to completely transform the developer's routeInfo input into the final version used to configure the router. + */ + export var prepareRouteInfo: (info: routeInfo) => void; + /** + * This should not normally be overwritten. But advanced users can override this to completely transform the developer's routeInfo input into the final version used to configure the router. + */ + export var handleInvalidRoute: (route: routeInfo, parameters: any) => void; + /** + * Once the router is required, you can call router.mapAuto(). This is the most basic configuration option. When you call this function (with no parameters) it tells the router to directly correlate route parameters to module names in the viewmodels folder. + */ + export var mapAuto: (path?: string) => void; + /** + * Works the same as mapRoute except that routes are automatically added to the visibleRoutes array. + */ + export var mapNav: (url: string, moduleId?: string, name?: string) => routeInfo; + /** + * You can pass a single routeInfo to this function, or you can pass the basic configuration parameters. url is your url pattern, moduleId is the module path this pattern will map to, name is used as the document title and visible determines whether or not to include it in the router's visibleRoutes array for easy navigation UI binding. + */ + export var mapRoute: (urlOrRouteInfo: any, moduleId?: string, name?: string, visible?: bool) => routeInfo; + /** + * This function takes an array of routeInfo objects or a single routeInfo object and uses it to configure the router. The finalized routeInfo (or array of infos) is returned. + */ + export var map: { + (routeOrRouteArray: string): void; + (routeOrRouteArray: string[]): void; + }; + /** + * After you've configured the router, you need to activate it. This is usually done in your shell. The activate function of the router returns a promise that resolves when the router is ready to start. To use the router, you should add an activate function to your shell and return the result from that. The application startup infrastructure of Durandal will detect your shell's activate function and call it at the appropriate time, waiting for it's promise to resolve. This allows Durandal to properly orchestrate the timing of composition and databinding along with animations and splash screen display. + */ + export var activate: (defaultRoute: string) => JQueryPromise; +} diff --git a/dustjs-linkedin/dustjs-linkedin-tests.ts b/dustjs-linkedin/dustjs-linkedin-tests.ts new file mode 100644 index 0000000000..ae96e74661 --- /dev/null +++ b/dustjs-linkedin/dustjs-linkedin-tests.ts @@ -0,0 +1,41 @@ +/// + +import dust = module("dustjs-linkedin"); + +// +// compilation +// +dust.compile("template", "template name", true); +dust.compile("template", "template name"); + +dust.compileFn(""); +var template = dust.compileFn("template", "template name"); + +// registration +dust.register("template name", template); +dust.loadSource("template source"); + +// context +var context = dust.makeBase({ anyProperty: "anyvalue" }); +context = dust.makeBase(context); + +// render and renderSource overloads +dust.render("template name", { anyProperty: "anyvalue" }, (err, out) => { }); +dust.render("template name", context, (err, out) => { }); + +dust.renderSource("template source", { anyProperty: "anyvalue" }); +dust.renderSource("template source", { anyProperty: "anyvalue" }, (err, out) => { }); +dust.renderSource("template source", context, (err, out) => { }); +dust.renderSource("template source", context); + +// stream +dust.stream("template name", { anyProperty: "anyvalue" }); +dust.stream("template name", context); + +// utils +var filter = dust.filters["someFilter"]; +filter("value"); + +dust.escapeHtml(""); +dust.escapeJs("['a', 124]"); + diff --git a/dustjs-linkedin/dustjs-linkedin.d.ts b/dustjs-linkedin/dustjs-linkedin.d.ts new file mode 100644 index 0000000000..fd65583327 --- /dev/null +++ b/dustjs-linkedin/dustjs-linkedin.d.ts @@ -0,0 +1,168 @@ +// Type definitions for linkedin dustjs 1.2.1 +// Project: https://github.com/linkedin/dustjs +// Definitions by: Marcelo Dezem +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// +// Due to a lack of documentation it's not possible +// to know which methods are intended to be public and which +// are intended to be used internally by the framework. +// All the interfaces definitions here exposes only the methods +// that are documented in some way (tutorials, guides, references, etc.). +// +// Fell free to include other methods. If possible let me know about. +// + +declare module "dustjs-linkedin" { + + /** + * A template compiled into a js function. + */ + export interface Template { + (chk: Chunk, ctx: Context): Chunk; + } + + export interface Chunk { + /** + * Writes data to this chunk's buffer. + */ + write(data: string): Chunk; + + /** + * Writes data to this chunk's buffer and marks it as flushable. This method must be called on any chunks created via chunk.map. Do not call this method on a handler's main chunk -- dust.render and dust.stream take care of this for you. + */ + end(data: string): Chunk; + + /** + * Creates a new chunk and passes it to callback. Use map to wrap asynchronous functions and to partition the template for streaming. + */ + map(callback: (chunk: Chunk) => any): Chunk; + + /** + * Convenience method to apply filters to a stream. + */ + tap(callback: (value: any) => any): Chunk; + + /** + * Removes the head tap function from the list. + */ + untap(): Chunk; + + /** + * Renders a template block, such as a default block or an else block. + */ + render(body: any, context: Context): Chunk; + + /** + * Sets an error on this chunk and immediately flushes the output. + */ + setError(err: any): Chunk; + } + + export interface Context { + /** + * Retrieves the value at key from the context stack. + */ + get (key: string): any; + + /** + * Pushes an arbitrary value onto the context stack and returns a new context instance. Specify index and/or length to enable enumeration helpers. + */ + push(head: any, idx?: number, len?: number): Context; + + /** + * Returns a new context instance consisting only of the value at head, plus any previously defined global object. + */ + rebase(head: any): Context; + + /** + * Returns the head of the context stack. + */ + current(): any; + } + + export interface Stream { + flush(): void; + emit(evt: string, data: any): void; + + /* + * Registers an event listener. Streams accept a single listener for a given event. + * @param evt the event. Possible values are data, end, error (maybe more, look in the source). + */ + on(evt: string, callback: (data?: any) => any); + + pipe(stream: Stream): Stream; + } + + /** + * register a template into the cache. + * @param name the unique template name. + * @param tmpl the template function. + */ + export function register(name: string, tmpl: Template): void; + + /** + * compile a template body into a string of JavaScript source code + * @param source the template string + * @param name the name used to register the compiled template into the internal cache. See render(). + * @strip strip whitespaces from the output. Defaults to false. + */ + export function compile(source: string, name: string, strip?: bool): string; + + /** + * Compiles source directly into a JavaScript function that takes a context and an optional callback (see dust.renderSource). Registers the template under [name] if this argument is supplied. + * @param source the template string + * @param name the template name (optional). + */ + export function compileFn(source: string, name?: string): Template; + + /** + * Evaluates a compiled source string. + */ + export function loadSource(compiled: string): Template; + + /** + * Renders the named template and calls callback on completion.context may be a plain object or an instance of dust.Context. + * @param name the template name. + * @param context a plain object or an instance of dust.Context. + */ + export function render(name: string, context: any, callback: (err: any, out: string) => any); + export function render(name: string, context: Context, callback: (err: any, out: string) => any); + + /** + * Compiles and renders source, invoking callback on completion. If no callback is supplied this function returns a Stream object. Use this function when precompilation is not required. + * @param source the template string. + * @param context a plain object or an instance of dust.Context. + * @param callback (optional). If supplied the callback will be called passing the result string. If omitted, renderSource() will return a dust.Stream object. + */ + export function renderSource(source: string, context: any): Stream; + export function renderSource(source: string, context: Context): Stream; + export function renderSource(source: string, context: any, callback: (err: any, out: string) => any): void; + export function renderSource(source: string, context: Context, callback: (err: any, out: string) => any): void; + + /** + * Streams the named template. context may be a plain object or an instance of dust.Context. Returns an instance of dust.Stream. + * @param name the template name. + * @param context a plain object or an instance of dust.Context. + */ + export function stream(name: string, context: any): Stream; + export function stream(name: string, context: Context): Stream; + + /** + * Manufactures a dust.Context instance with its global object set to object. + * @param global a plain object or an instance of dust.Context. + */ + export function makeBase(global: any): Context; + export function makeBase(global: Context): Context; + + export function escapeHtml(html: string): string; + export function escapeJs(js: string): string; + + declare var helpers: { + [key: string]: (chk: Chunk, ctx: Context, bodies?: any, params?: any) => any; + }; + + declare var filters: { + [key: string]: (value: string) => string; + }; +} \ No newline at end of file diff --git a/easeljs/easeljs-tests.ts b/easeljs/easeljs-tests.ts index 9569084343..8a1fd292c1 100644 --- a/easeljs/easeljs-tests.ts +++ b/easeljs/easeljs-tests.ts @@ -1,16 +1,19 @@ /// +var stage: any; +var myContext2D: any; + function test_simple() { - var canvas = document.getElementById('canvas'); - var stage = new Stage(canvas); - var shape = new Shape(); + var canvas = document.getElementById('canvas'); + var stage = new createjs.Stage(canvas); + var shape = new createjs.Shape(); shape.graphics.beginFill('rgba(255,0,0,1)').drawRoundRect(0, 0, 120, 120, 10); stage.addChild(shape); stage.update(); } function test_animation() { - var ss = new SpriteSheet({ + var ss = new createjs.SpriteSheet({ "frames": { "width": 200, "numFrames": 64, @@ -26,28 +29,28 @@ function test_animation() { ss.getAnimation("run").next = "jump"; ss.getAnimation("jump").next = "run"; - var bitmapAnimation = new BitmapAnimation(ss); + var bitmapAnimation = new createjs.BitmapAnimation(ss); bitmapAnimation.scaleY = bitmapAnimation.scaleX = .4; bitmapAnimation.gotoAndPlay("run"); - Ticker.setFPS(60); - Ticker.addListener(stage); + createjs.Ticker.setFPS(60); + createjs.Ticker.addListener(stage); stage.addChild(bitmapAnimation); } function test_graphics() { - var g = new Graphics(); + var g = new createjs.Graphics(); g.setStrokeStyle(1); - g.beginStroke(Graphics.getRGB(0, 0, 0)); - g.beginFill(Graphics.getRGB(255, 0, 0)); + g.beginStroke(createjs.Graphics.getRGB(0, 0, 0)); + g.beginFill(createjs.Graphics.getRGB(255, 0, 0)); g.drawCircle(0, 0, 3); - var s = new Shape(g); + var s = new createjs.Shape(g); s.x = 100; s.y = 100; stage.addChild(s); stage.update(); - var myGraphics: Graphics; + var myGraphics: createjs.Graphics; myGraphics.beginStroke("#F00").beginFill("#00F").drawRect(20, 20, 100, 50).draw(myContext2D); } \ No newline at end of file diff --git a/easeljs/easeljs.d.ts b/easeljs/easeljs.d.ts index a19c285b98..f7ec47027c 100644 --- a/easeljs/easeljs.d.ts +++ b/easeljs/easeljs.d.ts @@ -1,4 +1,4 @@ -// Type definitions for EaselJS 0.5 +// Type definitions for EaselJS 0.6 // Project: http://www.createjs.com/#!/EaselJS // Definitions by: Pedro Ferreira // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -27,6 +27,7 @@ module createjs { cacheCanvas: HTMLCanvasElement; cacheID: number; compositeOperation: string; + cursor: string; filters: Filter[]; hitArea: DisplayObject; id: number; @@ -53,6 +54,7 @@ module createjs { clone(): DisplayObject; draw(ctx: CanvasRenderingContext2D, ignoreCache?: bool): void; getCacheDataURL(): string; + getChildByName(name: string): DisplayObject; getConcatenatedMatrix(mtx: Matrix2D): Matrix2D; getMatrix(matrix: Matrix2D): Matrix2D; getStage(): Stage; @@ -61,6 +63,7 @@ module createjs { isVisible(): bool; localToGlobal(x: number, y: number): Point; localToLocal(x: number, y: number, target: DisplayObject): Point; + set(props: Object): DisplayObject; setTransform(x: number, y: number, scaleX: number, scaleY: number, rotation: number, skewX: number, skewY: number, regX: number, regY: number): DisplayObject; setupContext(ctx: CanvasRenderingContext2D): void; toString(): string; @@ -68,12 +71,26 @@ module createjs { updateCache(compositeOperation: string): void; // events - onClick: (event: MouseEvent) => any; - onDoubleClick: (event: MouseEvent) => any; - onMouseOut: (event: MouseEvent) => any; - onMouseOver: (event: MouseEvent) => any; - onPress: (event: MouseEvent) => any; - onTick: () => any; + click: (event: MouseEvent) => any; + dblClick: (event: MouseEvent) => any; + mouseout: (event: MouseEvent) => any; + mouseover: (event: MouseEvent) => any; + mousedown: (event: MouseEvent) => any; + tick: () => any; + + // EventDispatcher mixins + addEventListener(type: string, listener: (eventObj: Object) => bool): Function; + addEventListener(type: string, listener: (eventObj: Object) => void): Function; + addEventListener(type: string, listener: { handleEvent: (eventObj: Object) => bool; }): Object; + addEventListener(type: string, listener: { handleEvent: (eventObj: Object) => void; }): Object; + removeEventListener(type: string, listener: (eventObj: Object) => bool): void; + removeEventListener(type: string, listener: (eventObj: Object) => void): void; + removeEventListener(type: string, listener: { handleEvent: (eventObj: Object) => bool; }): void; + removeEventListener(type: string, listener: { handleEvent: (eventObj: Object) => void; }): void; + removeAllEventListeners(type: string): void; + dispatchEvent(eventObj: string, target: Object): bool; + dispatchEvent(eventObj: Object, target: Object): bool; + hasEventListener(type: string): bool; } @@ -142,6 +159,7 @@ module createjs { advance(): void; cache(): void; clone(): BitmapAnimation; + getBounds(): Rectangle; gotoAndPlay(frameOrAnimation: string): void; gotoAndPlay(frameOrAnimation: number): void; play(): void; @@ -149,9 +167,23 @@ module createjs { updateCache(): void; // events - onAnimationEnd: (reference: BitmapAnimation, animationEnded: string) => any; + onAnimationEnd: (event: Object) => any; } + export class ButtonHelper { + // properties + target: Object; + overLabel: string; + outLabel: string; + downLabel: string; + play: bool; + + // methods + constructor(target: MovieClip, outLabel: string, overLabel: string, downLabel: string, play: bool, hitArea: DisplayObject, hitLabel: string); + constructor(target: BitmapAnimation, outLabel: string, overLabel: string, downLabel: string, play: bool, hitArea: DisplayObject, hitLabel: string); + setEnabled(value: bool); + toString(): string; + } export class BoxBlurFilter extends Filter { // properties @@ -209,8 +241,7 @@ module createjs { } - export class Command - { + export class Command { // methods constructor (f, params, path); exec(scope: any): void; @@ -252,6 +283,35 @@ module createjs { } + export class EaselJS { + // properties + version: string; + buildDate: string; + } + + + export class EventDispatcher { + // properties + + // methods + static initialize(target: Object): void; + + addEventListener(type: string, listener: (eventObj: Object) => bool): Function; + addEventListener(type: string, listener: (eventObj: Object) => void): Function; + addEventListener(type: string, listener: { handleEvent: (eventObj: Object) => bool; }): Object; + addEventListener(type: string, listener: { handleEvent: (eventObj: Object) => void; }): Object; + removeEventListener(type: string, listener: (eventObj: Object) => bool): void; + removeEventListener(type: string, listener: (eventObj: Object) => void): void; + removeEventListener(type: string, listener: { handleEvent: (eventObj: Object) => bool; }): void; + removeEventListener(type: string, listener: { handleEvent: (eventObj: Object) => void; }): void; + removeAllEventListeners(type: string): void; + dispatchEvent(eventObj: string, target: Object): bool; + dispatchEvent(eventObj: Object, target: Object): bool; + hasEventListener(type: string): bool; + toString(): string; + } + + export class Graphics { // properties BASE_64: Object; @@ -263,7 +323,7 @@ module createjs { // methods arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise: bool): Graphics; arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): Graphics; - beginBitmapFill(image: Object, repetition?: string): Graphics; + beginBitmapFill(image: Object, repetition?: string, matrix?: Matrix2D): Graphics; beginBitmapStroke(image: Object, repetition?: string): Graphics; beginFill(color: string): Graphics; beginLinearGradientFill(colors: string[], ratios: number[], x0: number, y0: number, x1: number, y1: number): Graphics; @@ -285,20 +345,36 @@ module createjs { drawRoundRectComplex(x: number, y: number, width: number, height: number, radiusTL: number, radiusTR: number, radiusBR: number, radisBL: number): Graphics; endFill(): Graphics; endStroke(): Graphics; + isEmpty(): bool; static getHSL(hue: number, saturation: number, lightness: number, alpha?: number): string; static getRGB(red: number, green: number, blue: number, alpha?: number): string; lineTo(x: number, y: number): Graphics; moveTo(x: number, y: number): Graphics; quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): Graphics; rect(x: number, y: number, width: number, height: number): Graphics; - setStrokeStyle(thickness: number, caps?: string, joints?: string, miter?: number): Graphics; // caps and joints can be a string or number - setStrokeStyle(thickness: number, caps?: number, joints?: string, miter?: number): Graphics; - setStrokeStyle(thickness: number, caps?: string, joints?: number, miter?: number): Graphics; - setStrokeStyle(thickness: number, caps?: number, joints?: number, miter?: number): Graphics; + setStrokeStyle(thickness: number, caps?: string, joints?: string, miter?: number, ignoreScale?: bool): Graphics; // caps and joints can be a string or number + setStrokeStyle(thickness: number, caps?: number, joints?: string, miter?: number, ignoreScale?: bool): Graphics; + setStrokeStyle(thickness: number, caps?: string, joints?: number, miter?: number, ignoreScale?: bool): Graphics; + setStrokeStyle(thickness: number, caps?: number, joints?: number, miter?: number, ignoreScale?: bool): Graphics; toString(): string; } + export class Log { + // properties + static NONE: number; + static ERROR: number; + static WARNING: number; + static TRACE: number; + static ALL: number; + static level: number; + + // methods + static out(message: string, details: string, level: number); + static addKeys(keys: Object); + static log(message: string, details: string, level: number); + } + export class Matrix2D { // properties a: number; @@ -354,6 +430,20 @@ module createjs { clone(): MouseEvent; toString(): string; + // EventDispatcher mixins + addEventListener(type: string, listener: (eventObj: Object) => bool): Function; + addEventListener(type: string, listener: (eventObj: Object) => void ): Function; + addEventListener(type: string, listener: { handleEvent: (eventObj: Object) => bool; }): Object; + addEventListener(type: string, listener: { handleEvent: (eventObj: Object) => void; }): Object; + removeEventListener(type: string, listener: (eventObj: Object) => bool): void; + removeEventListener(type: string, listener: (eventObj: Object) => void ): void; + removeEventListener(type: string, listener: { handleEvent: (eventObj: Object) => bool; }): void; + removeEventListener(type: string, listener: { handleEvent: (eventObj: Object) => void; }): void; + removeAllEventListeners(type: string): void; + dispatchEvent(eventObj: string, target: Object): bool; + dispatchEvent(eventObj: Object, target: Object): bool; + hasEventListener(type: string): bool; + // events onMouseMove: (event: MouseEvent) => any; onMouseUp: (event: MouseEvent) => any; @@ -363,6 +453,8 @@ module createjs { export class MovieClip extends Container { // properties actionsEnabled: bool; + autoReset: bool; + currentFrame: number; static INDEPENDENT: string; loop: bool; mode: string; @@ -453,6 +545,7 @@ module createjs { getAnimation(name: string): SpriteSheetAnimation; getAnimations(): string[]; getFrame(frameIndex: number): Object; + getFrameBounds(frameIndex: number); getNumFrames(animation: string): number; toString(): string; @@ -467,22 +560,29 @@ module createjs { maxWidth: number; maxHeight: number; padding: number; + progress: number; spriteSheet: SpriteSheet; + timeSlice: number; // methods addFrame(source: DisplayObject, sourceRect?: Rectangle, scale?: number, setupFunction?: () => any, setupParams?: any[], setupScope?: Object): any; //HERE returns number or null addMovieClip(source: MovieClip, sourceRect?: Rectangle, scale?: number): void; build(): void; - buildAsync(callback?: (reference: SpriteSheetBuilder) => any, timeSlice?: number): void; + buildAsync(timeSlice?: number): void; clone(): SpriteSheetBuilder; stopAsync(): void; toString(): string; + + // events + complete: (event: Object) => any; + onProgress: (event: Object) => any; } export class SpriteSheetUtils { static addFlippedFrames(spriteSheet: SpriteSheet, horizontal?: bool, vertical?: bool, both?: bool): void; - static extractFrame(spriteSheet: HTMLImageElement, frame: number): HTMLImageElement; + static extractFrame(spriteSheet: SpriteSheet, frame: number): HTMLImageElement; + static extractFrame(spriteSheet: SpriteSheet, animationName: string): HTMLImageElement; static flip(spriteSheet: HTMLImageElement, flipData: Object): void; static mergeAlpha(rgbImage: HTMLImageElement, alphaImage: HTMLImageElement, canvas?: HTMLCanvasElement): HTMLCanvasElement; } @@ -498,18 +598,22 @@ module createjs { snapToPixelEnabled: bool; tickOnUpdate: bool; + new (): Stage; + new (canvas: HTMLElement): Stage; + // methods constructor (canvas: HTMLCanvasElement); clone(): Stage; enableMouseOver(frequency: number): void; + enableDOMEvents(enable: bool): void; toDataURL(backgroundColor: string, mimeType: string): string; update(): void; clear(): void; + handleEvent(evt: Object): void; // events - onMouseDown: (event: MouseEvent) => any; - onMouseMove: (event: MouseEvent) => any; - onMouseUp: (event: MouseEvent) => any; + stagemousemove: (event: MouseEvent) => any; + stagemouseup: (event: MouseEvent) => any; } @@ -553,6 +657,16 @@ module createjs { static setInterval(interval: number): void; static setPaused(value: bool): void; + // EventDispatcher mixins + static addEventListener(type: string, listener: (eventObj: Object) => bool): Function; + static addEventListener(type: string, listener: (eventObj: Object) => void): Function; + static addEventListener(type: string, listener: { handleEvent: (eventObj: Object) => bool; }): Object; + static addEventListener(type: string, listener: { handleEvent: (eventObj: Object) => void; }): Object; + static removeEventListener(type: string, listener: (eventObj: Object) => bool): void; + static removeEventListener(type: string, listener: (eventObj: Object) => void): void; + static removeEventListener(type: string, listener: { handleEvent: (eventObj: Object) => bool; }): void; + static removeEventListener(type: string, listener: { handleEvent: (eventObj: Object) => void; }): void; + // events tick: (timeElapsed: number) => any; } diff --git a/epiceditor/epiceditor-tests.ts b/epiceditor/epiceditor-tests.ts new file mode 100644 index 0000000000..ed02371fab --- /dev/null +++ b/epiceditor/epiceditor-tests.ts @@ -0,0 +1,79 @@ +/// + +var editor = new EpicEditor().load(); + +editor.load(function () { + console.log("Editor loaded.") +}); + +editor.unload(function () { + console.log("Editor unloaded.") +}); + +editor.getElement('editor').body.innerHTML; + +if (editor.is('loaded')) + editor.enterFullscreen(); + +editor.open('some-file'); +editor.importFile('some-file', "#Imported markdown\nFancy, huh?"); +var theContent = editor.exportFile(); + +var newName = prompt('What do you want to rename this file to?'); +editor.rename('old-filename.md', newName); + +editor.save(); +editor.remove('example.md'); +var files = editor.getFiles(); + +editor.on('unload', function () { + console.log('Editor was removed'); +}); + +editor.emit('unload'); + +editor.removeListener('unload'); + +editor.preview(); + +editor.edit(); + +editor.enterFullscreen(); + +editor.exitFullscreen(); + +editor.reflow(); +editor.reflow('height'); + +var marked; +var opts = { + container: 'epiceditor', + textarea: null, + basePath: 'epiceditor', + clientSideStorage: true, + localStorageName: 'epiceditor', + useNativeFullsreen: true, + parser: marked, + file: { + name: 'epiceditor', + defaultContent: '', + autoSave: 100 + }, + theme: { + base: '/themes/base/epiceditor.css', + preview: '/themes/preview/preview-dark.css', + editor: '/themes/editor/epic-dark.css' + }, + focusOnLoad: false, + shortcut: { + modifier: 18, + fullscreen: 70, + preview: 80 + }, + string: { + togglePreview: 'Toggle Preview Mode', + toggleEdit: 'Toggle Edit Mode', + toggleFullscreen: 'Enter Fullscreen' + } +} +var editor2 = new EpicEditor(opts); diff --git a/epiceditor/epiceditor.d.ts b/epiceditor/epiceditor.d.ts new file mode 100644 index 0000000000..7030923f2e --- /dev/null +++ b/epiceditor/epiceditor.d.ts @@ -0,0 +1,61 @@ +// Type definitions for EpicEditor 0.2 +// Project: http://epiceditor.com/ +// Definitions by: Boris Yankov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +interface EpicEditorOptions { + container?: any; + textarea?: any; + basePath?: string; + clientSideStorage?: bool; + localStorageName?: string; + useNativeFullsreen?: bool; + parser?: any; + file?: { + name: string; + defaultContent: string; + autoSave: any; + }; + theme?: { + base: string; + preview: string; + editor: string; + }; + focusOnLoad?: bool; + shortcut?: { + modifier: number; + fullscreen: number; + preview: number; + }; + string?: { + togglePreview: string; + toggleEdit: string; + toggleFullscreen: string; + }; +} + +class EpicEditor { + constructor(); + constructor(options: EpicEditorOptions); + + load(callback?: Function): EpicEditor; + unload(callback?: Function): EpicEditor; + getElement(element: string): any; + is(state: string): bool; + open(filename: string); + importFile(filename?: string, content?: string): void; + exportFile(filename?: string, type?: string): any; + rename(oldName: string, newName: string): void; + save(): void; + remove(filename: string): void; + getFiles(filename?: string): any; + on(event: string, handler: Function): void; + emit(event: string): void; + removeListener(event: string, handler?: Function): void; + preview(): void; + edit(): void; + enterFullscreen(): void; + exitFullscreen(): void; + reflow(type?: string): void; +} \ No newline at end of file diff --git a/express/express-tests.ts b/express/express-tests.ts index 9b54b1701c..53dfc11436 100644 --- a/express/express-tests.ts +++ b/express/express-tests.ts @@ -1,10 +1,1250 @@ /// -declare var _, $; +import express = module('express'); +var app = express(); -import Express = module('express'); -var express: Express; -var app: Express.ServerApplication; +////////////////////////// + +var hash: any; + +// config + +app.set('view engine', 'ejs'); +app.set('views', __dirname + '/views'); + +// middleware + +app.use(express.bodyParser()); +app.use(express.cookieParser('shhhh, very secret')); +app.use(express.session()); + +// Session-persisted message middleware + +app.use(function (req, res, next) { + var err = req.session.error + , msg = req.session.success; + delete req.session.error; + delete req.session.success; + res.locals.message = ''; + if (err) res.locals.message = '

' + err + '

'; + if (msg) res.locals.message = '

' + msg + '

'; + next(); +}); + +// dummy database + +var users = { + tj: { name: 'tj' } +}; + +// when you create a user, generate a salt +// and hash the password ('foobar' is the pass here) + +hash('foobar', function (err, salt, hash) { + if (err) throw err; + // store the salt & hash in the "db" + users.tj.salt = salt; + users.tj.hash = hash; +}); + + +// Authenticate using our plain-object database of doom! + +function authenticate(name, pass, fn) { + if (!module.parent) console.log('authenticating %s:%s', name, pass); + var user = users[name]; + // query the db for the given username + if (!user) return fn(new Error('cannot find user')); + // apply the same algorithm to the POSTed password, applying + // the hash against the pass / salt, if there is a match we + // found the user + hash(pass, user.salt, function (err, hash) { + if (err) return fn(err); + if (hash == user.hash) return fn(null, user); + fn(new Error('invalid password')); + }) +} + +function restrict(req: ExpressServerRequest, res: ExpressServerResponse, next?: Function) { + if (req.session.user) { + next(); + } else { + req.session.error = 'Access denied!'; + res.redirect('/login'); + } +} + +app.get('/', function (req, res) { + res.redirect('login'); +}); + +app.get('/restricted', restrict, function (req, res) { + res.send('Wahoo! restricted area, click to logout'); +}); + +app.get('/logout', function (req, res) { + // destroy the user's session to log them out + // will be re-created next request + req.session.destroy(function () { + res.redirect('/'); + }); +}); + +app.get('/login', function (req, res) { + res.render('login'); +}); + +app.post('/login', function (req, res) { + authenticate(req.body.username, req.body.password, function (err, user) { + if (user) { + // Regenerate session when signing in + // to prevent fixation + req.session.regenerate(function () { + // Store the user's primary key + // in the session store to be retrieved, + // or in this case the entire user object + req.session.user = user; + req.session.success = 'Authenticated as ' + user.name + + ' click to logout. ' + + ' You may now access /restricted.'; + res.redirect('back'); + }); + } else { + req.session.error = 'Authentication failed, please check your ' + + ' username and password.' + + ' (use "tj" and "foobar")'; + res.redirect('login'); + } + }); +}); + +if (!module.parent) { + app.listen(3000); + console.log('Express started on port 3000'); +} + +////////////// + +app.set('views', __dirname); +app.set('view engine', 'jade'); + +var pets = []; + +var n = 1000; +while (n--) { + pets.push({ name: 'Tobi', age: 2, species: 'ferret' }); + pets.push({ name: 'Loki', age: 1, species: 'ferret' }); + pets.push({ name: 'Jane', age: 6, species: 'ferret' }); +} + +app.use(express.logger('dev')); + +app.get('/', function (req, res) { + res.render('pets', { pets: pets }); +}); + +app.listen(3000); +console.log('Express listening on port 3000'); + +///////////// + +app.get('/', function (req, res) { + res.format({ + html: function () { + res.send('
    ' + users.map(function (user) { + return '
  • ' + user.name + '
  • '; + }).join('') + '
'); + }, + + text: function () { + res.send(users.map(function (user) { + return ' - ' + user.name + '\n'; + }).join('')); + }, + + json: function () { + res.json(users); + } + }) +}); + +// or you could write a tiny middleware like +// this to abstract make things a bit more declarative: + +function format(mod) { + var obj = require(mod); + return function (req, res) { + res.format(obj); + } +} + +app.get('/users', format('./users')); + +if (!module.parent) { + app.listen(3000); + console.log('listening on port 3000'); +} + +///////////////////////// + +// add favicon() before logger() so +// GET /favicon.ico requests are not +// logged, because this middleware +// reponds to /favicon.ico and does not +// call next() +app.use(express.favicon()); + +// custom log format +if ('test' != process.env.NODE_ENV) + app.use(express.logger(':method :url')); + +// parses request cookies, populating +// req.cookies and req.signedCookies +// when the secret is passed, used +// for signing the cookies. +app.use(express.cookieParser('my secret here')); + +// parses json, x-www-form-urlencoded, and multipart/form-data +app.use(express.bodyParser()); + +app.get('/', function (req, res) { + if (req.cookies.remember) { + res.send('Remembered :). Click to forget!.'); + } else { + res.send('

Check to ' + + '.

'); + } +}); + +app.get('/forget', function (req, res) { + res.clearCookie('remember'); + res.redirect('back'); +}); + +app.post('/', function (req, res) { + var minute = 60000; + if (req.body.remember) res.cookie('remember', 1, { maxAge: minute }); + res.redirect('back'); +}); + +if (!module.parent) { + app.listen(3000); + console.log('Express started on port 3000'); +} + +/////////////////// + +// ignore GET /favicon.ico +app.use(express.favicon()); + +// pass a secret to cookieParser() for signed cookies +app.use(express.cookieParser('manny is cool')); + +// add req.session cookie support +app.use(express.cookieSession()); + +// do something with the session +app.use(count); + +// custom middleware +function count(req, res) { + req.session.count = req.session.count || 0; + var n = req.session.count++; + res.send('viewed ' + n + ' times\n'); +} + +if (!module.parent) { + app.listen(3000); + console.log('Express server listening on port 3000'); +} + +/////////////// + +var api = app; + +app.use(express.static(__dirname + '/public')); + +// api middleware + +api.use(express.logger('dev')); +api.use(express.bodyParser()); + +/** + * CORS support. + */ + +api.all('*', function (req, res, next) { + if (!req.get('Origin')) return next(); + // use "*" here to accept any origin + res.set('Access-Control-Allow-Origin', 'http://localhost:3000'); + res.set('Access-Control-Allow-Methods', 'GET, POST'); + res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type'); + // res.set('Access-Control-Allow-Max-Age', 3600); + if ('OPTIONS' == req.method) return res.send(200); + next(); +}); + +/** + * POST a user. + */ + +api.post('/user', function (req, res) { + console.log(req.body); + res.send(201); +}); + +app.listen(3000); +api.listen(3001); + +console.log('app listening on 3000'); +console.log('api listening on 3001'); + +//////////////////// + +app.get('/', function (req, res) { + res.send(''); +}); + +// /files/* is accessed via req.params[0] +// but here we name it :file +app.get('/files/:file(*)', function (req, res, next?) { + var file = req.params.file + , path = __dirname + '/files/' + file; + + res.download(path); +}); + +// error handling middleware. Because it's +// below our routes, you will be able to +// "intercept" errors, otherwise Connect +// will respond with 500 "Internal Server Error". +app.use(function (err, req, res, next) { + // special-case 404s, + // remember you could + // render a 404 template here + if (404 == err.status) { + res.statusCode = 404; + res.send('Cant find that file, sorry!'); + } else { + next(err); + } +}); + +if (!module.parent) { + app.listen(3000); + console.log('Express started on port 3000'); +} + +/////////////////// + +// Register ejs as .html. If we did +// not call this, we would need to +// name our views foo.ejs instead +// of foo.html. The __express method +// is simply a function that engines +// use to hook into the Express view +// system by default, so if we want +// to change "foo.ejs" to "foo.html" +// we simply pass _any_ function, in this +// case `ejs.__express`. + +app.engine('.html', require('ejs').__express); + +// Optional since express defaults to CWD/views + +app.set('views', __dirname + '/views'); + +// Without this you would need to +// supply the extension to res.render() +// ex: res.render('users.html'). +app.set('view engine', 'html'); + +app.get('/', function (req, res) { + res.render('users', { + users: users, + title: "EJS example", + header: "Some users" + }); +}); + +if (!module.parent) { + app.listen(3000); + console.log('Express app started on port 3000'); +} + +//////////////////// + +var test: any; + +if (!test) app.use(express.logger('dev')); +app.use(app.router); + +// the error handler is strategically +// placed *below* the app.router; if it +// were above it would not receive errors +// from app.get() etc +app.use(error); + +// error handling middleware have an arity of 4 +// instead of the typical (req, res, next), +// otherwise they behave exactly like regular +// middleware, you may have several of them, +// in different orders etc. + +function error(err, req, res, next) { + // log it + if (!test) console.error(err.stack); + + // respond with 500 "Internal Server Error". + res.send(500); +} + +app.get('/', function (req, res) { + // Caught and passed down to the errorHandler middleware + throw new Error('something broke!'); +}); + +app.get('/next', function (req, res, next) { + // We can also pass exceptions to next() + process.nextTick(function () { + next(new Error('oh no!')); + }); +}); + +if (!module.parent) { + app.listen(3000); + console.log('Express started on port 3000'); +} + +///////////////////// + +var silent: any; + +// general config +app.set('views', __dirname + '/views'); +app.set('view engine', 'jade'); + +// our custom "verbose errors" setting +// which we can use in the templates +// via settings['verbose errors'] +app.enable('verbose errors'); + +// disable them in production +// use $ NODE_ENV=production node examples/error-pages +if ('production' == app.settings.env) { + app.disable('verbose errors'); +} + +app.use(express.favicon()); + +silent || app.use(express.logger('dev')); + +// "app.router" positions our routes +// above the middleware defined below, +// this means that Express will attempt +// to match & call routes _before_ continuing +// on, at which point we assume it's a 404 because +// no route has handled the request. + +app.use(app.router); + +// Since this is the last non-error-handling +// middleware use()d, we assume 404, as nothing else +// responded. + +// $ curl http://localhost:3000/notfound +// $ curl http://localhost:3000/notfound -H "Accept: application/json" +// $ curl http://localhost:3000/notfound -H "Accept: text/plain" + +app.use(function (req, res, next) { + res.status(404); + + // respond with html page + if (req.accepts('html')) { + res.render('404', { url: req.url }); + return; + } + + // respond with json + if (req.accepts('json')) { + res.send({ error: 'Not found' }); + return; + } + + // default to plain-text. send() + res.type('txt').send('Not found'); +}); + +// error-handling middleware, take the same form +// as regular middleware, however they require an +// arity of 4, aka the signature (err, req, res, next). +// when connect has an error, it will invoke ONLY error-handling +// middleware. + +// If we were to next() here any remaining non-error-handling +// middleware would then be executed, or if we next(err) to +// continue passing the error, only error-handling middleware +// would remain being executed, however here +// we simply respond with an error page. + +app.use(function (err, req, res, next) { + // we may use properties of the error object + // here and next(err) appropriately, or if + // we possibly recovered from the error, simply next(). + res.status(err.status || 500); + res.render('500', { error: err }); +}); + +// Routes + +app.get('/', function (req, res) { + res.render('index.jade'); +}); + +app.get('/404', function (req, res, next) { + // trigger a 404 since no other middleware + // will match /404 after this one, and we're not + // responding here + next(); +}); + +app.get('/403', function (req, res, next) { + // trigger a 403 error + var err = new Error('not allowed!'); + err.status = 403; + next(err); +}); + +app.get('/500', function (req, res, next) { + // trigger a generic (500) error + next(new Error('keyboard cat!')); +}); + +if (!module.parent) { + app.listen(3000); + //silent ||  console.log('Express started on port 3000'); +} + +/////////////// + +var fs: any; +var md: any; + +app.set('view engine', 'jade'); +app.set('views', __dirname + '/views'); + +function User(name) { + this.private = 'heyyyy'; + this.secret = 'something'; + this.name = name; + this.id = 123; +} + +// You'll probably want to do +// something like this so you +// dont expose "secret" data. + +User.prototype.toJSON = function () { + return { + id: this.id, + name: this.name + } +}; + +app.use(express.logger('dev')); + +// earlier on expose an object +// that we can tack properties on. +// all res.locals props are exposed +// to the templates, so "expose" will +// be present. + +app.use(function (req, res, next) { + res.locals.expose = {}; + // you could alias this as req or res.expose + // to make it shorter and less annoying + next(); +}); + +// pretend we loaded a user + +app.use(function (req, res, next) { + req.user = new User('Tobi'); + next(); +}); + +app.get('/', function (req, res) { + res.redirect('/user'); +}); + +app.get('/user', function (req, res) { + // we only want to expose the user + // to the client for this route: + res.locals.expose.user = req.user; + res.render('page'); +}); + +app.listen(3000); +console.log('app listening on port 3000'); + +/////////////////////// + +app.get('/', function (req, res) { + res.send('Hello World'); +}); + +app.listen(3000); +console.log('Express started on port 3000'); + +//////////////////// + +// register .md as an engine in express view system + +app.engine('md', function (path, options, fn) { + fs.readFile(path, 'utf8', function (err, str) { + if (err) return fn(err); + try { + var html = md(str); + html = html.replace(/\{([^}]+)\}/g, function (_, name) { + return options[name] || ''; + }) + fn(null, html); + } catch (err) { + fn(err); + } + }); +}) + +app.set('views', __dirname + '/views'); + +// make it the default so we dont need .md +app.set('view engine', 'md'); + +app.get('/', function (req, res) { + res.render('index', { title: 'Markdown Example' }); +}) + +app.get('/fail', function (req, res) { + res.render('missing', { title: 'Markdown Example' }); +}) + +if (!module.parent) { + app.listen(3000); + console.log('Express started on port 3000'); +} + +/////////////////////// + +var mformat: any; + +// bodyParser in connect 2.x uses node-formidable to parse +// the multipart form data. +app.use(express.bodyParser()) + +app.get('/', function (req, res) { + res.send('
' + + '

Title:

' + + '

Image:

' + + '

' + + '
'); +}); + +app.post('/', function (req, res, next) { + // the uploaded file can be found as `req.files.image` and the + // title field as `req.body.title` + res.send(mformat('\nuploaded %s (%d Kb) to %s as %s' + , req.files.image.name + , req.files.image.size / 1024 | 0 + , req.files.image.path + , req.body.title)); +}); + +if (!module.parent) { + app.listen(3000); + console.log('Express started on port 3000'); +} + +////////////////// + + +// first: +// $ npm install redis online +// $ redis-server + +/** + * Module dependencies. + */ + +var online: any; +var redis: any; +var db: any; + +// online + +online = online(db); + +// activity tracking, in this case using +// the UA string, you would use req.user.id etc + +app.use(function (req, res, next) { + // fire-and-forget + online.add(req.headers['user-agent']); + next(); +}); + +/** + * List helper. + */ + +function list(ids) { + return '
    ' + ids.map(function (id) { + return '
  • ' + id + '
  • '; + }).join('') + '
'; +} + +/** + * GET users online. + */ + +app.get('/', function (req, res, next) { + online.last(5, function (err, ids) { + if (err) return next(err); + res.send('

Users online: ' + ids.length + '

' + list(ids)); + }); +}); + +app.listen(3000); +console.log('listening on port 3000'); + +/////////////////// + +// Convert :to and :from to integers + +app.param(['to', 'from'], function (req, res, next, num, name) { + req.params[name] = num = parseInt(num, 10); + if (isNaN(num)) { + next(new Error('failed to parseInt ' + num)); + } else { + next(); + } +}); + +// Load user by id + +app.param('user', function (req, res, next, id) { + if (req.user = users[id]) { + next(); + } else { + next(new Error('failed to find user')); + } +}); + +/** + * GET index. + */ + +app.get('/', function (req, res) { + res.send('Visit /user/0 or /users/0-2'); +}); + +/** + * GET :user. + */ + +app.get('/user/:user', function (req, res, next) { + res.send('user ' + req.user.name); +}); + +/** + * GET users :from - :to. + */ + +app.get('/users/:from-:to', function (req, res, next) { + var from = req.params.from + , to = req.params.to + , names = users.map(function (user) { return user.name; }); + res.send('users ' + names.slice(from, to).join(', ')); +}); + +if (!module.parent) { + app.listen(3000); + console.log('Express started on port 3000'); +} + +////////////////// + +// Ad-hoc example resource method + +app.resource = function (path, obj) { + this.get(path, obj.index); + this.get(path + '/:a..:b.:format?', function (req, res) { + var a = parseInt(req.params.a, 10) + , b = parseInt(req.params.b, 10) + , format = req.params.format; + obj.range(req, res, a, b, format); + }); + this.get(path + '/:id', obj.show); + this.del(path + '/:id', obj.destroy); +}; + +// Fake controller. + +var FUser = { + index: function (req, res) { + res.send(users); + }, + show: function (req, res) { + res.send(users[req.params.id] || { error: 'Cannot find user' }); + }, + destroy: function (req, res) { + var id = req.params.id; + var destroyed = id in users; + delete users[id]; + res.send(destroyed ? 'destroyed' : 'Cannot find user'); + }, + range: function (req, res, a, b, format) { + var range = users.slice(a, b + 1); + switch (format) { + case 'json': + res.send(range); + break; + case 'html': + default: + var html = '
    ' + range.map(function (user) { + return '
  • ' + user.name + '
  • '; + }).join('\n') + '
'; + res.send(html); + break; + } + } +}; + +// curl http://localhost:3000/users -- responds with all users +// curl http://localhost:3000/users/1 -- responds with user 1 +// curl http://localhost:3000/users/4 -- responds with error +// curl http://localhost:3000/users/1..3 -- responds with several users +// curl -X DELETE http://localhost:3000/users/1 -- deletes the user + +app.resource('/users', FUser); + +app.get('/', function (req, res) { + res.send([ + '

Examples:

    ' + , '
  • GET /users
  • ' + , '
  • GET /users/1
  • ' + , '
  • GET /users/3
  • ' + , '
  • GET /users/1..3
  • ' + , '
  • GET /users/1..3.json
  • ' + , '
  • DELETE /users/4
  • ' + , '
' + ].join('\n')); +}); + +if (!module.parent) { + app.listen(3000); + console.log('Express started on port 3000'); +} + +///////////////////// + + +var verbose: any; + +app.map = function (a, route) { + route = route || ''; + for (var key in a) { + switch (typeof a[key]) { + // { '/path': { ... }} + case 'object': + app.map(a[key], route + key); + break; + // get: function(){ ... } + case 'function': + if (verbose) console.log('%s %s', key, route); + app[key](route, a[key]); + break; + } + } +}; + +var users2 = { + list: function (req, res) { + res.send('user list'); + }, + + get: function (req, res) { + res.send('user ' + req.params.uid); + }, + + del: function (req, res) { + res.send('delete users'); + } +}; + +var pets2 = { + list: function (req, res) { + res.send('user ' + req.params.uid + '\'s pets'); + }, + + del: function (req, res) { + res.send('delete ' + req.params.uid + '\'s pet ' + req.params.pid); + } +}; + +app.map({ + '/users': { + get: users2.list, + del: users2.del, + '/:uid': { + get: users.get , + '/pets': { + get: pets2.list, + '/:pid': { + del: pets2.del + } + } + } + } +}); + +app.listen(3000); + +/////////////////////////// + +// Example requests: +// curl http://localhost:3000/user/0 +// curl http://localhost:3000/user/0/edit +// curl http://localhost:3000/user/1 +// curl http://localhost:3000/user/1/edit (unauthorized since this is not you) +// curl -X DELETE http://localhost:3000/user/0 (unauthorized since you are not an admin) + +function loadUser(req, res, next) { + // You would fetch your user from the db + var user = users[req.params.id]; + if (user) { + req.user = user; + next(); + } else { + next(new Error('Failed to load user ' + req.params.id)); + } +} + +function andRestrictToSelf(req, res, next) { + // If our authenticated user is the user we are viewing + // then everything is fine :) + if (req.authenticatedUser.id == req.user.id) { + next(); + } else { + // You may want to implement specific exceptions + // such as UnauthorizedError or similar so that you + // can handle these can be special-cased in an error handler + // (view ./examples/pages for this) + next(new Error('Unauthorized')); + } +} + +function andRestrictTo(role) { + return function (req, res, next) { + if (req.authenticatedUser.role == role) { + next(); + } else { + next(new Error('Unauthorized')); + } + } +} + +// Middleware for faux authentication +// you would of course implement something real, +// but this illustrates how an authenticated user +// may interact with middleware + +app.use(function (req, res, next) { + req.authenticatedUser = users[0]; + next(); +}); + +app.get('/', function (req, res) { + res.redirect('/user/0'); +}); + +app.get('/user/:id', loadUser, function (req, res) { + res.send('Viewing user ' + req.user.name); +}); + +app.get('/user/:id/edit', loadUser, andRestrictToSelf, function (req, res) { + res.send('Editing user ' + req.user.name); +}); + +app.del('/user/:id', loadUser, andRestrictTo('admin'), function (req, res) { + res.send('Deleted user ' + req.user.name); +}); + +app.listen(3000); +console.log('Express app started on port 3000'); + +///////////////////////// + +app.set('view engine', 'jade'); +app.set('views', __dirname); + +// populate search + +db.sadd('ferret', 'tobi'); +db.sadd('ferret', 'loki'); +db.sadd('ferret', 'jane'); +db.sadd('cat', 'manny'); +db.sadd('cat', 'luna'); + +/** + * GET the search page. + */ + +app.get('/', function (req, res) { + res.render('search'); +}); + +/** + * GET search for :query. + */ + +app.get('/search/:query?', function (req, res) { + var query = req.params.query; + db.smembers(query, function (err, vals) { + if (err) return res.send(500); + res.send(vals); + }); +}); + +/** + * GET client javascript. Here we use sendfile() + * because serving __dirname with the static() middleware + * would also mean serving our server "index.js" and the "search.jade" + * template. + */ + +app.get('/client.js', function (req, res) { + res.sendfile(__dirname + '/client.js'); +}); + +app.listen(3000); +console.log('app listening on port 3000'); + +/////////////////// + +app.use(express.logger('dev')); + +// Required by session() middleware +// pass the secret for signed cookies +// (required by session()) +app.use(express.cookieParser('keyboard cat')); + +// Populates req.session +app.use(express.session()); + +app.get('/', function (req, res) { + var body = ''; + if (req.session.views) { + ++req.session.views; + } else { + req.session.views = 1; + body += '

First time visiting? view this page in several browsers :)

'; + } + res.send(body + '

viewed ' + req.session.views + ' times.

'); +}); + +app.listen(3000); +console.log('Express app started on port 3000'); + +//////////////////////// + +// log requests +app.use(express.logger('dev')); + +// express on its own has no notion +// of a "file". The express.static() +// middleware checks for a file matching +// the `req.path` within the directory +// that you pass it. In this case "GET /js/app.js" +// will look for "./public/js/app.js". + +app.use(express.static(__dirname + '/public')); + +// if you wanted to "prefix" you may use +// the mounting feature of Connect, for example +// "GET /static/js/app.js" instead of "GET /js/app.js". +// The mount-path "/static" is simply removed before +// passing control to the express.static() middleware, +// thus it serves the file correctly by ignoring "/static" +app.use('/static', express.static(__dirname + '/public')); + +// if for some reason you want to serve files from +// several directories, you can use express.static() +// multiple times! Here we're passing "./public/css", +// this will allow "GET /style.css" instead of "GET /css/style.css": +app.use(express.static(__dirname + '/public/css')); + +// this examples does not have any routes, however +// you may `app.use(app.router)` before or after these +// static() middleware. If placed before them your routes +// will be matched BEFORE file serving takes place. If placed +// after as shown here then file serving is performed BEFORE +// any routes are hit: +app.use(app.router); + +app.listen(3000); +console.log('listening on port 3000'); +console.log('try:'); +console.log(' GET /hello.txt'); +console.log(' GET /js/app.js'); +console.log(' GET /css/style.css'); + +////////////////// + +/* +edit /etc/vhosts: + +127.0.0.1 foo.example.com +127.0.0.1 bar.example.com +127.0.0.1 example.com +*/ + +// Main app + +var main = express(); + +main.use(express.logger('dev')); + +main.get('/', function (req, res) { + res.send('Hello from main app!') +}); + +main.get('/:sub', function (req, res) { + res.send('requsted ' + req.params.sub); +}); + +// Redirect app + +var redirect = express(); + +redirect.all('*', function (req, res) { + console.log(req.subdomains); + res.redirect('http://example.com:3000/' + req.subdomains[0]); +}); + +app.use(express.vhost('*.example.com', redirect)) +app.use(express.vhost('example.com', main)); + +app.listen(3000); +console.log('Express app started on port 3000'); + +//////////////////// + +// create an error with .status. we +// can then use the property in our +// custom error handler (Connect repects this prop as well) + +function merror(status, msg) { + var err = new Error(msg); + err.status = status; + return err; +} + +// if we wanted to supply more than JSON, we could +// use something similar to the content-negotiation +// example. + +// here we validate the API key, +// by mounting this middleware to /api +// meaning only paths prefixed with "/api" +// will cause this middleware to be invoked + +app.use('/api', function (req, res, next) { + var key = req.query['api-key']; + + // key isnt present + if (!key) return next(merror(400, 'api key required')); + + // key is invalid + if (!~apiKeys.indexOf(key)) return next(merror(401, 'invalid api key')); + + // all good, store req.key for route access + req.key = key; + next(); +}); + +// position our routes above the error handling middleware, +// and below our API middleware, since we want the API validation +// to take place BEFORE our routes +app.use(app.router); + +// middleware with an arity of 4 are considered +// error handling middleware. When you next(err) +// it will be passed through the defined middleware +// in order, but ONLY those with an arity of 4, ignoring +// regular middleware. +app.use(function (err, req, res, next) { + // whatever you want here, feel free to populate + // properties on `err` to treat it differently in here. + res.send(err.status || 500, { error: err.message }); +}); + +// our custom JSON 404 middleware. Since it's placed last +// it will be the last middleware called, if all others +// invoke next() and do not respond. +app.use(function (req, res) { + res.send(404, { error: "Lame, can't find that" }); +}); + +// map of valid api keys, typically mapped to +// account info with some sort of database like redis. +// api keys do _not_ serve as authentication, merely to +// track API usage or help prevent malicious behavior etc. + +var apiKeys = ['foo', 'bar', 'baz']; + +// these two objects will serve as our faux database + +var repos = [ + { name: 'express', url: 'http://github.com/visionmedia/express' } + , { name: 'stylus', url: 'http://github.com/learnboost/stylus' } + , { name: 'cluster', url: 'http://github.com/learnboost/cluster' } +]; + +var userRepos = { + tobi: [repos[0], repos[1]] + , loki: [repos[1]] + , jane: [repos[2]] +}; + +// we now can assume the api key is valid, +// and simply expose the data + +app.get('/api/users', function (req, res, next) { + res.send(users); +}); + +app.get('/api/repos', function (req, res, next) { + res.send(repos); +}); + +app.get('/api/user/:name/repos', function (req, res, next) { + var name = req.params.name + , user = userRepos[name]; + + if (user) res.send(user); + else next(); +}); + +if (!module.parent) { + app.listen(3000); + console.log('Express server listening on port 3000'); +} + +////// function test_general() { @@ -97,7 +1337,7 @@ function test_general() { } function test_request() { - var req: Express.ServerRequest; + var req: ExpressServerRequest; req.params.name; req.params[0]; req.query.q; @@ -130,7 +1370,7 @@ function test_request() { } function test_response() { - var res: Express.ServerResponse; + var res: ExpressServerResponse; res.status(404).sendfile('path/to/404.png'); res.set('Content-Type', 'text/plain'); res.set({ diff --git a/express/express.d.ts b/express/express.d.ts index c8fe6bec31..8e19ab0049 100644 --- a/express/express.d.ts +++ b/express/express.d.ts @@ -1,218 +1,1954 @@ -// Type definitions for Express 3.0 +// Type definitions for Express 3.1 // Project: http://expressjs.com // Definitions by: Boris Yankov -// Definitions: https://github.com/borisyankov/DefinitelyTyped +// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped -/* -USAGE +/* =================== USAGE =================== -/// -import express = module('express') -var app = express() -... + import express = module('express'); + var app = express(); -MIDDLEWARE + =============================================== */ -express exports lots of middleware, like .static, .session, etc, but use connect so you don't have to escape -var connect = require('connect') -connect.session({}) +/// -*/ +interface Route { + path: string; -/// + method: string; -// do not reference this. use module('express') instead -declare module _express { + callbacks: Function[]; - import http = module("http"); + regexp: any; - export interface Handler { - (req: ServerRequest, res: ServerResponse, next?: Function): void; - } + /** + * Check if this route matches `path`, if so + * populate `.params`. + */ + match(path: string): bool; +} +declare var Route: { + /** + * Initialize `Route` with the given HTTP `method`, `path`, + * and an array of `callbacks` and `options`. + * + * Options: + * + * - `sensitive` enable case-sensitive routes + * - `strict` enable strict matching for trailing slashes + * + * @param method + * @param path + * @param callbacks + * @param options + */ + new (method: string, path: string, callbacks: Function[], options: any): Route; +} - export interface Errback { (err: Error): void; } +interface Handler { + (req: ExpressServerRequest, res: ExpressServerResponse, next?: Function): void; +} - export interface CookieOptions { - maxAge?: number; - signed?: bool; - expires?: Date; - httpOnly?: bool; - path?: string; - domain?: string; - secure?: bool; - } +interface CookieOptions { + maxAge?: number; + signed?: bool; + expires?: Date; + httpOnly?: bool; + path?: string; + domain?: string; + secure?: bool; +} - export interface ExpressSettings { - env?: string; - views?: string; - } +interface Errback { (err: Error): void; } - export interface ServerApplication { - settings: ExpressSettings; - locals: any; - routes: any; +interface ExpressSession { + /** + * Update reset `.cookie.maxAge` to prevent + * the cookie from expiring when the + * session is still active. + * + * @return {Session} for chaining + * @api public + */ + touch(): ExpressSession; - (): ServerApplication; + /** + * Reset `.maxAge` to `.originalMaxAge`. + */ + resetMaxAge(): ExpressSession; - router: Handler; + /** + * Save the session data with optional callback `fn(err)`. + */ + save(fn: Function): ExpressSession; - use(route: string, callback: Function): ServerApplication; - use(route: string, server: ServerApplication): ServerApplication; - use(callback: Function): ServerApplication; - use(server: ServerApplication): ServerApplication; + /** + * Re-loads the session data _without_ altering + * the maxAge properties. Invokes the callback `fn(err)`, + * after which time if no exception has occurred the + * `req.session` property will be a new `Session` object, + * although representing the same session. + */ + reload(fn: Function): ExpressSession; - engine(ext: string, callback: Function): ServerApplication; + /** + * Destroy `this` session. + */ + destroy(fn: Function): ExpressSession; - param(param: Function): ServerApplication; - param(name: string, callback: Function): ServerApplication; - param(name: string, expressParam: any): ServerApplication; - param(name: any[], callback: Function): ServerApplication; + /** + * Regenerate this request's session. + */ + regenerate(fn: Function): ExpressSession; - set(name: string): ServerApplication; - set(name: string, val: any): ServerApplication; + user: any; - enabled(name: string): bool; - disabled(name: string): bool; + error: string; - enable(name: string): ServerApplication; - disable(name: string): ServerApplication; + success: string; - configure(env: string, callback: () => void ): ServerApplication; - configure(...params: any[]): ServerApplication; // covering this case: (...env: string[], callback: () => void) - configure(callback: () => void ): ServerApplication; + views: any; +} +declare var ExpressSession: { + /** + * Create a new `Session` with the given request and `data`. + */ + new (req: ExpressServerRequest, data: any): ExpressSession; +} - all(path: string, ...callbacks: Function[]): void; +interface ExpressServerRequest { - render(view: string, callback: (err: Error, html) => void ): void; - render(view: string, optionss: any, callback: (err: Error, html) => void ): void; + session: ExpressSession; - listen(port: number, hostname: string, backlog: number, callback: Function): void; - listen(port: number, callback: Function): void; - listen(path: string, callback?: Function): void; - listen(handle: any, listeningListener?: Function): void; + /** + * Return request header. + * + * The `Referrer` header field is special-cased, + * both `Referrer` and `Referer` are interchangeable. + * + * Examples: + * + * req.get('Content-Type'); + * // => "text/plain" + * + * req.get('content-type'); + * // => "text/plain" + * + * req.get('Something'); + * // => undefined + * + * Aliased as `req.header()`. + * + * @param name + */ + get (name: string): string; - get(name: string): any; - get(path: RegExp, handler: Handler): void; - get(path: string, ...callbacks: Handler[]): void; + header(name: string): string; - post(path: RegExp, handler: Handler ): void; - post(path: string, ...callbacks: Handler[]): void; + /** + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single mime type string + * such as "application/json", the extension name + * such as "json", a comma-delimted list such as "json, html, text/plain", + * or an array `["json", "html", "text/plain"]`. When a list + * or array is given the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * req.accepts('html'); + * // => "html" + * + * // Accept: text/*, application/json + * req.accepts('html'); + * // => "html" + * req.accepts('text/html'); + * // => "text/html" + * req.accepts('json, text'); + * // => "json" + * req.accepts('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * req.accepts('image/png'); + * req.accepts('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * req.accepts(['html', 'json']); + * req.accepts('html, json'); + * // => "json" + */ + accepts(type: string): string; - put(path: RegExp, handler: Handler ): void; - put(path: string, ...callbacks: Handler[]): void; + accepts(type: string[]): string; - del(path: RegExp, handler: Handler ): void; - del(path: string, ...callbacks: Handler[]): void; - } + /** + * Check if the given `charset` is acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param charset + */ + acceptsCharset(charset: string): bool; - export interface ServerRequest extends http.ServerRequest { + /** + * Check if the given `lang` is acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param lang + */ + acceptsLanguage(lang: string): bool; - accepted: any[]; - acceptedLanguages: string[]; - acceptedCharsets: string[]; + /** + * Parse Range header field, + * capping to the given `size`. + * + * Unspecified ranges such as "0-" require + * knowledge of your resource length. In + * the case of a byte range this is of course + * the total number of bytes. If the Range + * header field is not given `null` is returned, + * `-1` when unsatisfiable, `-2` when syntactically invalid. + * + * NOTE: remember that ranges are inclusive, so + * for example "Range: users=0-3" should respond + * with 4 users when available, not 3. + * + * @param size + */ + range(size: number): Array; - params: any; - query: any; - body: any; - files: any; + /** + * Return an array of Accepted media types + * ordered from highest quality to lowest. + * + * Examples: + * + * [ { value: 'application/json', + * quality: 1, + * type: 'application', + * subtype: 'json' }, + * { value: 'text/html', + * quality: 0.5, + * type: 'text', + * subtype: 'html' } ] + */ + accepted: Array; - route: any; - cookies: any; - signedCookies: any; + /** + * Return an array of Accepted languages + * ordered from highest quality to lowest. + * + * Examples: + * + * Accept-Language: en;q=.5, en-us + * ['en-us', 'en'] + */ + acceptedLanguages: Array; - get(field: string): string; - header(field: string): string; + /** + * Return an array of Accepted charsets + * ordered from highest quality to lowest. + * + * Examples: + * + * Accept-Charset: iso-8859-5;q=.2, unicode-1-1;q=0.8 + * ['unicode-1-1', 'iso-8859-5'] + */ + acceptedCharsets: Array; - accepts(types: string): any; - accepts(types: string[]): any; - acceptsCharset(charset: string): bool; - acceptsLanguage(lang: string): bool; + /** + * Return the value of param `name` when present or `defaultValue`. + * + * - Checks route placeholders, ex: _/user/:id_ + * - Checks body params, ex: id=12, {"id":12} + * - Checks query string params, ex: ?id=12 + * + * To utilize request bodies, `req.body` + * should be an object. This can be done by using + * the `connect.bodyParser()` middleware. + * + * @param name + * @param defaultValue + */ + param(name: string, defaultValue?: any): string; - range(size: number): number[]; + /** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains the give mime `type`. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * req.is('html'); + * req.is('text/html'); + * req.is('text/*'); + * // => true + * + * // When Content-Type is application/json + * req.is('json'); + * req.is('application/json'); + * req.is('application/*'); + * // => true + * + * req.is('html'); + * // => false + * + * @param type + */ + is(type: string): bool; - param(name: string, defaultValue?: any): string; - is(type: string): bool; + /** + * Return the protocol string "http" or "https" + * when requested with TLS. When the "trust proxy" + * setting is enabled the "X-Forwarded-Proto" header + * field will be trusted. If you're running behind + * a reverse proxy that supplies https for you this + * may be enabled. + */ + protocol: string; - protocol: string; - secure: bool; - ip: string; - ips: string[]; - auth: any; - subdomains: string[]; - path: string; - host: string; - fresh: bool; - stale: bool; - xhr: bool; - } + /** + * Short-hand for: + * + * req.protocol == 'https' + */ + secure: bool; - export interface ServerResponse extends http.ServerResponse { + /** + * Return the remote address, or when + * "trust proxy" is `true` return + * the upstream addr. + */ + ip: string; - charset: string; - locals: any; + /** + * When "trust proxy" is `true`, parse + * the "X-Forwarded-For" ip address list. + * + * For example if the value were "client, proxy1, proxy2" + * you would receive the array `["client", "proxy1", "proxy2"]` + * where "proxy2" is the furthest down-stream. + */ + ips: string[]; - status(code: number): ServerResponse; - links(links: any): ServerResponse; + /** + * Return basic auth credentials. + * + * Examples: + * + * // http://tobi:hello@example.com + * req.auth + * // => { username: 'tobi', password: 'hello' } + */ + auth: any; - send(status: number): ServerResponse; - send(bodyOrStatus: any): ServerResponse; - send(status: number, body: any): ServerResponse; - json(status: number): ServerResponse; - json(bodyOrStatus: any): ServerResponse; - json(status: number, body: any): ServerResponse; - jsonp(status: number): ServerResponse; - jsonp(bodyOrStatus: any): ServerResponse; - jsonp(status: number, body: any): ServerResponse; + /** + * Return subdomains as an array. + * + * Subdomains are the dot-separated parts of the host before the main domain of + * the app. By default, the domain of the app is assumed to be the last two + * parts of the host. This can be changed by setting "subdomain offset". + * + * For example, if the domain is "tobi.ferrets.example.com": + * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. + * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. + */ + subdomains: string[]; - sendfile(path: string): void; - sendfile(path: string, options: any): void; - sendfile(path: string, fn: Errback): void; - sendfile(path: string, options: any, fn: Errback): void; - download(path: string): void; - download(path: string, filename: string): void; - download(path: string, fn: Errback): void; - download(path: string, filename: string, fn: Errback): void; + /** + * Short-hand for `url.parse(req.url).pathname`. + */ + path: string; - type(type: string): ServerResponse; - contentType(type: string): ServerResponse; + /** + * Parse the "Host" header field hostname. + */ + host: string; - format(object: any): ServerResponse; - attachment(filename?: string): ServerResponse; + /** + * Check if the request is fresh, aka + * Last-Modified and/or the ETag + * still match. + */ + fresh: bool; - set(field: any): void; - set(field: string, value: string): void; - header(field: any): void; - header(field: string, value: string): void; + /** + * Check if the request is stale, aka + * "Last-Modified" and / or the "ETag" for the + * resource has changed. + */ + stale: bool; - get(field: string): string; + /** + * Check if the request was an _XMLHttpRequest_. + */ + xhr: bool; - clearCookie(name: string, options?: any): ServerResponse; - cookie(name: string, value: any, options?: CookieOptions): ServerResponse; + //body: { username: string; password: string; remember: bool; title: string; }; + body: any; - redirect(url: string): void; - redirect(status: number, url: string): void; - redirect(url: string, status: number): void; + //cookies: { string; remember: bool; }; + cookies: any; - render(view: string, options: any): void; - render(view: string, callback: (err: Error, html: any) => void ): void; - render(view: string, options: any, callback: (err: Error, html: any) => void ): void; - } + method: string; + + params: any; + + user: any; + + files: any; + + /** + * Clear cookie `name`. + * + * @param name + * @param options + */ + clearCookie(name: string, options?: any): ExpressServerResponse; + + query: any; + + route: any; + + signedCookies: any; + + originalUrl: string; +} + +interface ExpressServerResponse { + /** + * Set status `code`. + * + * @param code + */ + status(code: number): ExpressServerResponse; + + /** + * Set Link header field with the given `links`. + * + * Examples: + * + * res.links({ + * next: 'http://api.example.com/users?page=2', + * last: 'http://api.example.com/users?page=5' + * }); + * + * @param links + */ + links(links: any): ExpressServerResponse; + + /** + * Send a response. + * + * Examples: + * + * res.send(new Buffer('wahoo')); + * res.send({ some: 'json' }); + * res.send('

some html

'); + * res.send(404, 'Sorry, cant find that'); + * res.send(404); + */ + send(status: number): ExpressServerResponse; + + send(bodyOrStatus: any): ExpressServerResponse; + + send(status: number, body: any): ExpressServerResponse; + + + /** + * Send JSON response. + * + * Examples: + * + * res.json(null); + * res.json({ user: 'tj' }); + * res.json(500, 'oh noes!'); + * res.json(404, 'I dont have that'); + */ + json(status: number): ExpressServerResponse; + + json(bodyOrStatus: any): ExpressServerResponse; + + json(status: number, body: any): ExpressServerResponse; + + /** + * Send JSON response with JSONP callback support. + * + * Examples: + * + * res.jsonp(null); + * res.jsonp({ user: 'tj' }); + * res.jsonp(500, 'oh noes!'); + * res.jsonp(404, 'I dont have that'); + */ + jsonp(status: number): ExpressServerResponse; + + jsonp(bodyOrStatus: any): ExpressServerResponse; + + jsonp(status: number, body: any): ExpressServerResponse; + + /** + * Transfer the file at the given `path`. + * + * Automatically sets the _Content-Type_ response header field. + * The callback `fn(err)` is invoked when the transfer is complete + * or when an error occurs. Be sure to check `res.sentHeader` + * if you wish to attempt responding, as the header and some data + * may have already been transferred. + * + * Options: + * + * - `maxAge` defaulting to 0 + * - `root` root directory for relative filenames + * + * Examples: + * + * The following example illustrates how `res.sendfile()` may + * be used as an alternative for the `static()` middleware for + * dynamic situations. The code backing `res.sendfile()` is actually + * the same code, so HTTP cache support etc is identical. + * + * app.get('/user/:uid/photos/:file', function(req, res){ + * var uid = req.params.uid + * , file = req.params.file; + * + * req.user.mayViewFilesFrom(uid, function(yes){ + * if (yes) { + * res.sendfile('/uploads/' + uid + '/' + file); + * } else { + * res.send(403, 'Sorry! you cant see that.'); + * } + * }); + * }); + */ + sendfile(path: string): void; + + sendfile(path: string, options: any): void; + + sendfile(path: string, fn: Errback): void; + + sendfile(path: string, options: any, fn: Errback): void; + + /** + * Transfer the file at the given `path` as an attachment. + * + * Optionally providing an alternate attachment `filename`, + * and optional callback `fn(err)`. The callback is invoked + * when the data transfer is complete, or when an error has + * ocurred. Be sure to check `res.headerSent` if you plan to respond. + * + * This method uses `res.sendfile()`. + */ + download(path: string): void; + + download(path: string, filename: string): void; + + download(path: string, fn: Errback): void; + + download(path: string, filename: string, fn: Errback): void; + + /** + * Set _Content-Type_ response header with `type` through `mime.lookup()` + * when it does not contain "/", or set the Content-Type to `type` otherwise. + * + * Examples: + * + * res.type('.html'); + * res.type('html'); + * res.type('json'); + * res.type('application/json'); + * res.type('png'); + * + * @param type + */ + contentType(type: string): ExpressServerResponse; + + /** + * Set _Content-Type_ response header with `type` through `mime.lookup()` + * when it does not contain "/", or set the Content-Type to `type` otherwise. + * + * Examples: + * + * res.type('.html'); + * res.type('html'); + * res.type('json'); + * res.type('application/json'); + * res.type('png'); + * + * @param type + */ + type(type: string): ExpressServerResponse; + + /** + * Respond to the Acceptable formats using an `obj` + * of mime-type callbacks. + * + * This method uses `req.accepted`, an array of + * acceptable types ordered by their quality values. + * When "Accept" is not present the _first_ callback + * is invoked, otherwise the first match is used. When + * no match is performed the server responds with + * 406 "Not Acceptable". + * + * Content-Type is set for you, however if you choose + * you may alter this within the callback using `res.type()` + * or `res.set('Content-Type', ...)`. + * + * res.format({ + * 'text/plain': function(){ + * res.send('hey'); + * }, + * + * 'text/html': function(){ + * res.send('

hey

'); + * }, + * + * 'appliation/json': function(){ + * res.send({ message: 'hey' }); + * } + * }); + * + * In addition to canonicalized MIME types you may + * also use extnames mapped to these types: + * + * res.format({ + * text: function(){ + * res.send('hey'); + * }, + * + * html: function(){ + * res.send('

hey

'); + * }, + * + * json: function(){ + * res.send({ message: 'hey' }); + * } + * }); + * + * By default Express passes an `Error` + * with a `.status` of 406 to `next(err)` + * if a match is not made. If you provide + * a `.default` callback it will be invoked + * instead. + * + * @param obj + */ + format(obj: any): ExpressServerResponse; + + /** + * Set _Content-Disposition_ header to _attachment_ with optional `filename`. + * + * @param filename + */ + attachment(filename?: string): ExpressServerResponse; + + /** + * Set header `field` to `val`, or pass + * an object of header fields. + * + * Examples: + * + * res.set('Foo', ['bar', 'baz']); + * res.set('Accept', 'application/json'); + * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); + * + * Aliased as `res.header()`. + */ + set (field: any): void; + + set (field: string, value?: string): void; + + header(field: any): void; + + header(field: string, value?: string): void; + + /** + * Get value for header `field`. + * + * @param field + */ + get (field: string): string; + + /** + * Clear cookie `name`. + * + * @param name + * @param options + */ + clearCookie(name: string, options?: any): ExpressServerResponse; + + /** + * Set cookie `name` to `val`, with the given `options`. + * + * Options: + * + * - `maxAge` max-age in milliseconds, converted to `expires` + * - `signed` sign the cookie + * - `path` defaults to "/" + * + * Examples: + * + * // "Remember Me" for 15 minutes + * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); + * + * // save as above + * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) + */ + cookie(name: string, val: string, options: CookieOptions); + + cookie(name: string, val: any, options: CookieOptions); + + cookie(name: string, val: any); + + /** + * Set the location header to `url`. + * + * The given `url` can also be the name of a mapped url, for + * example by default express supports "back" which redirects + * to the _Referrer_ or _Referer_ headers or "/". + * + * Examples: + * + * res.location('/foo/bar').; + * res.location('http://example.com'); + * res.location('../login'); // /blog/post/1 -> /blog/login + * + * Mounting: + * + * When an application is mounted and `res.location()` + * is given a path that does _not_ lead with "/" it becomes + * relative to the mount-point. For example if the application + * is mounted at "/blog", the following would become "/blog/login". + * + * res.location('login'); + * + * While the leading slash would result in a location of "/login": + * + * res.location('/login'); + * + * @param url + */ + location(url: string); + + /** + * Redirect to the given `url` with optional response `status` + * defaulting to 302. + * + * The resulting `url` is determined by `res.location()`, so + * it will play nicely with mounted apps, relative paths, + * `"back"` etc. + * + * Examples: + * + * res.redirect('/foo/bar'); + * res.redirect('http://example.com'); + * res.redirect(301, 'http://example.com'); + * res.redirect('http://example.com', 301); + * res.redirect('../login'); // /blog/post/1 -> /blog/login + */ + redirect(url: string): void; + + redirect(status: number, url: string): void; + + redirect(url: string, status: number): void; + + /** + * Render `view` with the given `options` and optional callback `fn`. + * When a callback function is given a response will _not_ be made + * automatically, otherwise a response of _200_ and _text/html_ is given. + * + * Options: + * + * - `cache` boolean hinting to the engine it should cache + * - `filename` filename of the view being rendered + */ + render(view: string): void; + + render(view: string, options: any): void; + + render(view: string, callback: (err: Error, html: any) => void ): void; + + render(view: string, options: any, callback: (err: Error, html: any) => void ): void; + + locals: any; + + charset: string; +} + +interface ExpressApplication { + /** + * Initialize the server. + * + * - setup default configuration + * - setup default middleware + * - setup route reflection methods + */ + init(); + + /** + * Initialize application configuration. + */ + defaultConfiguration(); + + /** + * Proxy `connect#use()` to apply settings to + * mounted applications. + **/ + use(route: string, callback?: Function): ExpressApplication; + + use(route: string, server: ExpressApplication): ExpressApplication; + + use(callback: Function): ExpressApplication; + + use(server: ExpressApplication): ExpressApplication; + + /** + * Register the given template engine callback `fn` + * as `ext`. + * + * By default will `require()` the engine based on the + * file extension. For example if you try to render + * a "foo.jade" file Express will invoke the following internally: + * + * app.engine('jade', require('jade').__express); + * + * For engines that do not provide `.__express` out of the box, + * or if you wish to "map" a different extension to the template engine + * you may use this method. For example mapping the EJS template engine to + * ".html" files: + * + * app.engine('html', require('ejs').renderFile); + * + * In this case EJS provides a `.renderFile()` method with + * the same signature that Express expects: `(path, options, callback)`, + * though note that it aliases this method as `ejs.__express` internally + * so if you're using ".ejs" extensions you dont need to do anything. + * + * Some template engines do not follow this convention, the + * [Consolidate.js](https://github.com/visionmedia/consolidate.js) + * library was created to map all of node's popular template + * engines to follow this convention, thus allowing them to + * work seamlessly within Express. + */ + engine(ext: string, fn: Function): ExpressApplication; + + /** + * Map the given param placeholder `name`(s) to the given callback(s). + * + * Parameter mapping is used to provide pre-conditions to routes + * which use normalized placeholders. For example a _:user_id_ parameter + * could automatically load a user's information from the database without + * any additional code, + * + * The callback uses the samesignature as middleware, the only differencing + * being that the value of the placeholder is passed, in this case the _id_ + * of the user. Once the `next()` function is invoked, just like middleware + * it will continue on to execute the route, or subsequent parameter functions. + * + * app.param('user_id', function(req, res, next, id){ + * User.find(id, function(err, user){ + * if (err) { + * next(err); + * } else if (user) { + * req.user = user; + * next(); + * } else { + * next(new Error('failed to load user')); + * } + * }); + * }); + * + * @param name + * @param fn + */ + param(name: string, fn: Function): ExpressApplication; + + param(name: Array, fn: Function): ExpressApplication; + + /** + * Assign `setting` to `val`, or return `setting`'s value. + * + * app.set('foo', 'bar'); + * app.get('foo'); + * // => "bar" + * + * Mounted servers inherit their parent server's settings. + * + * @param setting + * @param val + */ + set (setting: string, val: string): ExpressApplication; + + /** + * Return the app's absolute pathname + * based on the parent(s) that have + * mounted it. + * + * For example if the application was + * mounted as "/admin", which itself + * was mounted as "/blog" then the + * return value would be "/blog/admin". + */ + path(): string; + + /** + * Check if `setting` is enabled (truthy). + * + * app.enabled('foo') + * // => false + * + * app.enable('foo') + * app.enabled('foo') + * // => true + */ + enabled(setting: string): bool; + + /** + * Check if `setting` is disabled. + * + * app.disabled('foo') + * // => true + * + * app.enable('foo') + * app.disabled('foo') + * // => false + * + * @param setting + */ + disabled(setting: string): bool; + + /** + * Enable `setting`. + * + * @param setting + */ + enable(setting: string): ExpressApplication; + + /** + * Disable `setting`. + * + * @param setting + */ + disable(setting: string): ExpressApplication; + + /** + * Configure callback for zero or more envs, + * when no `env` is specified that callback will + * be invoked for all environments. Any combination + * can be used multiple times, in any order desired. + * + * Examples: + * + * app.configure(function(){ + * // executed for all envs + * }); + * + * app.configure('stage', function(){ + * // executed staging env + * }); + * + * app.configure('stage', 'production', function(){ + * // executed for stage and production + * }); + * + * Note: + * + * These callbacks are invoked immediately, and + * are effectively sugar for the following: + * + * var env = process.env.NODE_ENV || 'development'; + * + * switch (env) { + * case 'development': + * ... + * break; + * case 'stage': + * ... + * break; + * case 'production': + * ... + * break; + * } + * + * @param env + * @param fn + */ + configure(env: string, fn: Function): ExpressApplication; + + configure(env0: string, env1: string, fn: Function): ExpressApplication; + + configure(env0: string, env1: string, env2: string, fn: Function): ExpressApplication; + + configure(env0: string, env1: string, env2: string, env3: string, fn: Function): ExpressApplication; + + configure(env0: string, env1: string, env2: string, env3: string, env4: string, fn: Function): ExpressApplication; + + configure(fn: Function): ExpressApplication; + + /** + * Special-cased "all" method, applying the given route `path`, + * middleware, and callback to _every_ HTTP method. + * + * @param path + * @param fn + */ + all(path: string, fn?: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any): ExpressApplication; + + all(path: string, ...callbacks: Function[]): void; + + /** + * Render the given view `name` name with `options` + * and a callback accepting an error and the + * rendered template string. + * + * Example: + * + * app.render('email', { name: 'Tobi' }, function(err, html){ + * // ... + * }) + * + * @param name + * @param options or fn + * @param fn + */ + render(name: string, options: string, fn: Function); + + render(name: string, fn: Function); + + get (name: string): any; + + get (name: string, handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any): any; + + get (name: string, + handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler2: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any): any; + + get (name: string, + handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler2: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler3: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any): any; + + get (name: string, + handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler2: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler3: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler4: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any): any; + + get (name: string, + handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler2: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler3: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler4: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler5: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any): any; + + get (name: string, + handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler2: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler3: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler4: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler5: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + ...handlers: any[]): any; + + get (name: RegExp): any; + + get (name: RegExp, handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any): any; + + get (name: RegExp, + handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler2: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any): any; + + get (name: RegExp, + handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler2: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler3: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any): any; + + get (name: RegExp, + handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler2: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler3: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler4: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any): any; + + get (name: RegExp, + handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler2: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler3: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler4: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler5: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + ...handlers: any[]): any; + + post(name: string): any; + + post(name: string, handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any): any; + + post(name: string, + handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler2: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any): any; + + post(name: string, + handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler2: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler3: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any): any; + + post(name: string, + handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler2: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler3: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler4: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any): any; + + post(name: string, + handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler2: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler3: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler4: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler5: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + ...handlers: any[]): any; + + post(name: RegExp): any; + + post(name: RegExp, handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any): any; + + post(name: RegExp, + handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler2: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any): any; + + post(name: RegExp, + handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler2: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler3: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any): any; + + post(name: RegExp, + handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler2: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler3: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler4: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any): any; + + post(name: RegExp, + handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler2: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler3: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler4: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler5: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + ...handlers: any[]): any; + + put(name: string): any; + + put(name: string, handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any): any; + + put(name: string, + handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler2: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any): any; + + put(name: string, + handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler2: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler3: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any): any; + + put(name: string, + handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler2: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler3: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler4: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any): any; + + put(name: string, + handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler2: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler3: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler4: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler5: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + ...handlers: any[]): any; + + put(name: RegExp): any; + + put(name: RegExp, handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any): any; + + put(name: RegExp, + handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler2: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any): any; + + put(name: RegExp, + handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler2: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler3: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any): any; + + put(name: RegExp, + handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler2: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler3: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler4: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any): any; + + put(name: RegExp, + handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler2: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler3: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler4: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler5: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + ...handlers: any[]): any; + + del(name: string): any; + + del(name: string, handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any): any; + + del(name: string, + handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler2: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any): any; + + del(name: string, + handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler2: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler3: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any): any; + + del(name: string, + handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler2: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler3: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler4: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any): any; + + del(name: string, + handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler2: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler3: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler4: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler5: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + ...handlers: any[]): any; + + del(name: RegExp): any; + + del(name: RegExp, handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any): any; + + del(name: RegExp, + handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler2: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any): any; + + del(name: RegExp, + handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler2: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler3: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any): any; + + del(name: RegExp, + handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler2: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler3: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler4: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any): any; + + del(name: RegExp, + handler: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler2: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler3: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler4: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + handler5: (req: ExpressServerRequest, res: ExpressServerResponse, next: Function) => any, + ...handlers: any[]): any; + + /** + * Listen for connections. + * + * A node `http.Server` is returned, with this + * application (which is a `Function`) as its + * callback. If you wish to create both an HTTP + * and HTTPS server you may do so with the "http" + * and "https" modules as shown here: + * + * var http = require('http') + * , https = require('https') + * , express = require('express') + * , app = express(); + * + * http.createServer(app).listen(80); + * https.createServer({ ... }, app).listen(443); + */ + listen(port: number, hostname: string, backlog: number, callback: Function): void; + + listen(port: number, callback: Function): void; + + listen(path: string, callback?: Function): void; + + listen(handle: any, listeningListener?: Function): void; + + render(view: string, callback: (err: Error, html) => void ): void; + + render(view: string, optionss: any, callback: (err: Error, html) => void ): void; + + route: Route; + + router: string; + + settings: any; + + resource: any; + + map: any; + + locals: any; +} + +interface Express extends ExpressApplication { + /** + * Framework version. + */ + version: string; + + /** + * Expose mime. + */ + mime: string; + + (): ExpressApplication; + + /** + * Create an express application. + */ + createApplication(): ExpressApplication; + + createServer(): ExpressApplication; + + application: any; + + request: ExpressServerRequest; + + response: ExpressServerResponse; } declare module "express" { - export function (): _express.ServerApplication; - export function createServer(): ServerApplication; - export function static(path: string): any; - export var listen; + export function (): Express; - // Connect middleware + /** + * Body parser: + * + * Parse request bodies, supports _application/json_, + * _application/x-www-form-urlencoded_, and _multipart/form-data_. + * + * This is equivalent to: + * + * app.use(connect.json()); + * app.use(connect.urlencoded()); + * app.use(connect.multipart()); + * + * Examples: + * + * connect() + * .use(connect.bodyParser()) + * .use(function(req, res) { + * res.end('viewing user ' + req.body.user.name); + * }); + * + * $ curl -d 'user[name]=tj' http://local/ + * $ curl -d '{"user":{"name":"tj"}}' -H "Content-Type: application/json" http://local/ + * + * View [json](json.html), [urlencoded](urlencoded.html), and [multipart](multipart.html) for more info. + * + * @param options + */ export function bodyParser(options?: any): Handler; - export function errorHandler(opts?: any): Handler; - export function methodOverride(): Handler; - export interface ServerApplication extends _express.ServerApplication {} - export interface ServerRequest extends _express.ServerRequest {} - export interface ServerResponse extends _express.ServerResponse {} - export interface Handler extends _express.Handler {} -} + /** + * Error handler: + * + * Development error handler, providing stack traces + * and error message responses for requests accepting text, html, + * or json. + * + * Text: + * + * By default, and when _text/plain_ is accepted a simple stack trace + * or error message will be returned. + * + * JSON: + * + * When _application/json_ is accepted, connect will respond with + * an object in the form of `{ "error": error }`. + * + * HTML: + * + * When accepted connect will output a nice html stack trace. + */ + export function errorHandler(opts?: any): Handler; + + /** + * Method Override: + * + * Provides faux HTTP method support. + * + * Pass an optional `key` to use when checking for + * a method override, othewise defaults to _\_method_. + * The original method is available via `req.originalMethod`. + * + * @param key + */ + export function methodOverride(key?: string): Handler; + + /** + * Cookie parser: + * + * Parse _Cookie_ header and populate `req.cookies` + * with an object keyed by the cookie names. Optionally + * you may enabled signed cookie support by passing + * a `secret` string, which assigns `req.secret` so + * it may be used by other middleware. + * + * Examples: + * + * connect() + * .use(connect.cookieParser('optional secret string')) + * .use(function(req, res, next){ + * res.end(JSON.stringify(req.cookies)); + * }) + * + * @param secret + */ + export function cookieParser(secret?: string): Handler; + + /** + * Session: + * + * Setup session store with the given `options`. + * + * Session data is _not_ saved in the cookie itself, however + * cookies are used, so we must use the [cookieParser()](cookieParser.html) + * middleware _before_ `session()`. + * + * Examples: + * + * connect() + * .use(connect.cookieParser()) + * .use(connect.session({ secret: 'keyboard cat', key: 'sid', cookie: { secure: true }})) + * + * Options: + * + * - `key` cookie name defaulting to `connect.sid` + * - `store` session store instance + * - `secret` session cookie is signed with this secret to prevent tampering + * - `cookie` session cookie settings, defaulting to `{ path: '/', httpOnly: true, maxAge: null }` + * - `proxy` trust the reverse proxy when setting secure cookies (via "x-forwarded-proto") + * + * Cookie option: + * + * By default `cookie.maxAge` is `null`, meaning no "expires" parameter is set + * so the cookie becomes a browser-session cookie. When the user closes the + * browser the cookie (and session) will be removed. + * + * ## req.session + * + * To store or access session data, simply use the request property `req.session`, + * which is (generally) serialized as JSON by the store, so nested objects + * are typically fine. For example below is a user-specific view counter: + * + * connect() + * .use(connect.favicon()) + * .use(connect.cookieParser()) + * .use(connect.session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }})) + * .use(function(req, res, next){ + * var sess = req.session; + * if (sess.views) { + * res.setHeader('Content-Type', 'text/html'); + * res.write('

views: ' + sess.views + '

'); + * res.write('

expires in: ' + (sess.cookie.maxAge / 1000) + 's

'); + * res.end(); + * sess.views++; + * } else { + * sess.views = 1; + * res.end('welcome to the session demo. refresh!'); + * } + * } + * )).listen(3000); + * + * ## Session#regenerate() + * + * To regenerate the session simply invoke the method, once complete + * a new SID and `Session` instance will be initialized at `req.session`. + * + * req.session.regenerate(function(err){ + * // will have a new session here + * }); + * + * ## Session#destroy() + * + * Destroys the session, removing `req.session`, will be re-generated next request. + * + * req.session.destroy(function(err){ + * // cannot access session here + * }); + * + * ## Session#reload() + * + * Reloads the session data. + * + * req.session.reload(function(err){ + * // session updated + * }); + * + * ## Session#save() + * + * Save the session. + * + * req.session.save(function(err){ + * // session saved + * }); + * + * ## Session#touch() + * + * Updates the `.maxAge` property. Typically this is + * not necessary to call, as the session middleware does this for you. + * + * ## Session#cookie + * + * Each session has a unique cookie object accompany it. This allows + * you to alter the session cookie per visitor. For example we can + * set `req.session.cookie.expires` to `false` to enable the cookie + * to remain for only the duration of the user-agent. + * + * ## Session#maxAge + * + * Alternatively `req.session.cookie.maxAge` will return the time + * remaining in milliseconds, which we may also re-assign a new value + * to adjust the `.expires` property appropriately. The following + * are essentially equivalent + * + * var hour = 3600000; + * req.session.cookie.expires = new Date(Date.now() + hour); + * req.session.cookie.maxAge = hour; + * + * For example when `maxAge` is set to `60000` (one minute), and 30 seconds + * has elapsed it will return `30000` until the current request has completed, + * at which time `req.session.touch()` is called to reset `req.session.maxAge` + * to its original value. + * + * req.session.cookie.maxAge; + * // => 30000 + * + * Session Store Implementation: + * + * Every session store _must_ implement the following methods + * + * - `.get(sid, callback)` + * - `.set(sid, session, callback)` + * - `.destroy(sid, callback)` + * + * Recommended methods include, but are not limited to: + * + * - `.length(callback)` + * - `.clear(callback)` + * + * For an example implementation view the [connect-redis](http://github.com/visionmedia/connect-redis) repo. + * + * @param options + */ + export function session(options?: any): Handler; + + /** + * Hash the given `sess` object omitting changes + * to `.cookie`. + * + * @param sess + */ + export function hash(sess: string): string; + + /** + * Static: + * + * Static file server with the given `root` path. + * + * Examples: + * + * var oneDay = 86400000; + * + * connect() + * .use(connect.static(__dirname + '/public')) + * + * connect() + * .use(connect.static(__dirname + '/public', { maxAge: oneDay })) + * + * Options: + * + * - `maxAge` Browser cache maxAge in milliseconds. defaults to 0 + * - `hidden` Allow transfer of hidden files. defaults to false + * - `redirect` Redirect to trailing "/" when the pathname is a dir. defaults to true + * + * @param root + * @param options + */ + export function static (root: string, options?: any): Handler; + + /** + * Basic Auth: + * + * Enfore basic authentication by providing a `callback(user, pass)`, + * which must return `true` in order to gain access. Alternatively an async + * method is provided as well, invoking `callback(user, pass, callback)`. Populates + * `req.user`. The final alternative is simply passing username / password + * strings. + * + * Simple username and password + * + * connect(connect.basicAuth('username', 'password')); + * + * Callback verification + * + * connect() + * .use(connect.basicAuth(function(user, pass){ + * return 'tj' == user & 'wahoo' == pass; + * })) + * + * Async callback verification, accepting `fn(err, user)`. + * + * connect() + * .use(connect.basicAuth(function(user, pass, fn){ + * User.authenticate({ user: user, pass: pass }, fn); + * })) + * + * @param callback or username + * @param realm + */ + export function basicAuth(callback: Function, realm: string); + + export function basicAuth(callback: string, realm: string); + + export function basicAuth(callback: Function); + + /** + * Compress: + * + * Compress response data with gzip/deflate. + * + * Filter: + * + * A `filter` callback function may be passed to + * replace the default logic of: + * + * exports.filter = function(req, res){ + * return /json|text|javascript/.test(res.getHeader('Content-Type')); + * }; + * + * Options: + * + * All remaining options are passed to the gzip/deflate + * creation functions. Consult node's docs for additional details. + * + * - `chunkSize` (default: 16*1024) + * - `windowBits` + * - `level`: 0-9 where 0 is no compression, and 9 is slow but best compression + * - `memLevel`: 1-9 low is slower but uses less memory, high is fast but uses more + * - `strategy`: compression strategy + * + * @param options + */ + export function compress(options?: any): Handler; + + /** + * Cookie Session: + * + * Cookie session middleware. + * + * var app = connect(); + * app.use(connect.cookieParser()); + * app.use(connect.cookieSession({ secret: 'tobo!', cookie: { maxAge: 60 * 60 * 1000 }})); + * + * Options: + * + * - `key` cookie name defaulting to `connect.sess` + * - `secret` prevents cookie tampering + * - `cookie` session cookie settings, defaulting to `{ path: '/', httpOnly: true, maxAge: null }` + * - `proxy` trust the reverse proxy when setting secure cookies (via "x-forwarded-proto") + * + * Clearing sessions: + * + * To clear the session simply set its value to `null`, + * `cookieSession()` will then respond with a 1970 Set-Cookie. + * + * req.session = null; + * + * @param options + */ + export function cookieSession(options?: any): Handler; + + /** + * Anti CSRF: + * + * CRSF protection middleware. + * + * By default this middleware generates a token named "_csrf" + * which should be added to requests which mutate + * state, within a hidden form field, query-string etc. This + * token is validated against the visitor's `req.session._csrf` + * property. + * + * The default `value` function checks `req.body` generated + * by the `bodyParser()` middleware, `req.query` generated + * by `query()`, and the "X-CSRF-Token" header field. + * + * This middleware requires session support, thus should be added + * somewhere _below_ `session()` and `cookieParser()`. + * + * Options: + * + * - `value` a function accepting the request, returning the token + * + * @param options + */ + export function csrf(options: any); + + /** + * Directory: + * + * Serve directory listings with the given `root` path. + * + * Options: + * + * - `hidden` display hidden (dot) files. Defaults to false. + * - `icons` display icons. Defaults to false. + * - `filter` Apply this filter function to files. Defaults to false. + * + * @param root + * @param options + */ + export function directory(root: string, options?: any): Handler; + + /** + * Favicon: + * + * By default serves the connect favicon, or the favicon + * located by the given `path`. + * + * Options: + * + * - `maxAge` cache-control max-age directive, defaulting to 1 day + * + * Examples: + * + * Serve default favicon: + * + * connect() + * .use(connect.favicon()) + * + * Serve favicon before logging for brevity: + * + * connect() + * .use(connect.favicon()) + * .use(connect.logger('dev')) + * + * Serve custom favicon: + * + * connect() + * .use(connect.favicon('public/favicon.ico)) + * + * @param path + * @param options + */ + export function favicon(path?: string, options?: any); + + /** + * JSON: + * + * Parse JSON request bodies, providing the + * parsed object as `req.body`. + * + * Options: + * + * - `strict` when `false` anything `JSON.parse()` accepts will be parsed + * - `reviver` used as the second "reviver" argument for JSON.parse + * - `limit` byte limit disabled by default + * + * @param options + */ + export function json(options?: any): Handler; + + /** + * Limit: + * + * Limit request bodies to the given size in `bytes`. + * + * A string representation of the bytesize may also be passed, + * for example "5mb", "200kb", "1gb", etc. + * + * connect() + * .use(connect.limit('5.5mb')) + * .use(handleImageUpload) + */ + export function limit(bytes: number): Handler; + + export function limit(bytes: string): Handler; + + /** + * Logger: + * + * Log requests with the given `options` or a `format` string. + * + * Options: + * + * - `format` Format string, see below for tokens + * - `stream` Output stream, defaults to _stdout_ + * - `buffer` Buffer duration, defaults to 1000ms when _true_ + * - `immediate` Write log line on request instead of response (for response times) + * + * Tokens: + * + * - `:req[header]` ex: `:req[Accept]` + * - `:res[header]` ex: `:res[Content-Length]` + * - `:http-version` + * - `:response-time` + * - `:remote-addr` + * - `:date` + * - `:method` + * - `:url` + * - `:referrer` + * - `:user-agent` + * - `:status` + * + * Formats: + * + * Pre-defined formats that ship with connect: + * + * - `default` ':remote-addr - - [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"' + * - `short` ':remote-addr - :method :url HTTP/:http-version :status :res[content-length] - :response-time ms' + * - `tiny` ':method :url :status :res[content-length] - :response-time ms' + * - `dev` concise output colored by response status for development use + * + * Examples: + * + * connect.logger() // default + * connect.logger('short') + * connect.logger('tiny') + * connect.logger({ immediate: true, format: 'dev' }) + * connect.logger(':method :url - :referrer') + * connect.logger(':req[content-type] -> :res[content-type]') + * connect.logger(function(tokens, req, res){ return 'some format string' }) + * + * Defining Tokens: + * + * To define a token, simply invoke `connect.logger.token()` with the + * name and a callback function. The value returned is then available + * as ":type" in this case. + * + * connect.logger.token('type', function(req, res){ return req.headers['content-type']; }) + * + * Defining Formats: + * + * All default formats are defined this way, however it's public API as well: + * + * connect.logger.format('name', 'string or function') + */ + export function logger(options: string): Handler; + + export function logger(options: Function): Handler; + + export function logger(options?: any): Handler; + + /** + * Compile `fmt` into a function. + * + * @param fmt + */ + export function compile(fmt: string): Handler; + + /** + * Define a token function with the given `name`, + * and callback `fn(req, res)`. + * + * @param name + * @param fn + */ + export function token(name: string, fn: Function): any; + + /** + * Define a `fmt` with the given `name`. + */ + export function format(name: string, str: string): any; + + export function format(name: string, str: Function): any; + + /** + * Query: + * + * Automatically parse the query-string when available, + * populating the `req.query` object. + * + * Examples: + * + * connect() + * .use(connect.query()) + * .use(function(req, res){ + * res.end(JSON.stringify(req.query)); + * }); + * + * The `options` passed are provided to qs.parse function. + */ + export function query(options: any): Handler; + + /** + * Reponse time: + * + * Adds the `X-Response-Time` header displaying the response + * duration in milliseconds. + */ + export function responseTime(): Handler; + + /** + * Static cache: + * + * Enables a memory cache layer on top of + * the `static()` middleware, serving popular + * static files. + * + * By default a maximum of 128 objects are + * held in cache, with a max of 256k each, + * totalling ~32mb. + * + * A Least-Recently-Used (LRU) cache algo + * is implemented through the `Cache` object, + * simply rotating cache objects as they are + * hit. This means that increasingly popular + * objects maintain their positions while + * others get shoved out of the stack and + * garbage collected. + * + * Benchmarks: + * + * static(): 2700 rps + * node-static: 5300 rps + * static() + staticCache(): 7500 rps + * + * Options: + * + * - `maxObjects` max cache objects [128] + * - `maxLength` max cache object length 256kb + */ + export function staticCache(options: any): Handler; + + /** + * Timeout: + * + * Times out the request in `ms`, defaulting to `5000`. The + * method `req.clearTimeout()` is added to revert this behaviour + * programmatically within your application's middleware, routes, etc. + * + * The timeout error is passed to `next()` so that you may customize + * the response behaviour. This error has the `.timeout` property as + * well as `.status == 408`. + */ + export function timeout(ms: number): Handler; + + /** + * Vhost: + * + * Setup vhost for the given `hostname` and `server`. + * + * connect() + * .use(connect.vhost('foo.com', fooApp)) + * .use(connect.vhost('bar.com', barApp)) + * .use(connect.vhost('*.com', mainApp)) + * + * The `server` may be a Connect server or + * a regular Node `http.Server`. + * + * @param hostname + * @param server + */ + export function vhost(hostname: string, server: any): Handler; + + export function urlencoded(): any; + + export function multipart(): any; +} \ No newline at end of file diff --git a/fabricjs/fabricjs.d.ts b/fabricjs/fabricjs.d.ts index ec4559e945..256e4cb41b 100644 --- a/fabricjs/fabricjs.d.ts +++ b/fabricjs/fabricjs.d.ts @@ -758,6 +758,7 @@ declare module fabric { fromURL(url: string): IImage; fromURL(url: string, callback: (image: IImage) => any): IImage; fromURL(url: string, callback: (image: IImage) => any, objObjects: IObjectOptions): IImage; + new (element: HTMLImageElement, objObjects: IObjectOptions): IImage; prototype: any; filters: diff --git a/filesystem/filesystem-tests.ts b/filesystem/filesystem-tests.ts new file mode 100644 index 0000000000..8f175db98d --- /dev/null +++ b/filesystem/filesystem-tests.ts @@ -0,0 +1,49 @@ +/// +// http://www.w3.org/TR/file-system-api/ + +// 2. Introduction +declare function getAsText(file:File): void; +declare function writeDataToLogFile(fileWriter:FileWriterSync): void; + +function useAsyncFS(fs:FileSystem):void { + // see getAsText example in [FILE-API-ED]. + fs.root.getFile("already_there.txt", null, function (f:FileEntry): void{ + + // In the example of the specification, there is a following code: + // + // getAsText(f.file()); + // + // It seems wrong because f is ASYNCRONOUS file system. + f.file(getAsText); + + }); + + // But now we can also write to the file; see [FILE-WRITER-ED]. + fs.root.getFile("logFile", {create: true}, function (f:FileEntry): void{ + f.createWriter(writeDataToLogFile); + }); +} +window.requestFileSystem(window.TEMPORARY, 1024 * 1024, function(fs:FileSystem): void{ + useAsyncFS(fs); +}); + +// In a worker: + +var tempFS:FileSystemSync = window.requestFileSystemSync(window.TEMPORARY, 1024 * 1024); +var logFile:FileEntrySync = tempFS.root.getFile("logFile", {create: true}); +var writer:FileWriterSync = logFile.createWriter(); +writer.seek(writer.length); +writeDataToLogFile(writer); + + +// 5.2 The Flags dictionary +var fsSync:FileSystemSync = window.requestFileSystemSync(window.TEMPORARY, 1024 * 1024); +// Get the data directory, creating it if it doesn't exist. +var dataDir:DirectoryEntrySync = fsSync.root.getDirectory("data", {create: true}); + +// Create the lock file, if and only if it doesn't exist. +try { + var lockFile:FileEntrySync = dataDir.getFile("lockfile.txt", {create: true, exclusive: true}); +} catch (ex) { + // It already exists, or something else went wrong. +} diff --git a/filesystem/filesystem.d.ts b/filesystem/filesystem.d.ts new file mode 100644 index 0000000000..90b159f752 --- /dev/null +++ b/filesystem/filesystem.d.ts @@ -0,0 +1,528 @@ +// Type Definitions for File API: Directories and System (File System API) +// Project: http://www.w3.org/TR/file-system-api/ +// Definitions by: Kon +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface LocalFileSystem { + + /** + * Used for storage with no guarantee of persistence. + */ + TEMPORARY:number; + + /** + * Used for storage that should not be removed by the user agent without application or user permission. + */ + PERSISTENT:number; + + /** + * Requests a filesystem in which to store application data. + * @param type Whether the filesystem requested should be persistent, as defined above. Use one of TEMPORARY or PERSISTENT. + * @param size This is an indicator of how much storage space, in bytes, the application expects to need. + * @param successCallback The callback that is called when the user agent provides a filesystem. + * @param errorCallback A callback that is called when errors happen, or when the request to obtain the filesystem is denied. + */ + requestFileSystem(type:number, size:number, successCallback:FileSystemCallback, errorCallback?:ErrorCallback):void; + + /** + * Allows the user to look up the Entry for a file or directory referred to by a local URL. + * @param url A URL referring to a local file in a filesystem accessable via this API. + * @param successCallback A callback that is called to report the Entry to which the supplied URL refers. + * @param errorCallback A callback that is called when errors happen, or when the request to obtain the Entry is denied. + */ + resolveLocalFileSystemURL(url:string, successCallback:EntryCallback, errorCallback?:ErrorCallback):void; + + /** + * see requestFileSystem. + */ + webkitRequestFileSystem(type:number, size:number, successCallback:FileSystemCallback, errorCallback?:ErrorCallback):void; +} + +interface LocalFileSystemSync { + /** + * Used for storage with no guarantee of persistence. + */ + TEMPORARY:number; + + /** + * Used for storage that should not be removed by the user agent without application or user permission. + */ + PERSISTENT:number; + + /** + * Requests a filesystem in which to store application data. + * @param type Whether the filesystem requested should be persistent, as defined above. Use one of TEMPORARY or PERSISTENT. + * @param size This is an indicator of how much storage space, in bytes, the application expects to need. + */ + requestFileSystemSync(type:number, size:number):FileSystemSync; + + /** + * Allows the user to look up the Entry for a file or directory referred to by a local URL. + * @param url A URL referring to a local file in a filesystem accessable via this API. + */ + resolveLocalFileSystemSyncURL(url:string):EntrySync; + + /** + * see requestFileSystemSync + */ + webkitRequestFileSystemSync(type:number, size:number):FileSystemSync; +} + +interface Metadata { + /** + * This is the time at which the file or directory was last modified. + * @readonly + */ + modificationTime:Date; + + /** + * The size of the file, in bytes. This must return 0 for directories. + * @readonly + */ + size:number; +} + +interface Flags { + /** + * Used to indicate that the user wants to create a file or directory if it was not previously there. + */ + create?:bool; + + /** + * By itself, exclusive must have no effect. Used with create, it must cause getFile and getDirectory to fail if the target path already exists. + */ + exclusive?:bool; +} + +/** + * This interface represents a file system. + */ +interface FileSystem{ + /** + * This is the name of the file system. The specifics of naming filesystems is unspecified, but a name must be unique across the list of exposed file systems. + * @readonly + */ + name: string; + + /** + * The root directory of the file system. + * @readonly + */ + root:any; +} + +interface Entry { + + /** + * Entry is a file. + */ + isFile:bool; + + /** + * Entry is a directory. + */ + isDirectory:bool; + + /** + * Look up metadata about this entry. + * @param successCallback A callback that is called with the time of the last modification. + * @param errorCallback ErrorCallback A callback that is called when errors happen. + */ + getMetadata(successCallback:MetadataCallback, errorCallback?:ErrorCallback):void; + + /** + * The name of the entry, excluding the path leading to it. + */ + name:string; + + /** + * The full absolute path from the root to the entry. + */ + fullPath:string; + + /** + * The file system on which the entry resides. + */ + filesystem:FileSystem; + + /** + * Move an entry to a different location on the file system. It is an error to try to: + * + * + *
  • move a directory inside itself or to any child at any depth;
  • + *
  • move an entry into its parent if a name different from its current one isn't provided;
  • + *
  • move a file to a path occupied by a directory;
  • + *
  • move a directory to a path occupied by a file;
  • + *
  • move any element to a path occupied by a directory which is not empty.
  • + *
      + * + * A move of a file on top of an existing file must attempt to delete and replace that file. + * A move of a directory on top of an existing empty directory must attempt to delete and replace that directory. + */ + moveTo(parent:DirectoryEntry, newName?:string, successCallback?:EntryCallback, errorCallback?:ErrorCallback):string; + + /** + * Copy an entry to a different location on the file system. It is an error to try to: + * + *
        + *
      • copy a directory inside itself or to any child at any depth;
      • + *
      • copy an entry into its parent if a name different from its current one isn't provided;
      • + *
      • copy a file to a path occupied by a directory;
      • + *
      • copy a directory to a path occupied by a file;
      • + *
      • copy any element to a path occupied by a directory which is not empty.
      • + *
      • A copy of a file on top of an existing file must attempt to delete and replace that file.
      • + *
      • A copy of a directory on top of an existing empty directory must attempt to delete and replace that directory.
      • + *
      + * + * Directory copies are always recursive--that is, they copy all contents of the directory. + */ + copyTo(parent:DirectoryEntry, newName?:string, successCallback?:EntryCallback, errorCallback?:ErrorCallback):string; + + /** + * Returns a URL that can be used to identify this entry. Unlike the URN defined in [FILE-API-ED], it has no specific expiration; as it describes a location on disk, it should be valid at least as long as that location exists. + */ + toURL():string; + + /** + * Deletes a file or directory. It is an error to attempt to delete a directory that is not empty. It is an error to attempt to delete the root directory of a filesystem. + * @param successCallback A callback that is called on success. + * @param errorCallback A callback that is called when errors happen. + */ + remove(successCallback:VoidCallback, errorCallback?:ErrorCallback):void; + + /** + * Look up the parent DirectoryEntry containing this Entry. If this Entry is the root of its filesystem, its parent is itself. + * @param successCallback A callback that is called to return the parent Entry. + * @param errorCallback A callback that is called when errors happen. + */ + getParent(successCallback:EntryCallback, errorCallback?:ErrorCallback):void; +} + +/** + * This interface represents a directory on a file system. + */ +interface DirectoryEntry extends Entry { + /** + * Creates a new DirectoryReader to read Entries from this Directory. + */ + createReader():DirectoryReader; + + /** + * Creates or looks up a file. + * @param path Either an absolute path or a relative path from this DirectoryEntry to the file to be looked up or created. It is an error to attempt to create a file whose immediate parent does not yet exist. + * @param options + *
        + *
      • If create and exclusive are both true, and the path already exists, getFile must fail.
      • + *
      • If create is true, the path doesn't exist, and no other error occurs, getFile must create it as a zero-length file and return a corresponding FileEntry.
      • + *
      • If create is not true and the path doesn't exist, getFile must fail.
      • + *
      • If create is not true and the path exists, but is a directory, getFile must fail.
      • + *
      • Otherwise, if no other error occurs, getFile must return a FileEntry corresponding to path.
      • + *
      + * @param successCallback A callback that is called to return the File selected or created. + * @param errorCallback A callback that is called when errors happen. + */ + getFile(path:string, options?:Flags, successCallback?:EntryCallback, errorCallback?:ErrorCallback):void; + + /** + * Creates or looks up a directory. + * @param path Either an absolute path or a relative path from this DirectoryEntry to the directory to be looked up or created. It is an error to attempt to create a directory whose immediate parent does not yet exist. + * @param options + *
        + *
      • If create and exclusive are both true and the path already exists, getDirectory must fail.
      • + *
      • If create is true, the path doesn't exist, and no other error occurs, getDirectory must create and return a corresponding DirectoryEntry.
      • + *
      • If create is not true and the path doesn't exist, getDirectory must fail.
      • + *
      • If create is not true and the path exists, but is a file, getDirectory must fail.
      • + *
      • Otherwise, if no other error occurs, getDirectory must return a DirectoryEntry corresponding to path.
      • + *
      + * @param successCallback A callback that is called to return the DirectoryEntry selected or created. + * @param errorCallback A callback that is called when errors happen. + * + */ + getDirectory(path:string, options?:Flags, successCallback?:EntryCallback, errorCallback?:ErrorCallback):void; + + /** + * Deletes a directory and all of its contents, if any. In the event of an error [e.g. trying to delete a directory that contains a file that cannot be removed], some of the contents of the directory may be deleted. It is an error to attempt to delete the root directory of a filesystem. + * @param successCallback A callback that is called on success. + * @param errorCallback A callback that is called when errors happen. + */ + removeRecursively(successCallback:VoidCallback, errorCallback?:ErrorCallback):void; +} + +/** + * This interface lets a user list files and directories in a directory. If there are no additions to or deletions from a directory between the first and last call to readEntries, and no errors occur, then: + *
        + *
      • A series of calls to readEntries must return each entry in the directory exactly once.
      • + *
      • Once all entries have been returned, the next call to readEntries must produce an empty array.
      • + *
      • If not all entries have been returned, the array produced by readEntries must not be empty.
      • + *
      • The entries produced by readEntries must not include the directory itself ["."] or its parent [".."].
      • + *
      + */ +interface DirectoryReader { + /** + * Read the next block of entries from this directory. + * @param successCallback Called once per successful call to readEntries to deliver the next previously-unreported set of Entries in the associated Directory. If all Entries have already been returned from previous invocations of readEntries, successCallback must be called with a zero-length array as an argument. + * @param errorCallback A callback indicating that there was an error reading from the Directory. + */ + readEntries(successCallback:EntriesCallback, errorCallback?:ErrorCallback):void; +} + +/** + * This interface represents a file on a file system. + */ +interface FileEntry extends Entry { + /** + * Creates a new FileWriter associated with the file that this FileEntry represents. + * @param successCallback A callback that is called with the new FileWriter. + * @param errorCallback A callback that is called when errors happen. + */ + createWriter(successCallback:FileWriterCallback, errorCallback?:ErrorCallback):void; + + /** + * Returns a File that represents the current state of the file that this FileEntry represents. + * @param successCallback A callback that is called with the File. + * @param errorCallback A callback that is called when errors happen. + */ + file(successCallback:FileCallback, errorCallback?:ErrorCallback):void; +} + +/** + * When requestFileSystem() succeeds, the following callback is made. + */ +interface FileSystemCallback { + /** + * @param filesystem The file systems to which the app is granted access. + */ + (filesystem:FileSystem):void; +} + +/** + * This interface is the callback used to look up Entry objects. + */ +interface EntryCallback { + /** + * @param entry + */ + (entry:Entry):void; +} + +/** + * When readEntries() succeeds, the following callback is made. + */ +interface EntriesCallback { + (entries:Entry[]):void; +} + +/** + * This interface is the callback used to look up file and directory metadata. + */ +interface MetadataCallback { + (metadata:Metadata):void; +} + +/** + * This interface is the callback used to create a FileWriter. + */ +interface FileWriterCallback { + (fileWriter:FileWriter):void; +} + +/** + * This interface is the callback used to obtain a File. + */ +interface FileCallback { + (file:File):void; +} + +/** + * This interface is the generic callback used to indicate success of an asynchronous method. + */ +interface VoidCallback { + ():void; +} + +/** + * When an error occurs, the following callback is made. + */ +interface ErrorCallback { + (err:DOMError):void; +} + + +/** + * This interface represents a file system. + */ +interface FileSystemSync { + /** + * This is the name of the file system. The specifics of naming filesystems is unspecified, but a name must be unique across the list of exposed file systems. + */ + name:string; + + /** + * root The root directory of the file system. + */ + root:DirectoryEntrySync; +} + +/** + * An abstract interface representing entries in a file system, each of which may be a FileEntrySync or DirectoryEntrySync. + */ +interface EntrySync{ + /** + * EntrySync is a file. + * @readonly + */ + isFile:bool; + + /** + * EntrySync is a directory. + * @readonly + */ + isDirectory:bool; + + /** + * Look up metadata about this entry. + */ + getMetadata():Metadata; + + /** + * The name of the entry, excluding the path leading to it. + */ + name:string; + + /** + * The full absolute path from the root to the entry. + */ + fullPath:string; + + /** + * The file system on which the entry resides. + */ + filesystem:FileSystemSync; + + /** + * Move an entry to a different location on the file system. It is an error to try to: + *
        + *
      • move a directory inside itself or to any child at any depth;
      • + *
      • move an entry into its parent if a name different from its current one isn't provided;
      • + *
      • move a file to a path occupied by a directory;
      • + *
      • move a directory to a path occupied by a file;
      • + *
      • move any element to a path occupied by a directory which is not empty.
      • + * + * A move of a file on top of an existing file must attempt to delete and replace that file. A move of a directory on top of an existing empty directory must attempt to delete and replace that directory. + * @param parent The directory to which to move the entry. + * @param newName The new name of the entry. Defaults to the EntrySync's current name if unspecified. + */ + moveTo(parent:DirectoryEntrySync, newName?:string):EntrySync; + + /** + * Copy an entry to a different location on the file system. It is an error to try to: + *
          + *
        • copy a directory inside itself or to any child at any depth;
        • + *
        • copy an entry into its parent if a name different from its current one isn't provided;
        • + *
        • copy a file to a path occupied by a directory;
        • + *
        • copy a directory to a path occupied by a file;
        • + *
        • copy any element to a path occupied by a directory which is not empty.
        • + * + * A copy of a file on top of an existing file must attempt to delete and replace that file. + * A copy of a directory on top of an existing empty directory must attempt to delete and replace that directory. + * Directory copies are always recursive--that is, they copy all contents of the directory. + */ + copyTo(parent:DirectoryEntrySync, newName?:string):EntrySync; + + /** + * Returns a URL that can be used to identify this entry. Unlike the URN defined in [FILE-API-ED], it has no specific expiration; as it describes a location on disk, it should be valid at least as long as that location exists. + */ + toURL():string; + + /** + * Deletes a file or directory. It is an error to attempt to delete a directory that is not empty. It is an error to attempt to delete the root directory of a filesystem. + */ + remove ():void; + + /** + * Look up the parent DirectoryEntrySync containing this Entry. If this EntrySync is the root of its filesystem, its parent is itself. + */ + getParent():DirectoryEntrySync; +} + +/** + * This interface represents a directory on a file system. + */ +interface DirectoryEntrySync extends EntrySync { + /** + * Creates a new DirectoryReaderSync to read EntrySyncs from this DirectorySync. + */ + createReader():DirectoryReaderSync; + + /** + * Creates or looks up a directory. + * @param path Either an absolute path or a relative path from this DirectoryEntrySync to the file to be looked up or created. It is an error to attempt to create a file whose immediate parent does not yet exist. + * @param options + *
            + *
          • If create and exclusive are both true and the path already exists, getFile must fail.
          • + *
          • If create is true, the path doesn't exist, and no other error occurs, getFile must create it as a zero-length file and return a corresponding FileEntry.
          • + *
          • If create is not true and the path doesn't exist, getFile must fail.
          • + *
          • If create is not true and the path exists, but is a directory, getFile must fail.
          • + *
          • Otherwise, if no other error occurs, getFile must return a FileEntrySync corresponding to path.
          • + *
          + */ + getFile(path:string, options?:Flags):FileEntrySync; + + /** + * Creates or looks up a directory. + * @param path Either an absolute path or a relative path from this DirectoryEntrySync to the directory to be looked up or created. It is an error to attempt to create a directory whose immediate parent does not yet exist. + * @param options + *
            + *
          • If create and exclusive are both true and the path already exists, getDirectory must fail.
          • + *
          • If create is true, the path doesn't exist, and no other error occurs, getDirectory must create and return a corresponding DirectoryEntry.
          • + *
          • If create is not true and the path doesn't exist, getDirectory must fail.
          • + *
          • If create is not true and the path exists, but is a file, getDirectory must fail.
          • + *
          • Otherwise, if no other error occurs, getDirectory must return a DirectoryEntrySync corresponding to path.
          • + *
          + */ + getDirectory(path:string, options?:Flags):DirectoryEntrySync; + + /** + * Deletes a directory and all of its contents, if any. In the event of an error [e.g. trying to delete a directory that contains a file that cannot be removed], some of the contents of the directory may be deleted. It is an error to attempt to delete the root directory of a filesystem. + */ + removeRecursively():void; +} + +/** + * This interface lets a user list files and directories in a directory. If there are no additions to or deletions from a directory between the first and last call to readEntries, and no errors occur, then: + *
            + *
          • A series of calls to readEntries must return each entry in the directory exactly once.
          • + *
          • Once all entries have been returned, the next call to readEntries must produce an empty array.
          • + *
          • If not all entries have been returned, the array produced by readEntries must not be empty.
          • + *
          • The entries produced by readEntries must not include the directory itself ["."] or its parent [".."].
          • + *
          + */ +interface DirectoryReaderSync { + /** + * Read the next block of entries from this directory. + */ + readEntries():EntrySync[]; +} + +/** + * This interface represents a file on a file system. + */ +interface FileEntrySync extends EntrySync { + /** + * Creates a new FileWriterSync associated with the file that this FileEntrySync represents. + */ + createWriter():FileWriterSync; + + /** + * Returns a File that represents the current state of the file that this FileEntrySync represents. + */ + file():File; +} + +interface Window extends LocalFileSystem, LocalFileSystemSync{ +} + +interface WorkerGlobalScope extends LocalFileSystem, LocalFileSystemSync{ +} diff --git a/filewriter/filewriter-tests.ts b/filewriter/filewriter-tests.ts new file mode 100644 index 0000000000..f70e76087d --- /dev/null +++ b/filewriter/filewriter-tests.ts @@ -0,0 +1,16 @@ +/// + +// http://www.w3.org/TR/file-writer-api/ +function writeFile(writer:FileWriter): void{ + function done(evt:Event): void{ + alert("Write completed."); + } + function error(evt:Event): void{ + alert("Write failed:" + evt); + } + + var b:Blob = new Blob(); + writer.onwrite = done; + writer.onerror = error; + writer.write(b); +} \ No newline at end of file diff --git a/filewriter/filewriter.d.ts b/filewriter/filewriter.d.ts new file mode 100644 index 0000000000..2257ee9eb8 --- /dev/null +++ b/filewriter/filewriter.d.ts @@ -0,0 +1,176 @@ +// Type Definitions for File API: Writer +// Project: http://www.w3.org/TR/file-writer-api/ +// Definitions by: Kon +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/** + * This interface provides methods to monitor the asynchronous writing of blobs to disk using progress events [PROGRESS-EVENTS] and event handler attributes. + * This interface is specified to be used within the context of the global object (Window [HTML5]) and within Web Workers (WorkerUtils [WEBWORKERS-ED]). + */ +interface FileSaver extends EventTarget { + /** + * When the abort method is called, user agents must run the steps below: + *
            + *
          1. If readyState == DONE or readyState == INIT, terminate this overall series of steps without doing anything else.
          2. + *
          3. Set readyState to DONE.
          4. + *
          5. If there are any tasks from the object's FileSaver task source in one of the task queues, then remove those tasks.
          6. + *
          7. Terminate the write algorithm being processed.
          8. + *
          9. Set the error attribute to a DOMError object of type "AbortError".
          10. + *
          11. Fire a progress event called abort
          12. + *
          13. Fire a progress event called writeend
          14. + *
          15. Terminate this algorithm.
          16. + *
          + */ + abort():void; + + /** + * The blob is being written. + * @readonly + */ + INIT:number; + + /** + * The object has been constructed, but there is no pending write. + * @readonly + */ + WRITING:number; + + /** + * The entire Blob has been written to the file, an error occurred during the write, or the write was aborted using abort(). The FileSaver is no longer writing the blob. + * @readonly + */ + DONE:number; + + /** + * The FileSaver object can be in one of 3 states. The readyState attribute, on getting, must return the current state, which must be one of the following values: + *
            + *
          • INIT
          • + *
          • WRITING
          • + *
          • DONE
          • + *
              + * @readonly + */ + readyState:number; + + /** + * The last error that occurred on the FileSaver. + * @readonly + */ + error:DOMError; + + /** + * Handler for writestart events + */ + onwritestart:Function; + + /** + * Handler for progress events. + */ + onprogress:Function; + + /** + * Handler for write events. + */ + onwrite:Function; + + /** + * Handler for abort events. + */ + onabort:Function; + + /** + * Handler for error events. + */ + onerror:Function; + + /** + * Handler for writeend events. + */ + onwriteend:Function; +} + +var FileSaver: { + /** + * When the FileSaver constructor is called, the user agent must return a new FileSaver object with readyState set to INIT. + * This constructor must be visible when the script's global object is either a Window object or an object implementing the WorkerUtils interface. + */ + new(data:Blob): FileSaver; +} + +/** + * This interface expands on the FileSaver interface to allow for multiple write actions, rather than just saving a single Blob. + */ +interface FileWriter extends FileSaver { + /** + * The byte offset at which the next write to the file will occur. This must be no greater than length. + * A newly-created FileWriter must have position set to 0. + */ + position:number; + + /** + * The length of the file. If the user does not have read access to the file, this must be the highest byte offset at which the user has written. + */ + length:number; + + /** + * Write the supplied data to the file at position. + * @param data The blob to write. + */ + write(data:Blob):void; + + /** + * Seek sets the file position at which the next write will occur. + * @param offset If nonnegative, an absolute byte offset into the file. If negative, an offset back from the end of the file. + */ + seek(offset:number):void; + + /** + * Changes the length of the file to that specified. If shortening the file, data beyond the new length must be discarded. If extending the file, the existing data must be zero-padded up to the new length. + * @param size The size to which the length of the file is to be adjusted, measured in bytes. + */ + truncate(size:number):void; +} + +/** + * This interface lets users write, truncate, and append to files using simple synchronous calls. + * This interface is specified to be used only within Web Workers (WorkerUtils [WEBWORKERS]). + */ +interface FileWriterSync { + /** + * The byte offset at which the next write to the file will occur. This must be no greater than length. + */ + position:number; + + /** + * The length of the file. If the user does not have read access to the file, this must be the highest byte offset at which the user has written. + */ + length:number; + + /** + * Write the supplied data to the file at position. Upon completion, position will increase by data.size. + * @param data The blob to write. + */ + write(data:Blob):void; + + /** + * Seek sets the file position at which the next write will occur. + * @param offset An absolute byte offset into the file. If offset is greater than length, length is used instead. If offset is less than zero, length is added to it, so that it is treated as an offset back from the end of the file. If it is still less than zero, zero is used. + */ + seek(offset:number):void; + + /** + * Changes the length of the file to that specified. If shortening the file, data beyond the new length must be discarded. If extending the file, the existing data must be zero-padded up to the new length. + * Upon successful completion: + *
                + *
              • length must be equal to size.
              • + *
              • position must be the lesser of + *
                  + *
                • its pre-truncate value,
                • + *
                • size.
                • + *
                + *
              • + *
              + * @param size The size to which the length of the file is to be adjusted, measured in bytes. + */ + truncate(size:number):void; +} diff --git a/flexSlider/flexSlider-tests.ts b/flexSlider/flexSlider-tests.ts new file mode 100644 index 0000000000..8651102422 --- /dev/null +++ b/flexSlider/flexSlider-tests.ts @@ -0,0 +1,84 @@ +/// + +// Can also be used with $(document).ready() +$(window).load(function() { + $('.flexslider').flexslider({ + animation: "slide" + }); +}); + +// Can also be used with $(document).ready() +$(window).load(function() { + $('.flexslider').flexslider({ + animation: "slide", + controlNav: "thumbnails" + }); +}); + +$(window).load(function() { + // The slider being synced must be initialized first + $('#carousel').flexslider({ + animation: "slide", + controlNav: false, + animationLoop: false, + slideshow: false, + itemWidth: 210, + itemMargin: 5, + asNavFor: '#slider' + }); + + $('#slider').flexslider({ + animation: "slide", + controlNav: false, + animationLoop: false, + slideshow: false, + sync: "#carousel" + }); +}); + +$(window).load(function() { + $('.flexslider').flexslider({ + animation: "slide", + animationLoop: false, + itemWidth: 210, + itemMargin: 5 + }); +}); + +// Can also be used with $(document).ready() +$(window).load(function() { + $('.flexslider').flexslider({ + animation: "slide", + animationLoop: false, + itemWidth: 210, + itemMargin: 5, + minItems: 2, + maxItems: 4 + }); +}); + +// Can also be used with $(document).ready() +$(window).load(function() { + + // Vimeo API nonsense + var player = document.getElementById('player_1'); + $(player).on('ready', ready); + + function addEvent(element, eventName, callback) { + if (element.addEventListener) { + element.addEventListener(eventName, callback, false) + } else { + element.attachEvent(eventName, callback, false); + } + } + + function ready(player_id) { + var froogaloop = $(player_id); + froogaloop.on('play', function(data) { + $('.flexslider').flexslider("pause"); + }); + froogaloop.on('pause', function(data) { + $('.flexslider').flexslider("play"); + }); + } +}); \ No newline at end of file diff --git a/flexSlider/flexSlider.d.ts b/flexSlider/flexSlider.d.ts new file mode 100644 index 0000000000..290cc1c459 --- /dev/null +++ b/flexSlider/flexSlider.d.ts @@ -0,0 +1,90 @@ +// Type definitions for FlexSlider 2 jquery plugin +// Project: https://github.com/woothemes/FlexSlider +// Definitions by: Diullei Gomes +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface SliderObject { //Object: The slider element itself + container: Object; //Object: The ul.slides within the slider + slides: Object; //Object: The slides of the slider + count: number; //Int: The total number of slides in the slider + currentSlide: number; //Int: The slide currently being shown + animatingTo: number; //Int: Useful in .before(), the slide currently animating to + animating: bool; //Boolean: is slider animating? + atEnd: bool; //Boolean: is the slider at either end? + manualPause: bool; //Boolean: force slider to stay paused during pauseOnHover event + controlNav: Object; //Object: The slider controlNav + directionNav: Object; //Object: The slider directionNav + controlsContainer: Object; //Object: The controlsContainer element of the slider + manualControls: Object; //Object: The manualControls element of the slider + flexAnimate(target, pause?); //Function: Move slider - (target, pause) parameters + pause(); //Function: Pause slider slideshow interval + resume(); //Function: Resume slider slideshow interval + canAdvance(target); //Function: returns boolean if slider can advance - (target) parameter + getTarget(dir); //Function: get target given a direction - "next" or "prev" parameter +} + +interface FlexSliderOptions { + namespace?: string; //{NEW} String: Prefix string attached to the class of every element generated by the plugin + selector?: string; //{NEW} Selector: Must match a simple pattern. '{container} > {slide}' -- Ignore pattern at your own peril + animation?: string; //String: Select your animation type, "fade" or "slide" + easing?: string; //{NEW} String: Determines the easing method used in jQuery transitions. jQuery easing plugin is supported! + direction?: string; //String: Select the sliding direction, "horizontal" or "vertical" + reverse?: bool; //{NEW} Boolean: Reverse the animation direction + animationLoop?: bool; //Boolean: Should the animation loop? If bool; directionNav will received "disable" classes at either end + smoothHeight?: bool; //{NEW} Boolean: Allow height of the slider to animate smoothly in horizontal mode + startAt?: number; //Integer: The slide that the slider should start on. Array notation (0 = first slide) + slideshow?: bool; //Boolean: Animate slider automatically + slideshowSpeed?: number; //Integer: Set the speed of the slideshow cycling, in milliseconds + animationSpeed?: number; //Integer: Set the speed of animations, in milliseconds + initDelay?: number; //{NEW} Integer: Set an initialization delay, in milliseconds + randomize?: bool; //Boolean: Randomize slide order + + // Usability features + pauseOnAction?: bool; //Boolean: Pause the slideshow when interacting with control elements, highly recommended. + pauseOnHover?: bool; //Boolean: Pause the slideshow when hovering over slider, then resume when no longer hovering + useCSS?: bool; //{NEW} Boolean: Slider will use CSS3 transitions if available + touch?: bool; //{NEW} Boolean: Allow touch swipe navigation of the slider on touch-enabled devices + video?: bool; //{NEW} Boolean: If using video in the slider, will prevent CSS3 3D Transforms to avoid graphical glitches + + // Primary Controls + controlNav?: any; //Boolean: Create navigation for paging control of each clide? Note: Leave true for manualControls usage + directionNav?: bool; //Boolean: Create navigation for previous/next navigation? (true/false) + prevText?: string; //String: Set the text for the "previous" directionNav item + nextText?: string; //String: Set the text for the "next" directionNav item + + // Secondary Navigation + keyboard?: bool; //Boolean: Allow slider navigating via keyboard left/right keys + multipleKeyboard?: bool; //{NEW} Boolean: Allow keyboard navigation to affect multiple sliders. Default behavior cuts out keyboard navigation with more than one slider present. + mousewheel?: bool; //{UPDATED} Boolean: Requires jquery.mousewheel.js (https://github.com/brandonaaron/jquery-mousewheel) - Allows slider navigating via mousewheel + pausePlay?: bool; //Boolean: Create pause/play dynamic element + pauseText?: string; //String: Set the text for the "pause" pausePlay item + playText?: string; //String: Set the text for the "play" pausePlay item + + // Special properties + controlsContainer?: string; //{UPDATED} Selector: USE CLASS SELECTOR. Declare which container the navigation elements should be appended too. Default container is the FlexSlider element. Example use would be ".flexslider-container". Property is ignored if given element is not found. + manualControls?: string; //Selector: Declare custom control navigation. Examples would be ".flex-control-nav li" or "#tabs-nav li img", etc. The number of elements in your controlNav should match the number of slides/tabs. + sync?: string; //{NEW} Selector: Mirror the actions performed on this slider with another slider. Use with care. + asNavFor?: string; //{NEW} Selector: Internal property exposed for turning the slider into a thumbnail navigation for another slider + + // Carousel Options + itemWidth?: number; //{NEW} Integer: Box-model width of individual carousel items, including horizontal borders and padding. + itemMargin?: number; //{NEW} Integer: Margin between carousel items. + minItems?: number; //{NEW} Integer: Minimum number of carousel items that should be visible. Items will resize fluidly when below this. + maxItems?: number; //{NEW} Integer: Maxmimum number of carousel items that should be visible. Items will resize fluidly when above this limit. + move?: number; //{NEW} Integer: Number of carousel items that should move on animation. If number; slider will move all visible items. + + // Callback API + start?: (slider: SliderObject) => any; //Callback: function(slider) - Fires when the slider loads the first slide + before?: (slider: SliderObject) => any; //Callback: function(slider) - Fires asynchronously with each slider animation + after?: () => any; //Callback: function(slider) - Fires after each slider animation completes + end?: () => any; //Callback: function(slider) - Fires when the slider reaches the last slide (asynchronous) + added?: () => any; //{NEW} Callback: function(slider) - Fires after a slide is added + removed?: () => any; +} + + +interface JQuery { + flexslider(options?: FlexSliderOptions); +} diff --git a/foundation/foundation.d.ts b/foundation/foundation.d.ts index e36d48952d..fba9752ddd 100644 --- a/foundation/foundation.d.ts +++ b/foundation/foundation.d.ts @@ -31,10 +31,33 @@ interface RevealOptions { animationSpeed?: number; closeOnBackgroundClick?: bool; dismissModalClass?: string; + /** + * The class of the modals background. + */ + bgClass?: string; open?: () => void; opened?: () => void; close?: () => void; closed?: () => void; + /** + * The modals background object. + */ + bg: JQuery; + /** + * The css property for when the modal is opened and closed. + */ + css: { + open: { + opacity?: number; + visibility?: string; + display: string; + }; + close: { + opacity: number; + visibility: string; + display: string; + }; + }; } interface JoyrideOptions { diff --git a/gamepad/gamepad-tests.ts b/gamepad/gamepad-tests.ts new file mode 100644 index 0000000000..7491d7970e --- /dev/null +++ b/gamepad/gamepad-tests.ts @@ -0,0 +1,72 @@ +/// + + +()=>{ + function runAnimation() + { + window.requestAnimationFrame(runAnimation); + + var gamepads = navigator.getGamepads(); + + for (var i = 0; i < gamepads.length; ++i) + { + var pad = gamepads[i]; + // todo; simple demo of displaying pad.axes and pad.buttons + } + } + + window.requestAnimationFrame(runAnimation); +}; + +()=>{ + window.addEventListener('GamepadConnected', (e: GamepadEvent)=>{ + console.log('Gamepad ' + e.gamepad.index + ' connected!'); + }, false); + window.addEventListener('GamepadDisconnected', (e: GamepadEvent)=>{ + console.log('Gamepad ' + e.gamepad.index + ' disconnected!'); + }, false); + window.addEventListener('webkitGamepadConnected', (e: GamepadEvent)=>{ + console.log('Gamepad ' + e.gamepad.index + ' connected!'); + }, false); + window.addEventListener('webkitGamepadDisconnected', (e: GamepadEvent)=>{ + console.log('Gamepad ' + e.gamepad.index + ' disconnected!'); + }, false); + window.addEventListener('mozGamepadConnected', (e: GamepadEvent)=>{ + console.log('Gamepad ' + e.gamepad.index + ' connected!'); + }, false); + window.addEventListener('mozGamepadDisconnected', (e: GamepadEvent)=>{ + console.log('Gamepad ' + e.gamepad.index + ' disconnected!'); + }, false); + + var requestAnimationFrame = window.requestAnimationFrame || window["mozRequestAnimationFrame"]; + var getGamepads = navigator.getGamepads || navigator.webkitGetGamepads; + if(getGamepads){ + function runAnimation() + { + requestAnimationFrame.call(window, runAnimation); + + var gamepads: GamepadList = getGamepads.call(navigator); + for(var i = 0; i < gamepads.length; i++){ + var pad: Gamepad = gamepads[i]; + if(pad){ + for (var k = 0; k < pad.buttons.length; k++) + { + var button = pad.buttons[k]; + if(button !== 0){ + console.log('pad[' + pad.index + ']: ' + 'time=' + pad.timestamp + ' id="' + pad.id + '" button[' + k + '] = ' + button); + } + } + for (var k = 0; k < pad.axes.length; k++) + { + var axis = pad.axes[k]; + if(Math.abs(axis) > 0.1){ + console.log('pad[' + pad.index + ']: ' + 'time=' + pad.timestamp + ' id="' + pad.id + '" axis[' + k + '] = ' + axis); + } + } + } + } + } + + runAnimation(); + } +}(); \ No newline at end of file diff --git a/gamepad/gamepad.d.ts b/gamepad/gamepad.d.ts new file mode 100644 index 0000000000..833b714344 --- /dev/null +++ b/gamepad/gamepad.d.ts @@ -0,0 +1,78 @@ +// Type definitions for Gamepad API +// Project: http://www.w3.org/TR/gamepad/ +// Definitions by: Kon +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/** + * This interface defines an individual gamepad device. + */ +interface Gamepad{ + /** + * An identification string for the gamepad. This string identifies the brand or style of connected gamepad device. Typically, this will include the USB vendor and a product ID. + * @readonly + */ + id:string; + + /** + * The index of the gamepad in the Navigator. When multiple gamepads are connected to a user agent, indices must be assigned on a first-come, first-serve basis, starting at zero. If a gamepad is disconnected, previously assigned indices must not be reassigned to gamepads that continue to be connected. However, if a gamepad is disconnected, and subsequently the same or a different gamepad is then connected, index entries must be reused. + * @readonly + */ + index:number; + + /** + * Last time the data for this gamepad was updated. Timestamp is a monotonically increasing value that allows the author to determine if the axes and button data have been updated from the hardware, relative to a previously saved timestamp. + * @readonly + */ + timestamp:number; + + /** + * Array of values for all axes of the gamepad. All axis values must be linearly normalized to the range [-1.0 .. 1.0]. As appropriate, -1.0 should correspond to "up" or "left", and 1.0 should correspond to "down" or "right". Axes that are drawn from a 2D input device should appear next to each other in the axes array, X then Y. It is recommended that axes appear in decreasing order of importance, such that element 0 and 1 typically represent the X and Y axis of a directional stick. + * @readonly + */ + axes:number[]; + + /** + * Array of values for all buttons of the gamepad. All button values must be linearly normalized to the range [0.0 .. 1.0]. 0.0 must mean fully unpressed, and 1.0 must mean fully pressed. It is recommended that buttons appear in decreasing importance such that the primary button, secondary button, tertiary button, and so on appear as elements 0, 1, 2, ... in the buttons array. + * @readonly + */ + buttons:number[]; +} + +/** + * + */ +interface GamepadEvent extends Event{ + /** + * The single gamepad attribute provides access to the associated gamepad data for this event. + * @readonly + */ + gamepad:Gamepad; +} + +interface GamepadList{ + [index: number]: Gamepad; + length: number; +} + +interface Navigator{ + /** + * The currently connected and interacted-with gamepads. Gamepads must only appear in the list if they are currently connected to the user agent, and have been interacted with by the user. Otherwise, they must not appear in the list to avoid a malicious page from fingerprinting the user based on connected devices. + * @readonly + */ + getGamepads(): Gamepad[]; + + webkitGetGamepads(): GamepadList; + + // Not supported yet :( + // mozGetGamepads(): Gamepad[]; +} + +/* + * @event gamepadconnected + * A user agent must dispatch this event type to indicate the user has connected a gamepad. If a gamepad was already connected when the page was loaded, the gamepadconnected event will be dispatched when the user presses a button or moves an axis. + */ + +/* + * @event gamepaddisconnected + * When a gamepad is disconnected from the user agent, if the user agent has previously dispatched a gamepadconnected event, a gamepaddisconnected event must be dispatched. + */ \ No newline at end of file diff --git a/gamequery/gamequery-tests.ts b/gamequery/gamequery-tests.ts new file mode 100644 index 0000000000..857a05a484 --- /dev/null +++ b/gamequery/gamequery-tests.ts @@ -0,0 +1,282 @@ +/// + +//Original examples: https://github.com/onaluf/gameQuery/tree/master/tests/human + +$(function () { + var simpleVerticalAnimation = new $.gameQuery.Animation({ imageURL: "sv.png", type: $.gameQuery.ANIMATION_VERTICAL, numberOfFrame: 4, delta: 32, rate: 300 }); + var simpleHorizontalAnimation = new $.gameQuery.Animation({ imageURL: "sh.png", type: $.gameQuery.ANIMATION_HORIZONTAL, numberOfFrame: 4, delta: 32, rate: 300 }); + + var multiVerticalAnimation = new $.gameQuery.Animation({ imageURL: "mv.png", type: $.gameQuery.ANIMATION_VERTICAL | $.gameQuery.ANIMATION_MULTI, numberOfFrame: 4, delta: 32, rate: 300, distance: 32 }); + var multiHorizontalAnimation = new $.gameQuery.Animation({ imageURL: "mh.png", type: $.gameQuery.ANIMATION_HORIZONTAL | $.gameQuery.ANIMATION_MULTI, numberOfFrame: 4, delta: 32, rate: 300, distance: 32 }); + + var simpleOffsetVerticalAnimation = new $.gameQuery.Animation({ imageURL: "sov.png", type: $.gameQuery.ANIMATION_VERTICAL, offsetx: 100, offsety: 100, numberOfFrame: 4, delta: 32, rate: 300 }); + var simpleOffsetHorizontalAnimation = new $.gameQuery.Animation({ imageURL: "soh.png", type: $.gameQuery.ANIMATION_HORIZONTAL, offsetx: 100, offsety: 100, numberOfFrame: 4, delta: 32, rate: 300 }); + + var multiOffsetVerticalAnimation = new $.gameQuery.Animation({ imageURL: "mov.png", type: $.gameQuery.ANIMATION_VERTICAL | $.gameQuery.ANIMATION_MULTI, offsetx: 100, offsety: 100, numberOfFrame: 4, delta: 32, rate: 300, distance: 32 }); + var multiOffsetHorizontalAnimation = new $.gameQuery.Animation({ imageURL: "moh.png", type: $.gameQuery.ANIMATION_HORIZONTAL | $.gameQuery.ANIMATION_MULTI, offsetx: 100, offsety: 100, numberOfFrame: 4, delta: 32, rate: 300, distance: 32 }); + + var pingpongAnimation = new $.gameQuery.Animation({ imageURL: "rebound.png", type: $.gameQuery.ANIMATION_HORIZONTAL | $.gameQuery.ANIMATION_PINGPONG, numberOfFrame: 9, delta: 64, rate: 60 }); + var multiPingpongAnimation = new $.gameQuery.Animation({ imageURL: "reboundm.png", type: $.gameQuery.ANIMATION_HORIZONTAL | $.gameQuery.ANIMATION_PINGPONG | $.gameQuery.ANIMATION_MULTI, numberOfFrame: 9, delta: 64, rate: 60, distance: 64 }); + + var callbackAnim = new $.gameQuery.Animation({ imageURL: "sv.png", type: $.gameQuery.ANIMATION_VERTICAL | $.gameQuery.ANIMATION_ONCE | $.gameQuery.ANIMATION_CALLBACK, numberOfFrame: 4, delta: 32, rate: 300 }); + var counter = 0; + $("#playground").playground({ height: 64, width: 500 }); + + $.playground() + .addSprite("simpleVertical", { animation: simpleVerticalAnimation, posx: 0 }) + .addSprite("simpleHorizontal", { animation: simpleHorizontalAnimation, posx: 34 }) + .addSprite("multiVertical", { animation: multiVerticalAnimation, posx: 75 }) + .addSprite("multiHorizontal", { animation: multiHorizontalAnimation, posx: 109 }) + .addSprite("simpleOffsetVertical", { animation: simpleOffsetVerticalAnimation, posx: 150 }) + .addSprite("simpleOffsetHorizontal", { animation: simpleOffsetHorizontalAnimation, posx: 184 }) + .addSprite("multiOffsetVertical", { animation: multiOffsetVerticalAnimation, posx: 225 }) + .addSprite("multiOffsetHorizontal", { animation: multiOffsetHorizontalAnimation, posx: 259 }) + .addSprite("pingpong", { animation: pingpongAnimation, posx: 286, width: 64, height: 64 }) + .addSprite("multiPingpong", { animation: multiPingpongAnimation, posx: 350, width: 64, height: 64 }) + .addSprite("callback", { + animation: callbackAnim, posx: 414, callback: function () { + counter++; + if (counter > 1) { + $("#callback").remove(); + } + } + }); + + $("#multiVertical").setAnimation(1); + $("#multiHorizontal").setAnimation(1); + $("#multiOffsetVertical").setAnimation(1); + $("#multiOffsetHorizontal").setAnimation(1); + $("#multiPingpong").setAnimation(1); + + $.playground().startGame(); +}); +$(function () { + + var red = new $.gameQuery.Animation({ + imageURL: "red.png", + type: $.gameQuery.ANIMATION_HORIZONTAL + }); + var blue = new $.gameQuery.Animation({ + imageURL: "blue.png", + type: $.gameQuery.ANIMATION_HORIZONTAL + }); + + $("#playground").playground({ height: 450, width: 350 }); + + // no group, no translation, no transformation + $.playground() + .addSprite("a1", { animation: red, width: 30, height: 30, posx: 0, posy: 0 }) + .addSprite("b1", { animation: red, width: 30, height: 30, posx: 15, posy: 15 }); + + // one group, no translation, no transformation + $.playground() + .addSprite("a2", { animation: red, width: 30, height: 30, posx: 0, posy: 50 }) + .addGroup("g1", { width: 100, height: 100, posx: -55, posy: -5 }) + .addSprite("b2", { animation: red, width: 30, height: 30, posx: 70, posy: 70 }); + + // no group, absolute translation, no rotation + $.playground() + .addSprite("a3", { animation: red, width: 30, height: 30, posx: 0, posy: 100 }) + .addSprite("b3", { animation: red, width: 30, height: 30, posx: 100, posy: 131 }); + $("#b3").x(15).y(115); + + // no group, relative translation, scale + $.playground() + .addSprite("a4", { animation: red, width: 30, height: 30, posx: 0, posy: 150 }) + .addSprite("b4", { animation: red, width: 30, height: 30, posx: 100, posy: 181 }); + $("#b4").x(-85, true).y(-16, true); + + // no group, no translation, flip + $.playground() + .addSprite("a5", { animation: red, width: 30, height: 30, posx: 0, posy: 200 }) + .addSprite("b5", { animation: red, width: 30, height: 30, posx: 15, posy: 215 }); + $("#a5").flipv(); + $("#b5").fliph(); + + // no group, no translation, rotation + $.playground() + .addSprite("a6", { animation: red, width: 30, height: 30, posx: 0, posy: 250 }) + .addSprite("b6", { animation: red, width: 30, height: 30, posx: 30, posy: 265 }); + $("#b6").rotate(45); + + // no group, no translation, scale + $.playground() + .addSprite("a7", { animation: red, width: 30, height: 30, posx: 0, posy: 300 }) + .addSprite("b7", { animation: red, width: 30, height: 30, posx: 30, posy: 315 }); + $("#b7").scale(1.5); + + // no group, no translation, override + $.playground() + .addSprite("a8", { animation: red, width: 30, height: 30, posx: 0, posy: 370 }) + .addSprite("b8", { animation: red, width: 30, height: 30, posx: 40, posy: 385 }); + + + + // now we try to turn every b* sprites blue + $("#a1").collision().each(function () { + $(this).setAnimation(blue); + }); + + $("#a2").collision().each(function () { + $(this).setAnimation(blue); + }); + + $("#a3").collision().each(function () { + $(this).setAnimation(blue); + }); + + $("#a4").collision().each(function () { + $(this).setAnimation(blue); + }); + + $("#a5").collision().each(function () { + $(this).setAnimation(blue); + }); + + $("#a6").collision().each(function () { + $(this).setAnimation(blue); + }); + + $("#a7").collision().each(function () { + $(this).setAnimation(blue); + }); + + $("#a8").collision({ x: 35 }).each(function () { + $(this).setAnimation(blue); + }); + + $.playground().startGame(); +}); + +$(function () { + var multiAnimation = new $.gameQuery.Animation({ + imageURL: "m.png", + type: $.gameQuery.ANIMATION_HORIZONTAL | $.gameQuery.ANIMATION_MULTI, + numberOfFrame: 3, + delta: 10, + distance: 10, + rate: 300 + }); + + var multiAnimationPingpong = new $.gameQuery.Animation({ + imageURL: "m.png", + type: $.gameQuery.ANIMATION_HORIZONTAL | $.gameQuery.ANIMATION_MULTI | $.gameQuery.ANIMATION_PINGPONG, + numberOfFrame: 3, + delta: 10, + distance: 10, + rate: 300 + }); + var animations = []; + animations[0] = new $.gameQuery.Animation({ + imageURL: "s1.png", + type: $.gameQuery.ANIMATION_HORIZONTAL, + numberOfFrame: 3, + delta: 10, + rate: 300 + }); + animations[1] = new $.gameQuery.Animation({ + imageURL: "s2.png", + type: $.gameQuery.ANIMATION_HORIZONTAL, + numberOfFrame: 3, + delta: 10, + rate: 300 + }); + animations[2] = new $.gameQuery.Animation({ + imageURL: "s3.png", + type: $.gameQuery.ANIMATION_HORIZONTAL, + numberOfFrame: 3, + delta: 10, + rate: 300 + }); + + var animationsPingpong = []; + animationsPingpong[0] = new $.gameQuery.Animation({ + imageURL: "s1.png", + type: $.gameQuery.ANIMATION_HORIZONTAL | $.gameQuery.ANIMATION_PINGPONG, + numberOfFrame: 3, + delta: 10, + rate: 300 + }); + animationsPingpong[1] = new $.gameQuery.Animation({ + imageURL: "s2.png", + type: $.gameQuery.ANIMATION_HORIZONTAL | $.gameQuery.ANIMATION_PINGPONG, + numberOfFrame: 3, + delta: 10, + rate: 300 + }); + animationsPingpong[2] = new $.gameQuery.Animation({ + imageURL: "s3.png", + type: $.gameQuery.ANIMATION_HORIZONTAL | $.gameQuery.ANIMATION_PINGPONG, + numberOfFrame: 3, + delta: 10, + rate: 300 + }); + + var tileDef = [[1, 2, 3], [2, 3, 1], [3, 1, 2]]; + var tileFun = function (i, j) { return 1 + (i + j) % 3; }; + $("#playground").playground({ height: 64, width: 350 }); + + $.playground() + .addTilemap("multiArray", tileDef, multiAnimation, { width: 10, height: 10, sizex: 3, sizey: 3, posx: 0 }).end() + .addTilemap("multiFunction", tileFun, multiAnimation, { width: 10, height: 10, sizex: 3, sizey: 3, posx: 40 }).end() + .addTilemap("arrayArray", tileDef, animations, { width: 10, height: 10, sizex: 3, sizey: 3, posx: 80 }).end() + .addTilemap("arrayFunction", tileFun, animations, { width: 10, height: 10, sizex: 3, sizey: 3, posx: 120 }).end() + .addTilemap("multiArrayPingpong", tileDef, multiAnimationPingpong, { width: 10, height: 10, sizex: 3, sizey: 3, posx: 160 }).end() + .addTilemap("arrayArrayPingpong", tileDef, animationsPingpong, { width: 10, height: 10, sizex: 3, sizey: 3, posx: 200 }).end() + .addGroup("testGroup", { height: 30, width: 30, posx: -40 }).addTilemap("outside", tileDef, multiAnimation, { width: 10, height: 10, sizex: 3, sizey: 3, posx: 0 }); + $("#testGroup").x(240); + $.playground().startGame(); +}); + +$(function () { + var multiAnimation = new $.gameQuery.Animation({ + imageURL: "m.png", + type: $.gameQuery.ANIMATION_HORIZONTAL | $.gameQuery.ANIMATION_MULTI, + numberOfFrame: 3, + delta: 10, + distance: 10, + rate: 300 + }); + + var tileDef = [[1, 2, 3, 1, 2, 3, 1, 2, 3], + [2, 3, 1, 2, 3, 1, 2, 3, 1], + [3, 1, 2, 3, 1, 2, 3, 1, 2]]; + + $("#playground").playground({ height: 60, width: 90 }); + + $.playground() + .addGroup("testGroup1", { height: 60, width: 180, posx: 0 }) + .addTilemap("map1", tileDef, multiAnimation, { width: 10, height: 10, sizex: 9, sizey: 3, posx: 0 }).end() + .addTilemap("map2", tileDef, multiAnimation, { width: 10, height: 10, sizex: 9, sizey: 3, posx: 90 }).end() + .end() + .addGroup("testGroup2", { height: 60, width: 90, posy: 60 }) + .addTilemap("map3", tileDef, multiAnimation, { width: 10, height: 10, sizex: 9, sizey: 3, posx: 0 }); + + + $("#testGroup1").x(-45); + $("#testGroup2").y(30); + $.playground().startGame(); +}); + +$(function () { + var animation = new $.gameQuery.Animation({ imageURL: "sh.png", type: $.gameQuery.ANIMATION_HORIZONTAL, numberOfFrame: 4, delta: 32, rate: 300 }); + + $("#playground").playground({ height: 64, width: 480 }); + + $.playground() + .addSprite("rotate", { animation: animation, posx: 0, posy: 16 }) + .addSprite("scale", { animation: animation, posx: 80, posy: 16 }) + .addSprite("rotateScale", { animation: animation, posx: 160, posy: 16 }) + .addSprite("scaleRotate", { animation: animation, posx: 240, posy: 16 }) + .addSprite("flipH", { animation: animation, posx: 320, posy: 16 }) + .addSprite("flipV", { animation: animation, posx: 400, posy: 16 }) + + $("#rotate").rotate(45); + $("#scale").scale(4); + $("#scale").scale(0.5, true); + $("#rotateScale").rotate(45).scale(2); + $("#scaleRotate").scale(2).rotate(45); + $("#flipV").flipv(true); + $("#flipH").fliph(true); + $.playground().startGame(); +}); \ No newline at end of file diff --git a/gamequery/gamequery.d.ts b/gamequery/gamequery.d.ts new file mode 100644 index 0000000000..dbb68fca4a --- /dev/null +++ b/gamequery/gamequery.d.ts @@ -0,0 +1,171 @@ +// Type definitions for gameQuery 0.7.0 +// Project: http://gamequeryjs.com/ +// Definitions by: David Laubreiter +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface PlaygroundOptions{ + height?: number; + width?: number; + refreshRate?: number; + keyTracker?: bool; + mouseTracker?: bool; + position?: string; + disableCollision?: bool; +} + +interface Coordinate3D{ + x: number; + y: number; + z: number; +} + +interface Size{ + w: number; + h: number; +} + +interface SpriteOptions{ + animation?: any; + height?: number; + width?: number; + posx?: number; + posy?: number; + callback?: () => any; +} + +interface GroupOptions{ + overflow?: string; + height?: number; + width?: number; + posx?: number; + posy?: number; +} + +interface TileMapOptions{ + sizex?: number; + sizey?: number; + height?: number; + width?: number; + posx?: number; + posy?: number; + buffer?: number; +} + +interface AnimationOptions{ + imageURL: string; + numberOfFrame?: number; + delta?: number; + rate?: number; + type?: number; + distance?: number; + offsetx?: number; + offsety?: number; +} + +interface Animation{ + imageURL: string; + numberOfFrame: number; + delta: number; + rate: number; + type: number; + distance: number; + offsetx: number; + offsety: number; + + new (options: AnimationOptions): Animation; +} + +interface GameQuery { + ANIMATION_VERTICAL: number; + ANIMATION_HORIZONTAL: number; + ANIMATION_ONCE: number; + ANIMATION_CALLBACK: number; + ANIMATION_MULTI: number; + ANIMATION_PINGPONG: number; + + Animation: Animation; + + keyTracker: bool[]; + + spriteCssClass: string; + groupCssClass: string; + tilemapCssClass: string; + tileCssClass: string; + tileTypePrefix: string; + tileIdPrefix: string; +} + +interface JQuery{ + playground(options?: PlaygroundOptions): JQuery; + + collision(query?: any): JQuery; + + startGame(callback?: () => void): JQuery; + pauseGame(): JQuery; + resumeGame(callback?: () => void ): JQuery; + + registerCallback(callback: () => void , rate: number): JQuery; + registerCallback(callback: () => number , rate: number): JQuery; + registerCallback(callback: () => bool , rate: number): JQuery; + + clearScenegraph(): JQuery; + clearAll(clearCallbacks?: bool): JQuery; + + loadCallback(callback: (percent: number) => void ): JQuery; + + rotate(angle: number, relative?: bool): JQuery; + scale(ratio: number, relative?: bool): JQuery; + flipv(flip?: bool): JQuery; + fliph(flip?: bool): JQuery; + + xyz(x: number, y: number, z: number, relative?: bool): JQuery; + xyz(): Coordinate3D; + + xy(x: number, y: number, relative?: bool): JQuery; + xy(): Coordinate3D; + + x(value: number, relative?: bool): JQuery; + x(): number; + + y(value: number, relative?: bool): JQuery; + y(): number; + + z(value: number, relative?: bool): JQuery; + z(): number; + + wh(width: number, height: number, relative?: bool): JQuery; + wh(): Size; + + w(value: number, relative?: bool): JQuery; + w(): number; + + h(value: number, relative?: bool): JQuery; + h(): number; + + addSprite(name: string, options: SpriteOptions): JQuery; + addGroup(name: string, options: GroupOptions): JQuery; + + addTilemap(name: string, tileDescription: number[][], animationList : Animation[], options: TileMapOptions) : JQuery; + addTilemap(name: string, tileDescription: number[][], animation : Animation, options: TileMapOptions) : JQuery; + addTilemap(name: string, tileDescription: (i: number, j: number) => number, animationList : Animation[], options: TileMapOptions) : JQuery; + addTilemap(name: string, tileDescription: (i: number, j: number) => number, animation : Animation, options: TileMapOptions) : JQuery; + + + gQ: GameQuery; + + setAnimation(animation: Animation, callback?: () => any): JQuery; + setAnimation(animation: number, callback?: () => any): JQuery; + setAnimation(): JQuery; + + pauseAnimation(): JQuery; + resumeAnimation(): JQuery; +} + +interface JQueryStatic{ + playground(): JQuery; + + gQ: GameQuery; + gameQuery: GameQuery; +} diff --git a/globalize/globalize.d.ts b/globalize/globalize.d.ts index 902236ced0..8b4a1ce97a 100644 --- a/globalize/globalize.d.ts +++ b/globalize/globalize.d.ts @@ -110,11 +110,11 @@ class GlobalizeStatic { addCultureInfo(cultureName, baseCultureName, info? ); findClosestCulture(cultureSelector: string); format(value, format, cultureSelector? ); - localize(key, cultureSelector); + localize(key, cultureSelector?); parseDate(value: string, formats? , cultureSelector?: string): Date; parseInt(value: string, radix? , cultureSelector?: string): number; parseFloat(value: string, radix? , cultureSelector?: string): number; } -declare var Globalize: GlobalizeStatic; \ No newline at end of file +declare var Globalize: GlobalizeStatic; diff --git a/google.analytics/ga-tests.ts b/google.analytics/ga-tests.ts new file mode 100644 index 0000000000..03d5c2ed50 --- /dev/null +++ b/google.analytics/ga-tests.ts @@ -0,0 +1,76 @@ +/// +/// + +describe("tester Google Analytics Tracker _gat object", () => { + + it("can set ga script element", () => { + ga = document.createElement("script"); + }); + + it("can set aync to true", () => { + ga.async = true; + }); + + it("can set src to string url", () => { + ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';; + }); + + it("can set type", () => { + ga.type = 'text/javascript'; + }); + + +}); + +describe("tester Google Analytics Tracker _gat object", () => { + it("can create _createTracker", () => { + _gat._createTracker('UA-65432-1'); + _gat._createTracker('UA-65432-2', 't2'); + }); + + it("can create _getTrackerByName", () => { + _gat._getTrackerByName(); + _gat._getTrackerByName('t2'); + }); + + it("can create _anonymizeIp", () => { + _gat._anonymizeIp(); + }); + +}); + +describe("tester Google Analytics Code _gaq object", () => { + it("can create _push", () => { + _gaq.push(['_setAccount', 'UA-XXXXXXX-YY']); + _gaq.push(['_gat._anonymizeIp']); + _gaq.push(['_trackPageview']); + + _gaq.push(() => { + var tracker = _gat._getTrackerByName('UA-65432-1'); + tracker._trackPageview(); + } + ); + }); +}); + + +describe("tester Google Analytics Code Tracker object", () => { + it("can create Tracker object and call methods", () => { + var tracker = _gat._getTrackerByName('UA-65432-1'); + tracker._trackPageview(); + tracker._getName(); + tracker._getAccount(); + tracker._getVersion(); + tracker._getVisitorCustomVar(0); + tracker._setAccount(); + tracker._setCustomVar(0, "name", "value", 1); + tracker._setSampleRate("80"); + tracker._setSessionCookieTimeout(1800000); + tracker._setSiteSpeedSampleRate(5); + tracker._setVisitorCookieTimeout(63072000000); + tracker._trackPageLoadTime(); + }); +}); + + + diff --git a/google.analytics/ga.d.ts b/google.analytics/ga.d.ts new file mode 100644 index 0000000000..b24bc6649e --- /dev/null +++ b/google.analytics/ga.d.ts @@ -0,0 +1,41 @@ +// Type definitions for Google Analytics +// Project: https://developers.google.com/analytics/devguides/collection/gajs/ +// Definitions by: Ronnie Haakon Hegelund +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +class Tracker { + _trackPageview(): void; + _getName(): string; + _getAccount(): string; + _getVersion(): string; + _getVisitorCustomVar(index: number); string; + _setAccount(): string; + _setCustomVar(index: number, name: string, value: string, opt_scope?: number): bool; + _setSampleRate(newRate: string): void; + _setSessionCookieTimeout(cookieTimeoutMillis: number): void; + _setSiteSpeedSampleRate(sampleRate: number): void; + _setVisitorCookieTimeout(milliseconds: number): void; + _trackPageLoadTime(): void; +} + +interface GoogleAnalyticsCode { + push(commandArray: string[]): void; + push(Function): void; +} + +interface GoogleAnalyticsTracker { + _getTracker(account: string): Tracker; + _createTracker(opt_account: string, opt_name?: string): Tracker; + _getTrackerByName(opt_name?: string): Tracker; + _anonymizeIp(): void; +} + +interface GoogleAnalytics { + type: string; + src: string; + async: bool; +} + +declare var ga: GoogleAnalytics; +declare var _gaq: GoogleAnalyticsCode; +declare var _gat: GoogleAnalyticsTracker; diff --git a/google.feeds/google.feed.api.d.ts b/google.feeds/google.feed.api.d.ts new file mode 100644 index 0000000000..386329f40a --- /dev/null +++ b/google.feeds/google.feed.api.d.ts @@ -0,0 +1,79 @@ +//Project Google Feed Apis +// Project: https://developers.google.com/feed/ +// Definitions by: https://github.com/RodneyJT + +declare module google.feeds { + export class feed { + constructor(); + constructor(url: string); + findFeeds(query?: string, callback?: (result: findResult) => void ): void; + getElementsByTagNameNS(node: string, ns: string, localName: string): any[]; + includeHistoricalEntries(): void; + load(callback?: (result: feedResult) => void ): void; + setNumEntries(num: number): void; + setResultFormat(format: string): void; + } +} + +interface feedResult { + error?: feedError; + xmlDocument?: string; + feed: feedJSON; +} + +interface findResult { + error?: feedError; + xmlDocument?: string; + findEntries: findEntry[]; +} + +interface feedError { + code: string; + message: string; +} + +interface feedJSON { + feedURL: string; + link: string; + author: string; + description: string; + entries: feedEntry[]; +} + +interface feedEntry { + mediaGroup: MediaGroup[]; + title: string; + link: string; + content: string; + contentSnippet: string; + publishedDate: string; + categories: string[]; +} + +interface findEntry { + title: string; + link: string; + contentSnippet: string; + url: string; +} + +interface MediaGroup { + content: MediaContent[]; +} + +interface MediaContent { + url: string; + fileSize: number; + type: string; + medium: string; + isDefault: bool; + expression: string; + bitrate: number; + framerate: number; + samplingrate: number; + channels: string; + duration: number; + height: number; + width: number; + lang: string; +} diff --git a/google.geolocation/google.geolocation-tests.ts b/google.geolocation/google.geolocation-tests.ts new file mode 100644 index 0000000000..f6574cfea4 --- /dev/null +++ b/google.geolocation/google.geolocation-tests.ts @@ -0,0 +1,18 @@ +// Test files for Geolocation Definition file +/// + +//determine if the handset has client side geo location capabilities +var isInit: bool = geo_position_js.init(); +if(isInit){ + geo_position_js.getCurrentPosition(success_callback, error_callback); +} else { + alert("Functionality not available"); +} + +function success_callback(position: Position): void { + geo_position_js.showMap(position.coords.latitude, position.coords.longitude); +} + +function error_callback(positionError: PositionError): void { + console.log(positionError.code); +} \ No newline at end of file diff --git a/google.geolocation/google.geolocation.d.ts b/google.geolocation/google.geolocation.d.ts new file mode 100644 index 0000000000..5260ba01e4 --- /dev/null +++ b/google.geolocation/google.geolocation.d.ts @@ -0,0 +1,12 @@ +// Type definitions for Google Geolocation 0.4.8 +// Project: https://code.google.com/p/geo-location-javascript/ +// Definitions by: Vincent Bortone +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface GeolocationStatic { + init(): bool; + getCurrentPosition(success: (position: Position) => void, error?: (positionError: PositionError) => void, opts?: PositionOptions): void; + showMap(latitude: number, longitude: number): void; +} + +declare var geo_position_js: GeolocationStatic; \ No newline at end of file diff --git a/googlemaps/google.maps.d.ts b/googlemaps/google.maps.d.ts index 340387c444..3596da3d49 100644 --- a/googlemaps/google.maps.d.ts +++ b/googlemaps/google.maps.d.ts @@ -1123,7 +1123,7 @@ declare module google.maps { worldSize?: Size; } - export interface StreetViewService { + export class StreetViewService { getPanoramaById(pano: string, callback: (streetViewPanoramaData: StreetViewPanoramaData, streetViewStatus: StreetViewStatus) => void ); getPanoramaByLocation(latlng: LatLng, radius: number, callback: (streetViewPanoramaData: StreetViewPanoramaData, streetViewStatus: StreetViewStatus) => void ); } diff --git a/highcharts/highcharts.d.ts b/highcharts/highcharts.d.ts index e135847103..ac10279d08 100644 --- a/highcharts/highcharts.d.ts +++ b/highcharts/highcharts.d.ts @@ -960,8 +960,8 @@ interface HighchartsOptions { subtitle?: HighchartsSubtitleOptions; title?: HighchartsTitleOptions; tooltip?: HighchartsTooltipOptions; - xAxis?: HighchartsAxisOptions[]; - yAxis?: HighchartsAxisOptions[]; + xAxis?: HighchartsAxisOptions; + yAxis?: HighchartsAxisOptions; } diff --git a/jake/jake-tests.ts b/jake/jake-tests.ts new file mode 100644 index 0000000000..410764d288 --- /dev/null +++ b/jake/jake-tests.ts @@ -0,0 +1,267 @@ +// https://github.com/mde/jake +/// + +import path = module("path"); + +desc('This is the default task.'); +task('default', function (params) { + console.log('This is the default task.'); +}); + +desc('This task has prerequisites.'); +task('hasPrereqs', ['foo', 'bar', 'baz'], function (params) { + console.log('Ran some prereqs first.'); +}); + +desc('This is an asynchronous task.'); +task('asyncTask', {async: true}, function () { + setTimeout(complete, 1000); +}); + +desc('This builds a minified JS file for production.'); +file('foo-minified.js', ['bar', 'foo-bar.js', 'foo-baz.js'], function () { + // Code to concat and minify goes here +}); + +desc('This creates the bar directory for use with the foo-minified.js file-task.'); +directory('bar'); + +desc('This is the default task.'); +task('default', function () { + console.log('This is the default task.'); +}); + +namespace('foo', function () { + desc('This the foo:bar task'); + task('bar', function () { + console.log('doing foo:bar task'); + }); + + desc('This the foo:baz task'); + task('baz', ['default', 'foo:bar'], function () { + console.log('doing foo:baz task'); + }); + +}); + +desc('This is an awesome task.'); +task('awesome', function (a, b, c) { + console.log(a, b, c); +}); + + +desc('This is an awesome task.'); +task('awesome', function (a, b, c) { + console.log(a, b, c); + console.log(process.env.qux, process.env.frang); +}); + + +jake.addListener('complete', function () { + process.exit(); +}); + +desc('Calls the foo:bar task and its prerequisites.'); +task('invokeFooBar', function () { + // Calls foo:bar and its prereqs + jake.Task['foo:bar'].invoke(); +}); + +desc('Calls the foo:bar task and its prerequisites.'); +task('invokeFooBar', function () { + // Calls foo:bar and its prereqs + jake.Task['foo:bar'].invoke(); + // Does nothing + jake.Task['foo:bar'].invoke(); +}); + +desc('Calls the foo:bar task without its prerequisites.'); +task('executeFooBar', function () { + // Calls foo:bar without its prereqs + jake.Task['foo:baz'].execute(); +}); + +desc('Calls the foo:bar task without its prerequisites.'); +task('executeFooBar', function () { + // Calls foo:bar without its prereqs + jake.Task['foo:baz'].execute(); + // Can keep running this over and over + jake.Task['foo:baz'].execute(); + jake.Task['foo:baz'].execute(); +}); + +desc('Calls the foo:bar task and its prerequisites.'); +task('invokeFooBar', function () { + // Calls foo:bar and its prereqs + jake.Task['foo:bar'].invoke(); + // Does nothing + jake.Task['foo:bar'].invoke(); + // Only re-runs foo:bar, but not its prerequisites + jake.Task['foo:bar'].reenable(); + jake.Task['foo:bar'].invoke(); +}); + +desc('Calls the foo:bar task and its prerequisites.'); +task('invokeFooBar', function () { + // Calls foo:bar and its prereqs + jake.Task['foo:bar'].invoke(); + // Does nothing + jake.Task['foo:bar'].invoke(); + // Re-runs foo:bar and all of its prerequisites + jake.Task['foo:bar'].reenable(true); + jake.Task['foo:bar'].invoke(); +}); + +desc('Passes params on to other tasks.'); +task('passParams', function () { + var t = jake.Task['foo:bar']; + // Calls foo:bar, passing along current args + t.invoke.apply(t, arguments); +}); + +desc('Calls the async foo:baz task and its prerequisites.'); +task('invokeFooBaz', {async: true}, function () { + var t = jake.Task['foo:baz']; + t.addListener('complete', function () { + console.log('Finished executing foo:baz'); + // Maybe run some other code + // ... + // Complete the containing task + complete(); + }); + // Kick off foo:baz + t.invoke(); +}); + + +namespace('vronk', function () { + task('groo', function () { + var t = jake.Task['vronk:zong']; + t.addListener('error', function (e) { + console.log(e.message); + }); + t.invoke(); + }); + + task('zong', function () { + throw new Error('OMFGZONG'); + }); +}); + +desc('This task fails.'); +task('failTask', function () { + fail('Yikes. Something back happened.'); +}); + + +desc('This task fails with an exit-status of 42.'); +task('failTaskQuestionCustomStatus', function () { + fail('What is the answer?', 42); +}); + + +declare var sourceDir:string; +declare var currentDir:string; +jake.mkdirP('app/views/layouts'); +jake.cpR(path.join(sourceDir, '/templates'), currentDir); +jake.readdirR('pkg'); +jake.rmRf('pkg'); + +desc('Runs the Jake tests.'); +task('test', {async: true}, function () { + var cmds = [ + 'node ./tests/parseargs.js' + , 'node ./tests/task_base.js' + , 'node ./tests/file_task.js' + ]; + jake.exec(cmds, function () { + console.log('All tests passed.'); + complete(); + }, {printStdout: true}); +}); + +var ex = jake.createExec(['do_thing.sh'], {printStdout: true}); +ex.addListener('error', function (msg, code) { + if (code == 127) { + console.log("Couldn't find do_thing script, trying do_other_thing"); + ex.append('do_other_thing.sh'); + } + else { + fail('Fatal error: ' + msg, code); + } +}); +ex.run(); + +task('echo', {async: true}, function () { + jake.exec(['echo "hello"'], function () { + jake.logger.log('Done.'); + complete(); + }, {printStdout: !jake.program.opts.quiet}); +}); + +function hoge(){ + var t = new jake.PackageTask('fonebone', 'v0.1.2112', function () { + var fileList = [ + 'Jakefile' + , 'README.md' + , 'package.json' + , 'lib/*' + , 'bin/*' + , 'tests/*' + ]; + this.packageFiles.include(fileList); + this.needTarGz = true; + this.needTarBz2 = true; + }); +} + +var list = new jake.FileList(); +list.include('foo/*.txt'); +list.include(['bar/*.txt', 'README.md']); +list.include('Makefile', 'package.json'); +list.exclude('foo/zoobie.txt'); +list.exclude(/foo\/src.*.txt/); +console.log(list.toArray()); + + +var t = new jake.TestTask('fonebone', function () { + var fileList = [ + 'tests/*' + , 'lib/adapters/**/test.js' + ]; + this.testFiles.include(fileList); + this.testFiles.exclude('tests/helper.js'); + this.testName = 'testMainAndAdapters'; +}); + +var assert = require('assert') + , tests; + +tests = { + 'sync test': function () { + // Assert something + assert.ok(true); + } +, 'async test': function (next) { + // Assert something else + assert.ok(true); + // Won't go next until this is called + next(); + } +, 'another sync test': function () { + // Assert something else + assert.ok(true); + } +}; + +//module.exports = tests; + +var p = new jake.NpmPublishTask('jake', [ + 'Makefile' +, 'Jakefile' +, 'README.md' +, 'package.json' +, 'lib/*' +, 'bin/*' +, 'tests/*' +]); \ No newline at end of file diff --git a/jake/jake.d.ts b/jake/jake.d.ts new file mode 100644 index 0000000000..ec6f20d2bc --- /dev/null +++ b/jake/jake.d.ts @@ -0,0 +1,388 @@ +// Type definitions for jake +// Project: https://github.com/mde/jake +// Definitions by: Kon +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +/** + * Complets an asynchronous task, allowing Jake's execution to proceed to the next task + */ +function complete(): void; + +/** + * Creates a description for a Jake Task (or FileTask, DirectoryTask). When invoked, the description that iscreated will be associated with whatever Task is created next. + * @param description The description for the Task + */ +function desc(description:string): void; + +/** + * Creates a Jake DirectoryTask. Can be used as a prerequisite for FileTasks, or for simply ensuring a directory exists for use with a Task's action. + * @param name The name of the DiretoryTask + */ +function directory(name:string): jake.DirectoryTask; + + +/** + * Causes Jake execution to abort with an error. Allows passing an optional error code, which will be used to set the exit-code of exiting process. + * @param err The error to thow when aborting execution. If this argument is an Error object, it will simply be thrown. If a String, it will be used as the error-message. (If it is a multi-line String, the first line will be used as the Error message, and the remaining lines will be used as the error-stack.) + */ +function fail(...err:string[]): void; +function fail(...err:Error[]): void; +function fail(...err:any[]): void; + +/** + * Creates a Jake FileTask. + * @name name The name of the Task + * @param prereqs Prerequisites to be run before this task + * @param action The action to perform for this task + * @param opts Perform this task asynchronously. If you flag a task with this option, you must call the global `complete` method inside the task's action, for execution to proceed to the next task. + */ +function file(name:string, prereqs?:string[], action?:()=>void, opts?:jake.FileTaskOptions): jake.FileTask; + +/** + * Creates a namespace which allows logical grouping of tasks, and prevents name-collisions with task-names. Namespaces can be nested inside of other namespaces. + * @param name The name of the namespace + * @param scope The enclosing scope for the namespaced tasks + */ +function namespace(name:string, scope:()=>void): void; + +/** + * @param name The name of the Task + * @param prereqs Prerequisites to be run before this task + * @param action The action to perform for this task + * @param opts + */ +function task(name:string, prereqs?:string[], action?:(...params:any[])=>any, opts?:jake.TaskOptions): jake.Task; +function task(name:string, action?:(...params:any[])=>any, opts?:jake.TaskOptions): jake.Task; +function task(name:string, opts?:jake.TaskOptions, action?:(...params:any[])=>any): jake.Task; + +module jake{ + + //////////////////////////////////////////////////////////////////////////////////// + // File-utils ////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////////// + + interface UtilOptions{ + silent?: bool; + } + + /** + * The jake.mkdirP utility recursively creates a set of nested directories. It will not throw an error if any of the directories already exists. + * https://github.com/substack/node-mkdirp + */ + export function mkdirP(name:string, mode?:string, f?:(er:Error, made:any)=>void): void; + export function mkdirP(name:string, f?:(er:Error, made:any)=>void): void; + + /** + * The jake.cpR utility does a recursive copy of a file or directory. + * Note that this command can only copy files and directories; it does not perform globbing (so arguments like '*.txt' are not possible). + * @param path the file/directory to copy, + * @param destination the destination. + */ + export function cpR(path:string, destination:string, opts?:UtilOptions, callback?:()=>void): void; + export function cpR(path:string, destination:string, callback?:(err:Error)=>void): void; + + /** + * The jake.readdirR utility gives you a recursive directory listing, giving you output somewhat similar to the Unix find command. It only works with a directory name, and does not perform filtering or globbing. + * @return an array of filepaths for all files in the 'pkg' directory, and all its subdirectories. + */ + export function readdirR(name:string, opts?:UtilOptions): string[]; + + /** + * The jake.rmRf utility recursively removes a directory and all its contents. + */ + export function rmRf(name:string, opts?:UtilOptions): void; + + ////////////////////////////////////////////////////////////////////////////////////////////// + // Running shell-commands //////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////////////// + + interface ExecOptions{ + /** + * print to stdout, default false + */ + + printStdout?:bool; + /** + * print to stderr, default false + */ + printStderr?:bool; + + /** + * stop execution on error, default true + */ + breakOnError?:bool; + } + export function exec(cmds:string[], callback?:()=>void, opts?:ExecOptions); + + + /** + * @event cmdStart When a new command begins to run. Passes one arg, the command being run. + * @event cmdEnd When a command finishes. Passes one arg, the command being run. + * @event stdout When the stdout for the child-process recieves data. This streams the stdout data. Passes one arg, the chunk of data. + * @event stderr When the stderr for the child-process recieves data. This streams the stderr data. Passes one arg, the chunk of data. + * @event error When a shell-command + */ + export interface Exec extends EventEmitter{ + constructor(cmds:string[], callback?:()=>void, opts?:ExecOptions); + constructor(cmds:string[], opts?:ExecOptions, callback?:()=>void); + constructor(cmds:string, callback?:()=>void, opts?:ExecOptions); + constructor(cmds:string, opts?:ExecOptions, callback?:()=>void); + append(cmd:string): void; + run(): void; + } + + export function createExec(cmds:string[], callback?:()=>void, opts?:ExecOptions ):Exec; + export function createExec(cmds:string[], opts?:ExecOptions, callback?:()=>void):Exec; + export function createExec(cmds:string, callback?:()=>void, opts?:ExecOptions ):Exec; + export function createExec(cmds:string, opts?:ExecOptions, callback?:()=>void):Exec; + + //////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Logging and output //////////////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////////////////////////////////////////////////// + + interface Logger{ + log(value:any): void; + error(value:any): void; + } + + export var logger: Logger; + + ////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // program //////////////////////////////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + export var program: { + opts: { + [name:string]: any; + quiet: bool; + }; + taskNames: string[]; + taskArgs: string[]; + envVars: { [key:string]: string; }; + }; + + + ////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Tasks ///////////////////////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + + export interface TaskOptions{ + /** + * Perform this task asynchronously. If you flag a task with this option, you must call the global `complete` method inside the task's action, for execution to proceed to the next task. + * @default false + */ + asyc?: bool; + } + + /** + * A Jake Task + * + * @event complete + */ + export class Task implements EventEmitter{ + /** + * @name name The name of the Task + * @param prereqs Prerequisites to be run before this task + * @param action The action to perform for this task + * @param opts Perform this task asynchronously. If you flag a task with this option, you must call the global `complete` method inside the task's action, for execution to proceed to the next task. + */ + constructor(name:string, prereqs?:string[], action?:()=>void, opts?:TaskOptions); + + /** + * Runs prerequisites, then this task. If the task has already been run, will not run the task again. + */ + invoke(): void; + + /** + * Runs this task, without running any prerequisites. If the task has already been run, it will still run it again. + */ + reenable(): void; + + addListener(event: string, listener: Function); + on(event: string, listener: Function); + once(event: string, listener: Function): void; + removeListener(event: string, listener: Function): void; + removeAllListener(event: string): void; + setMaxListeners(n: number): void; + listeners(event: string): { Function; }[]; + emit(event: string, arg1?: any, arg2?: any): void; + } + + + + export class DirectoryTask{ + /** + * @param name The name of the directory to create. + */ + constructor(name:string); + } + + export interface FileTaskOptions{ + /** + * Perform this task asynchronously. If you flag a task with this option, you must call the global `complete` method inside the task's action, for execution to proceed to the next task. + * @default false + */ + asyc?: bool; + } + + export class FileTask{ + /** + * @param name The name of the Task + * @param prereqs Prerequisites to be run before this task + * @param action The action to perform to create this file + * @param opts Perform this task asynchronously. If you flag a task with this option, you must call the global `complete` method inside the task's action, for execution to proceed to the next task. + */ + constructor(name:string, prereqs?:string[], action?:()=>void, opts?:FileTaskOptions); + } + + interface FileFilter{ + (filename:string): bool; + } + + export class FileList{ + constructor(); + + /** + * Includes file-patterns in the FileList. Should be called with one or more + * pattern for finding file to include in the list. Arguments should be strings + * for either a glob-pattern or a specific file-name, or an array of them + */ + include(files:string[]): void; + include(...files:string[]): void; + + /** + * Indicates whether a particular file would be filtered out by the current + * exclusion rules for this FileList. + * @param name The filename to check + * @return Whether or not the file should be excluded + */ + shouldExclude(name:string): bool; + + /** + * Excludes file-patterns from the FileList. Should be called with one or more + * pattern for finding file to include in the list. Arguments can be: + * 1. Strings for either a glob-pattern or a specific file-name + * 2. Regular expression literals + * 3. Functions to be run on the filename that return a true/false + */ + exclude(file:string[]): void; + exclude(...file:string[]): void; + exclude(file:RegExp[]): void; + exclude(...file:RegExp[]): void; + exclude(file:FileFilter[]): void; + exclude(...file:FileFilter[]): void; + + + /** + * Populates the FileList from the include/exclude rules with a list of + * actual files + */ + resolve(): void; + + /** + * Convert to a plain-jane array + */ + toArray(): string[]; + + /** + * Get rid of any current exclusion rules + */ + clearExclude(): void; + } + + export class PackageTask{ + /** + * Instantiating a PackageTask creates a number of Jake Tasks that make packaging and distributing your software easy. + * @param name The name of the project + * @param version The current project version (will be appended to the project-name in the package-archive + * @param definition Defines the contents of the package, and format of the package-archive. Will be executed on the instantiated PackageTask (i.e., 'this', will be the PackageTask instance), to set the various instance-propertiess. + */ + constructor(name:string, version:string, definition:()=>void); + + /** + * Equivalent to the '-C' command for the `tar` and `jar` commands. ("Change to this directory before adding files.") + */ + archiveChangeDir: string; + + /** + * Specifies the files and directories to include in the package-archive. If unset, this will default to the main package directory -- i.e., name + version. + */ + archiveContentDir: string; + + /** + * The shell-command to use for creating jar archives. + */ + jarCommand: string; + + /** + * Can be set to point the `jar` utility at a manifest file to use in a .jar archive. If unset, one will be automatically created by the `jar` utility. This path should be relative to the root of the package directory (this.packageDir above, likely 'pkg') + */ + manifestFile: string; + + /** + * The name of the project + */ + name: string; + + /** + * If set to true, uses the `jar` utility to create a .jar archive of the pagckage + */ + needJar: bool; + + /** + * If set to true, uses the `tar` utility to create a gzip .tgz archive of the pagckage + */ + needTar: bool; + + /** + * If set to true, uses the `tar` utility to create a bzip2 .bz2 archive of the pagckage + */ + needTarBz2: bool; + + /** + * If set to true, uses the `zip` utility to create a .zip archive of the pagckage + */ + needZip: bool; + + /** + * The list of files and directories to include in the package-archive + */ + packageFiles: FileList; + + /** + * The shell-command to use for creating tar archives. + */ + tarCommand: string; + + /** + * The project version-string + */ + version: string; + + /** + * The shell-command to use for creating zip archives. + */ + zipCommand: string; + + } + + export class TestTask{ + constructor(name:string, definition?:()=>void); + } + + export class NpmPublishTask{ + constructor(name:string, packageFiles:string[]); + } + + export function addListener(event: string, listener: Function); + export function on(event: string, listener: Function); + export function once(event: string, listener: Function): void; + export function removeListener(event: string, listener: Function): void; + export function removeAllListener(event: string): void; + export function setMaxListeners(n: number): void; + export function listeners(event: string): { Function; }[]; + export function emit(event: string, arg1?: any, arg2?: any): void; +} \ No newline at end of file diff --git a/jasmine/jasmine-tests.ts b/jasmine/jasmine-tests.ts index 32339676a6..46507d68de 100644 --- a/jasmine/jasmine-tests.ts +++ b/jasmine/jasmine-tests.ts @@ -60,7 +60,7 @@ describe("Included matchers:", () => { foo: 'foo' }; expect(a.foo).toBeDefined(); - expect(a.bar).not.toBeDefined(); + expect((a).bar).not.toBeDefined(); }); it("The `toBeUndefined` matcher compares against `undefined`", () => { @@ -68,7 +68,7 @@ describe("Included matchers:", () => { foo: 'foo' }; expect(a.foo).not.toBeUndefined(); - expect(a.bar).toBeUndefined(); + expect((a).bar).toBeUndefined(); }); it("The 'toBeNull' matcher compares against null", () => { @@ -120,7 +120,7 @@ describe("Included matchers:", () => { return 1 + 2; }; var bar = () => { - return a + 1; + //return a + 1; }; expect(foo).not.toThrow(); expect(bar).toThrow(); @@ -439,7 +439,7 @@ describe("Asynchronous specs", () => { currentWindowOnload(null); } - document.querySelector('.version').innerHTML = jasmineEnv.versionString(); + (document.querySelector('.version')).innerHTML = jasmineEnv.versionString(); execJasmine(); }; diff --git a/jasmine/jasmine.d.ts b/jasmine/jasmine.d.ts index 0d16559e92..05e4370040 100644 --- a/jasmine/jasmine.d.ts +++ b/jasmine/jasmine.d.ts @@ -7,7 +7,8 @@ declare function describe(description: string, specDefinitions: Function): void; declare function xdescribe(description: string, specDefinitions: Function): void; -declare function it(expectation: string, assertion: Function): void; +declare function it(expectation: string, assertion: () => void ): void; +declare function it(expectation: string, assertion: (done: (err?) => void) => void ): void; declare function xit(expectation: string, assertion: Function): void; declare function beforeEach(action: Function): void; @@ -23,7 +24,6 @@ declare function runs(asyncMethod: Function): void; declare function waitsFor(latchMethod: () => bool, failureMessage: string, timeout?: number): void; declare function waits(timeout?: number): void; - declare module jasmine { var Clock: Clock; @@ -165,6 +165,8 @@ declare module jasmine { toBeLessThan(expected): bool; toBeGreaterThan(expected): bool; toBeCloseTo(expected, precision): bool; + toContainHtml(expected: string): bool; + toContainText(expected: string): bool; toThrow(expected? ): bool; not: Matchers; @@ -291,4 +293,6 @@ declare module jasmine { Clock: Clock; util: Util; } + + export var HtmlReporter: any; } \ No newline at end of file diff --git a/jqrangeslider/jqrangeslider-tests.ts b/jqrangeslider/jqrangeslider-tests.ts index 37ffeb8eff..b4e3875f84 100644 --- a/jqrangeslider/jqrangeslider-tests.ts +++ b/jqrangeslider/jqrangeslider-tests.ts @@ -94,7 +94,10 @@ $("#formatterExample").dateRangeSlider({ formatter: (val: Date) => { var days = val.getDay(), month = val.getMonth() + 1, - year = val.getYear(); + // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getYear#Description + // getYear is no longer used and has been replaced by the getFullYear method. + // year = val.getYear(); + year = val.getFullYear(); return days + "/" + month + "/" + year; } }); diff --git a/jquery.bbq/jquery.bbq-tests.ts b/jquery.bbq/jquery.bbq-tests.ts new file mode 100644 index 0000000000..1543ae63c8 --- /dev/null +++ b/jquery.bbq/jquery.bbq-tests.ts @@ -0,0 +1,1282 @@ +/// +/// + + +// ************** Tests to jquery JQueryParam interface +var myObject = { + a: { + one: 1, + two: 2, + three: 3 + }, + b: [1,2,3] +}; +var recursiveEncoded = $.param(myObject); +var recursiveDecoded = decodeURIComponent($.param(myObject)); +var shallowEncoded = $.param(myObject, true); +var shallowDecoded = decodeURIComponent(shallowEncoded); + +var params = { width:1680, height:1050 }; +var str = jQuery.param(params); +$("#results").text(str); + +// <=1.3.2: +$.param({ a: [2,3,4] }) // "a=2&a=3&a=4" +// >=1.4: +$.param({ a: [2,3,4] }) // "a[]=2&a[]=3&a[]=4" + +// <=1.3.2: +$.param({ a: { b:1,c:2 }, d: [3,4,{ e:5 }] }) // "a=[object+Object]&d=3&d=4&d=[object+Object]" +// >=1.4: +$.param({ a: { b:1,c:2 }, d: [3,4,{ e:5 }] }) // "a[b]=1&a[c]=2&d[]=3&d[]=4&d[2][e]=5" +// ************************************************************* + +// Not sure why this isn't set by default in qunit.js.. +QUnit.jsDump.HTML = false; + +$(function(){ // START CLOSURE + + +var old_jquery = $.fn.jquery < '1.4', + is_chrome = /chrome/i.test( navigator.userAgent ), + params_init = 'a[]=4&a[]=5&a[]=6&b[x][]=7&b[y]=8&b[z][]=9&b[z][]=0&b[z][]=true&b[z][]=false&b[z][]=undefined&b[z][]=&c=1', + init_url, + ajaxcrawlable_init = $.param.fragment.ajaxCrawlable(), + aps = Array.prototype.slice; + +if ( $.param.querystring() !== params_init || $.param.fragment() !== params_init ) { + init_url = window.location.href; + init_url = $.param.querystring( init_url, params_init, 2 ); + init_url = $.param.fragment( init_url, params_init, 2 ); + window.location.href = init_url; +} + +$('#jq_version').html( $.fn.jquery ); + +function notice( txt? ) { + if ( txt ) { + $('#notice').html( txt ); + } else { + $('#notice').hide(); + } +}; + +function run_many_tests(...args: any[]) { + var tests = aps.call( arguments ), + delay = typeof tests[0] === 'number' && tests.shift(), + func_each = $.isFunction( tests[0] ) && tests.shift(), + func_done = $.isFunction( tests[0] ) && tests.shift(), + result; + + function set_result( i, test ) { + result = $.isArray( test ) + ? func_each.apply( this, test ) + : $.isFunction( test ) + ? test( result ) + : ''; + }; + + if ( delay ) { + stop(); + + (function loopy(){ + //test && test.func && test.func( result ); + if ( tests.length ) { + set_result( 0, tests.shift() ); + setTimeout( loopy, delay ); + } else { + func_done && func_done(); + start(); + } + })(); + + } else { + $.each( tests, set_result ); + func_done && func_done(); + } +} + +//////////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// + +QUnit.module( 'jQuery.param' ); + +var params_obj = { a:['4','5','6'], b:{x:['7'], y:'8', z:['9','0','true','false','undefined','']}, c:'1' }, + params_obj_coerce = { a:[4,5,6] },//, b:{x:[7], y:8, z:[9,0,true,false,undefined,'']}, c:1 }, + params_str = params_init, + params_str_old = 'a=4&a=5&a=6&b=[object+Object]&c=1', + + // If a params fragment starts with ! and BBQ is not in ajaxCrawlable mode, + // things can get very ugly, very quickly. + params_obj_bang = { "!a":['4'], a:['5','6'], b:{x:['7'], y:'8', z:['9','0','true','false','undefined','']}, c:'1' }, + params_obj_bang_coerce = { "!a":[4], a:[5,6] };//, b:{x:[7], y:8, z:[9,0,true,false,undefined,'']}, c:1 }; + +test( 'jQuery.param.sorted', function() { + var tests = [ + { + obj: {z:1,b:2,ab:3,bc:4,ba:5,aa:6,a1:7,x:8}, + traditional: false, + expected: 'a1=7&aa=6&ab=3&b=2&ba=5&bc=4&x=8&z=1' + }, + { + obj: {z:1,b:[6,5,4],x:2,a:[3,2,1]}, + traditional: false, + expected: 'a[]=3&a[]=2&a[]=1&b[]=6&b[]=5&b[]=4&x=2&z=1', + expected_old: 'a=3&a=2&a=1&b=6&b=5&b=4&x=2&z=1' + }, + { + obj: {z:1,b:[6,5,4],x:2,a:[3,2,1]}, + traditional: true, + expected: 'a=3&a=2&a=1&b=6&b=5&b=4&x=2&z=1' + }, + { + obj: {a:[[4,[5,6]],[[7,8],9]]}, + traditional: false, + expected: 'a[0][]=4&a[0][1][]=5&a[0][1][]=6&a[1][0][]=7&a[1][0][]=8&a[1][]=9', + expected_old: 'a=4,5,6&a=7,8,9' // obviously not great, but that's the way jQuery used to roll + } + ]; + + if ( $.fn.jquery != '1.4.1' ) { + // this explodes in jQuery 1.4.1 + tests.push({ + obj: {z:1,'b[]':[6,5,4],x:2,'a[]':[3,2,1]}, + obj_alt: {z:1,b:[6,5,4],x:2,a:[3,2,1]}, + traditional: false, + expected: 'a[]=3&a[]=2&a[]=1&b[]=6&b[]=5&b[]=4&x=2&z=1' + }); + } + + expect( tests.length * 2 + 6 ); + + $.each( tests, function(i,test){ + var unsorted = $.param( test.obj, test.traditional ), + sorted = $.param.sorted( test.obj, test.traditional ); + + equal( decodeURIComponent( sorted ), old_jquery && test.expected_old || test.expected, 'params should be sorted' ); + deepEqual( $.deparam( unsorted, true ), $.deparam( sorted, true ), 'sorted params should deparam the same as unsorted params' ) + }); + + equal( $.param.fragment( 'foo', '#b=2&a=1' ), 'foo#a=1&b=2', 'params should be sorted' ); + equal( $.param.fragment( 'foo', '#b=2&a=1', 1 ), 'foo#a=1&b=2', 'params should be sorted' ); + equal( $.param.fragment( 'foo', '#b=2&a=1', 2 ), 'foo#b=2&a=1', 'params should NOT be sorted' ); + equal( $.param.fragment( 'foo#c=3&a=4', '#b=2&a=1' ), 'foo#a=1&b=2&c=3', 'params should be sorted' ); + equal( $.param.fragment( 'foo#c=3&a=4', '#b=2&a=1', 1 ), 'foo#a=4&b=2&c=3', 'params should be sorted' ); + equal( $.param.fragment( 'foo#c=3&a=4', '#b=2&a=1', 2 ), 'foo#b=2&a=1', 'params should NOT be sorted' ); + +}); + +test( 'jQuery.param.querystring', function() { + expect( 11 ); + + equal( $.param.querystring( 'http://example.com/' ), '', 'properly identifying params' ); + equal( $.param.querystring( 'http://example.com/?foo' ),'foo', 'properly identifying params' ); + equal( $.param.querystring( 'http://example.com/?foo#bar' ),'foo', 'properly identifying params' ); + equal( $.param.querystring( 'http://example.com/?foo#bar?baz' ),'foo', 'properly identifying params' ); + equal( $.param.querystring( 'http://example.com/#foo' ),'', 'properly identifying params' ); + equal( $.param.querystring( 'http://example.com/#foo?bar' ),'', 'properly identifying params' ); + + equal( $.param.querystring(), params_str, 'params string from window.location' ); + equal( $.param.querystring( '?' + params_str ), params_str, 'params string from url' ); + equal( $.param.querystring( 'foo.html?' + params_str ), params_str, 'params string from url' ); + equal( $.param.querystring( 'http://a:b@example.com:1234/foo.html?' + params_str ), params_str, 'params string from url' ); + equal( $.param.querystring( 'http://a:b@example.com:1234/foo.html?' + params_str + '#bippity-boppity-boo' ), params_str, 'params string from url' ); +}); + +test( 'jQuery.param.querystring - build URL', function() { + expect( 10 ); + + function fake_encode( params_str ) { + return '?' + $.map( params_str.split('&'), encodeURIComponent ).join('&').replace( /%3D/g, '=' ).replace( /%2B/g, '+' ); + } + + var pre = 'http://a:b@example.com:1234/foo.html', + post = '#get-on-the-floor', + current_url = pre + post; + + run_many_tests( + + // execute this for each array item + function(){ + current_url = $.param.querystring.apply( this, [ current_url ].concat( aps.call( arguments ) ) ); + }, + + // tests: + + [ { a:'2' } ], + + function(result){ + equal( current_url, pre + '?a=2' + post, '$.param.querystring( url, Object )' ); + }, + + [ { b:'2' } ], + + function(result){ + equal( current_url, pre + '?a=2&b=2' + post, '$.param.querystring( url, Object )' ); + }, + + [ { c:true, d:false, e:'undefined', f:'' } ], + + function(result){ + equal( current_url, pre + '?a=2&b=2&c=true&d=false&e=undefined&f=' + post, '$.param.querystring( url, Object )' ); + }, + + [ { a:[4,5,6]}],//, b:{x:[7], y:8, z:[9,0,'true','false','undefined','']} }, 2 ], + + function(result){ + var params = old_jquery + ? 'a=4&a=5&a=6&b=[object+Object]' + : 'a[]=4&a[]=5&a[]=6&b[x][]=7&b[y]=8&b[z][]=9&b[z][]=0&b[z][]=true&b[z][]=false&b[z][]=undefined&b[z][]='; + + equal( current_url, pre + fake_encode( params ) + post, '$.param.querystring( url, Object, 2 )' ); + }, + + [ { a:'1', c:'2' }, 1 ], + + function(result){ + var params = old_jquery + ? 'a=4&a=5&a=6&b=[object+Object]&c=2' + : 'a[]=4&a[]=5&a[]=6&b[x][]=7&b[y]=8&b[z][]=9&b[z][]=0&b[z][]=true&b[z][]=false&b[z][]=undefined&b[z][]=&c=2'; + + equal( current_url, pre + fake_encode( params ) + post, '$.param.querystring( url, Object, 1 )' ); + }, + + [ 'foo=1' ], + + function(result){ + var params = old_jquery + ? 'a=4&a=5&a=6&b=[object+Object]&c=2&foo=1' + : 'a[]=4&a[]=5&a[]=6&b[x][]=7&b[y]=8&b[z][]=9&b[z][]=0&b[z][]=true&b[z][]=false&b[z][]=undefined&b[z][]=&c=2&foo=1'; + + equal( current_url, pre + fake_encode( params ) + post, '$.param.querystring( url, String )' ); + }, + + [ 'foo=2&bar=3', 1 ], + + function(result){ + var params = old_jquery + ? 'a=4&a=5&a=6&b=[object+Object]&bar=3&c=2&foo=1' + : 'a[]=4&a[]=5&a[]=6&b[x][]=7&b[y]=8&b[z][]=9&b[z][]=0&b[z][]=true&b[z][]=false&b[z][]=undefined&b[z][]=&bar=3&c=2&foo=1'; + + equal( current_url, pre + fake_encode( params ) + post, '$.param.querystring( url, String, 1 )' ); + }, + + [ 'http://example.com/test.html?/path/to/file.php#the-cow-goes-moo', 2 ], + + function(result){ + equal( current_url, pre + '?/path/to/file.php' + post, '$.param.querystring( url, String, 2 )' ); + }, + + [ '?another-example', 2 ], + + function(result){ + equal( current_url, pre + '?another-example' + post, '$.param.querystring( url, String, 2 )' ); + }, + + [ 'i_am_out_of_witty_strings', 2 ], + + function(result){ + equal( current_url, pre + '?i_am_out_of_witty_strings' + post, '$.param.querystring( url, String, 2 )' ); + } + + ); + +}); + +test( 'jQuery.param.fragment', function() { + expect( 29 ); + + equal( $.param.fragment( 'http://example.com/' ), '', 'properly identifying params' ); + equal( $.param.fragment( 'http://example.com/?foo' ),'', 'properly identifying params' ); + equal( $.param.fragment( 'http://example.com/?foo#bar' ),'bar', 'properly identifying params' ); + equal( $.param.fragment( 'http://example.com/?foo#bar?baz' ),'bar?baz', 'properly identifying params' ); + equal( $.param.fragment( 'http://example.com/#foo' ),'foo', 'properly identifying params' ); + equal( $.param.fragment( 'http://example.com/#foo?bar' ),'foo?bar', 'properly identifying params' ); + + equal( $.param.fragment( 'http://example.com/' ), '', 'properly identifying params' ); + equal( $.param.fragment( 'http://example.com/?foo' ),'', 'properly identifying params' ); + equal( $.param.fragment( 'http://example.com/?foo#!bar' ),'!bar', 'properly identifying params' ); + equal( $.param.fragment( 'http://example.com/?foo#!bar?baz' ),'!bar?baz', 'properly identifying params' ); + equal( $.param.fragment( 'http://example.com/#!foo' ),'!foo', 'properly identifying params' ); + equal( $.param.fragment( 'http://example.com/#!foo?bar' ),'!foo?bar', 'properly identifying params' ); + + equal( $.param.fragment(), params_str, 'params string from window.location' ); + equal( $.param.fragment( '#' + params_str ), params_str, 'params string from url' ); + equal( $.param.fragment( 'foo.html#' + params_str ), params_str, 'params string from url' ); + equal( $.param.fragment( 'http://a:b@example.com:1234/foo.html#' + params_str ), params_str, 'params string from url' ); + equal( $.param.fragment( 'http://a:b@example.com:1234/foo.html?bippity-boppity-boo#' + params_str ), params_str, 'params string from url' ); + + $.param.fragment.ajaxCrawlable( true ); + + equal( $.param.fragment( 'http://example.com/' ), '', 'properly identifying params' ); + equal( $.param.fragment( 'http://example.com/?foo' ),'', 'properly identifying params' ); + equal( $.param.fragment( 'http://example.com/?foo#bar' ),'bar', 'properly identifying params' ); + equal( $.param.fragment( 'http://example.com/?foo#bar?baz' ),'bar?baz', 'properly identifying params' ); + equal( $.param.fragment( 'http://example.com/#foo' ),'foo', 'properly identifying params' ); + equal( $.param.fragment( 'http://example.com/#foo?bar' ),'foo?bar', 'properly identifying params' ); + + equal( $.param.fragment( 'http://example.com/' ), '', 'properly identifying params' ); + equal( $.param.fragment( 'http://example.com/?foo' ),'', 'properly identifying params' ); + equal( $.param.fragment( 'http://example.com/?foo#!bar' ),'bar', 'properly identifying params' ); + equal( $.param.fragment( 'http://example.com/?foo#!bar?baz' ),'bar?baz', 'properly identifying params' ); + equal( $.param.fragment( 'http://example.com/#!foo' ),'foo', 'properly identifying params' ); + equal( $.param.fragment( 'http://example.com/#!foo?bar' ),'foo?bar', 'properly identifying params' ); + + $.param.fragment.ajaxCrawlable( false ); + +}); + +test( 'jQuery.param.fragment - build URL', function() { + expect( 40 ); + + function fake_encode( params_str ) { + return '#' + $.map( params_str.split('&'), encodeURIComponent ).join('&').replace( /%3D/g, '=' ).replace( /%2B/g, '+' ); + } + + var pre = 'http://a:b@example.com:1234/foo.html?and-dance-with-me', + current_url = pre; + + run_many_tests( + + // execute this for each array item + function(){ + current_url = $.param.fragment.apply( this, [ current_url ].concat( aps.call( arguments ) ) ); + }, + + // tests: + + [ { a:'2' } ], + + function(result){ + equal( current_url, pre + '#a=2', '$.param.fragment( url, Object )' ); + }, + + [ { b:'2' } ], + + function(result){ + equal( current_url, pre + '#a=2&b=2', '$.param.fragment( url, Object )' ); + }, + + [ { c:true, d:false, e:'undefined', f:'' } ], + + function(result){ + equal( current_url, pre + '#a=2&b=2&c=true&d=false&e=undefined&f=', '$.param.fragment( url, Object )' ); + }, + + [ { a:[4,5,6]}],//, b:{x:[7], y:8, z:[9,0,'true','false','undefined','']} }, 2 ], + + function(result){ + var params = old_jquery + ? 'a=4&a=5&a=6&b=[object+Object]' + : 'a[]=4&a[]=5&a[]=6&b[x][]=7&b[y]=8&b[z][]=9&b[z][]=0&b[z][]=true&b[z][]=false&b[z][]=undefined&b[z][]='; + + equal( current_url, pre + fake_encode( params ), '$.param.fragment( url, Object, 2 )' ); + }, + + [ { a:'1', c:'2' }, 1 ], + + function(result){ + var params = old_jquery + ? 'a=4&a=5&a=6&b=[object+Object]&c=2' + : 'a[]=4&a[]=5&a[]=6&b[x][]=7&b[y]=8&b[z][]=9&b[z][]=0&b[z][]=true&b[z][]=false&b[z][]=undefined&b[z][]=&c=2'; + + equal( current_url, pre + fake_encode( params ), '$.param.fragment( url, Object, 1 )' ); + }, + + [ 'foo=1' ], + + function(result){ + var params = old_jquery + ? 'a=4&a=5&a=6&b=[object+Object]&c=2&foo=1' + : 'a[]=4&a[]=5&a[]=6&b[x][]=7&b[y]=8&b[z][]=9&b[z][]=0&b[z][]=true&b[z][]=false&b[z][]=undefined&b[z][]=&c=2&foo=1'; + + equal( current_url, pre + fake_encode( params ), '$.param.fragment( url, String )' ); + }, + + [ 'foo=2&bar=3', 1 ], + + function(result){ + var params = old_jquery + ? 'a=4&a=5&a=6&b=[object+Object]&bar=3&c=2&foo=1' + : 'a[]=4&a[]=5&a[]=6&b[x][]=7&b[y]=8&b[z][]=9&b[z][]=0&b[z][]=true&b[z][]=false&b[z][]=undefined&b[z][]=&bar=3&c=2&foo=1'; + + equal( current_url, pre + fake_encode( params ), '$.param.fragment( url, String, 1 )' ); + }, + + [ 'http://example.com/test.html?the-cow-goes-moo#/path/to/file.php', 2 ], + + function(result){ + equal( current_url, pre + '#/path/to/file.php', '$.param.fragment( url, String, 2 )' ); + }, + + [ '#another-example', 2 ], + + function(result){ + equal( current_url, pre + '#another-example', '$.param.fragment( url, String, 2 )' ); + }, + + [ 'i_am_out_of_witty_strings', 2 ], + + function(result){ + equal( current_url, pre + '#i_am_out_of_witty_strings', '$.param.fragment( url, String, 2 )' ); + } + + ); + + $.param.fragment.ajaxCrawlable( true ); + + equal( $.param.fragment( 'foo', {} ) , 'foo#!', '$.param.fragment( url, Object )' ); + equal( $.param.fragment( 'foo', { b:2, a:1 } ) , 'foo#!a=1&b=2', '$.param.fragment( url, Object )' ); + equal( $.param.fragment( 'foo#', { b:2, a:1 } ) , 'foo#!a=1&b=2', '$.param.fragment( url, Object )' ); + equal( $.param.fragment( 'foo#!', { b:2, a:1 } ) , 'foo#!a=1&b=2', '$.param.fragment( url, Object )' ); + equal( $.param.fragment( 'foo#c=3&a=4', { b:2, a:1 } ) , 'foo#!a=1&b=2&c=3', '$.param.fragment( url, Object )' ); + equal( $.param.fragment( 'foo#!c=3&a=4', { b:2, a:1 } ) , 'foo#!a=1&b=2&c=3', '$.param.fragment( url, Object )' ); + + equal( $.param.fragment( 'foo', '' ) , 'foo#!', '$.param.fragment( url, String )' ); + equal( $.param.fragment( 'foo', 'b=2&a=1' ) , 'foo#!a=1&b=2', '$.param.fragment( url, String )' ); + equal( $.param.fragment( 'foo#', 'b=2&a=1' ) , 'foo#!a=1&b=2', '$.param.fragment( url, String )' ); + equal( $.param.fragment( 'foo#!', 'b=2&a=1' ) , 'foo#!a=1&b=2', '$.param.fragment( url, String )' ); + equal( $.param.fragment( 'foo#c=3&a=4', 'b=2&a=1' ) , 'foo#!a=1&b=2&c=3', '$.param.fragment( url, String )' ); + equal( $.param.fragment( 'foo#!c=3&a=4', 'b=2&a=1' ) , 'foo#!a=1&b=2&c=3', '$.param.fragment( url, String )' ); + + equal( $.param.fragment( 'foo', '#' ) , 'foo#!', '$.param.fragment( url, String )' ); + equal( $.param.fragment( 'foo', '#b=2&a=1' ) , 'foo#!a=1&b=2', '$.param.fragment( url, String )' ); + equal( $.param.fragment( 'foo#', '#b=2&a=1' ) , 'foo#!a=1&b=2', '$.param.fragment( url, String )' ); + equal( $.param.fragment( 'foo#!', '#b=2&a=1' ) , 'foo#!a=1&b=2', '$.param.fragment( url, String )' ); + equal( $.param.fragment( 'foo#c=3&a=4', '#b=2&a=1' ) , 'foo#!a=1&b=2&c=3', '$.param.fragment( url, String )' ); + equal( $.param.fragment( 'foo#!c=3&a=4', '#b=2&a=1' ) , 'foo#!a=1&b=2&c=3', '$.param.fragment( url, String )' ); + + equal( $.param.fragment( 'foo', '#!' ) , 'foo#!', '$.param.fragment( url, String )' ); + equal( $.param.fragment( 'foo', '#!b=2&a=1' ) , 'foo#!a=1&b=2', '$.param.fragment( url, String )' ); + equal( $.param.fragment( 'foo#', '#!b=2&a=1' ) , 'foo#!a=1&b=2', '$.param.fragment( url, String )' ); + equal( $.param.fragment( 'foo#!', '#!b=2&a=1' ) , 'foo#!a=1&b=2', '$.param.fragment( url, String )' ); + equal( $.param.fragment( 'foo#c=3&a=4', '#!b=2&a=1' ) , 'foo#!a=1&b=2&c=3', '$.param.fragment( url, String )' ); + equal( $.param.fragment( 'foo#!c=3&a=4', '#!b=2&a=1' ) , 'foo#!a=1&b=2&c=3', '$.param.fragment( url, String )' ); + + $.param.fragment.ajaxCrawlable( false ); + + // If a params fragment starts with ! and BBQ is not in ajaxCrawlable mode, + // things can get very ugly, very quickly. + equal( $.param.fragment( 'foo', '#!' ) , 'foo#!=', '$.param.fragment( url, String )' ); + equal( $.param.fragment( 'foo', '#!b=2&a=1' ) , 'foo#!b=2&a=1', '$.param.fragment( url, String )' ); + equal( $.param.fragment( 'foo#', '#!b=2&a=1' ) , 'foo#!b=2&a=1', '$.param.fragment( url, String )' ); + equal( $.param.fragment( 'foo#!', '#!b=2&a=1' ) , 'foo#!=&!b=2&a=1', '$.param.fragment( url, String )' ); + equal( $.param.fragment( 'foo#c=3&a=4', '#!b=2&a=1' ) , 'foo#!b=2&a=1&c=3', '$.param.fragment( url, String )' ); + equal( $.param.fragment( 'foo#!c=3&a=4', '#!b=2&a=1' ) , 'foo#!b=2&!c=3&a=1', '$.param.fragment( url, String )' ); + +}); + +test( 'jQuery.param.fragment.ajaxCrawlable', function() { + expect( 5 ); + + equal( ajaxcrawlable_init, false, 'ajaxCrawlable is disabled by default' ); + equal( $.param.fragment.ajaxCrawlable( true ), true, 'enabling ajaxCrawlable should return true' ); + equal( $.param.fragment.ajaxCrawlable(), true, 'ajaxCrawlable is now enabled' ); + equal( $.param.fragment.ajaxCrawlable( false ), false, 'disabling ajaxCrawlable should return false' ); + equal( $.param.fragment.ajaxCrawlable(), false, 'ajaxCrawlable is now disabled' ); +}); + +test( 'jQuery.param.fragment.noEscape', function() { + expect( 2 ); + + equal( $.param.fragment( '#', { foo: '/a,b@c$d+e&f=g h!' } ), '#foo=/a,b%40c%24d%2Be%26f%3Dg+h!', '/, should be unescaped, everything else but space (+) should be urlencoded' ); + + $.param.fragment.ajaxCrawlable( true ); + + equal( $.param.fragment( '#', { foo: '/a,b@c$d+e&f=g h!' } ), '#!foo=/a,b%40c%24d%2Be%26f%3Dg+h!', '/, should be unescaped, everything else but ! and space (+) should be urlencoded' ); + + $.param.fragment.ajaxCrawlable( false ); +}); + + + +//////////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// + +QUnit.module( 'jQuery.deparam' ); + +test( 'jQuery.deparam - 1.4-style params', function() { + expect( 2 ); + deepEqual( $.deparam( params_str ), params_obj, '$.deparam( String )' ); + deepEqual( $.deparam( params_str, true ), params_obj_coerce, '$.deparam( String, true )' ); +}); + +test( 'jQuery.deparam - pre-1.4-style params', function() { + var params_str = 'a=1&a=2&a=3&b=4&c=5&c=6&c=true&c=false&c=undefined&c=&d=7', + params_obj = { a:['1','2','3'], b:'4', c:['5','6','true','false','undefined',''], d:'7' }, + params_obj_coerce = { a:[1,2,3], b:4, c:[5,6,true,false,undefined,''], d:7 }; + + expect( 2 ); + deepEqual( $.deparam( params_str ), params_obj, '$.deparam( String )' ); + deepEqual( $.deparam( params_str, true ), params_obj_coerce, '$.deparam( String, true )' ); +}); + +test( 'jQuery.deparam.querystring', function() { + expect( 12 ); + + deepEqual( $.deparam.querystring(), params_obj, 'params obj from window.location' ); + deepEqual( $.deparam.querystring( /*true*/ ), params_obj_coerce, 'params obj from window.location, coerced' ); + deepEqual( $.deparam.querystring( params_str ), params_obj, 'params obj from string' ); + deepEqual( $.deparam.querystring( params_str, true ), params_obj_coerce, 'params obj from string, coerced' ); + deepEqual( $.deparam.querystring( '?' + params_str ), params_obj, 'params obj from string' ); + deepEqual( $.deparam.querystring( '?' + params_str, true ), params_obj_coerce, 'params obj from string, coerced' ); + deepEqual( $.deparam.querystring( 'foo.html?' + params_str ), params_obj, 'params obj from string' ); + deepEqual( $.deparam.querystring( 'foo.html?' + params_str, true ), params_obj_coerce, 'params obj from string, coerced' ); + deepEqual( $.deparam.querystring( 'http://a:b@example.com:1234/foo.html?' + params_str ), params_obj, 'params obj from string' ); + deepEqual( $.deparam.querystring( 'http://a:b@example.com:1234/foo.html?' + params_str, true ), params_obj_coerce, 'params obj from string, coerced' ); + deepEqual( $.deparam.querystring( 'http://a:b@example.com:1234/foo.html?' + params_str + '#bippity-boppity-boo' ), params_obj, 'params obj from string' ); + deepEqual( $.deparam.querystring( 'http://a:b@example.com:1234/foo.html?' + params_str + '#bippity-boppity-boo', true ), params_obj_coerce, 'params obj from string, coerced' ); +}); + +test( 'jQuery.deparam.fragment', function() { + expect( 36 ); + + deepEqual( $.deparam.fragment(), params_obj, 'params obj from window.location' ); + deepEqual( $.deparam.fragment( /*true*/ ), params_obj_coerce, 'params obj from window.location, coerced' ); + deepEqual( $.deparam.fragment( params_str ), params_obj, 'params obj from string' ); + deepEqual( $.deparam.fragment( params_str, true ), params_obj_coerce, 'params obj from string, coerced' ); + + deepEqual( $.deparam.fragment( '#' + params_str ), params_obj, 'params obj from string' ); + deepEqual( $.deparam.fragment( '#' + params_str, true ), params_obj_coerce, 'params obj from string, coerced' ); + deepEqual( $.deparam.fragment( 'foo.html#' + params_str ), params_obj, 'params obj from string' ); + deepEqual( $.deparam.fragment( 'foo.html#' + params_str, true ), params_obj_coerce, 'params obj from string, coerced' ); + deepEqual( $.deparam.fragment( 'http://a:b@example.com:1234/foo.html#' + params_str ), params_obj, 'params obj from string' ); + deepEqual( $.deparam.fragment( 'http://a:b@example.com:1234/foo.html#' + params_str, true ), params_obj_coerce, 'params obj from string, coerced' ); + deepEqual( $.deparam.fragment( 'http://a:b@example.com:1234/foo.html?bippity-boppity-boo#' + params_str ), params_obj, 'params obj from string' ); + deepEqual( $.deparam.fragment( 'http://a:b@example.com:1234/foo.html?bippity-boppity-boo#' + params_str, true ), params_obj_coerce, 'params obj from string, coerced' ); + + // If a params fragment starts with ! and BBQ is not in ajaxCrawlable mode, + // things can get very ugly, very quickly. + deepEqual( $.deparam.fragment( '#!' + params_str ), params_obj_bang, 'params obj from string' ); + deepEqual( $.deparam.fragment( '#!' + params_str, true ), params_obj_bang_coerce, 'params obj from string, coerced' ); + deepEqual( $.deparam.fragment( 'foo.html#!' + params_str ), params_obj_bang, 'params obj from string' ); + deepEqual( $.deparam.fragment( 'foo.html#!' + params_str, true ), params_obj_bang_coerce, 'params obj from string, coerced' ); + deepEqual( $.deparam.fragment( 'http://a:b@example.com:1234/foo.html#!' + params_str ), params_obj_bang, 'params obj from string' ); + deepEqual( $.deparam.fragment( 'http://a:b@example.com:1234/foo.html#!' + params_str, true ), params_obj_bang_coerce, 'params obj from string, coerced' ); + deepEqual( $.deparam.fragment( 'http://a:b@example.com:1234/foo.html?bippity-boppity-boo#!' + params_str ), params_obj_bang, 'params obj from string' ); + deepEqual( $.deparam.fragment( 'http://a:b@example.com:1234/foo.html?bippity-boppity-boo#!' + params_str, true ), params_obj_bang_coerce, 'params obj from string, coerced' ); + + $.param.fragment.ajaxCrawlable( true ); + + deepEqual( $.deparam.fragment( '#' + params_str ), params_obj, 'params obj from string' ); + deepEqual( $.deparam.fragment( '#' + params_str, true ), params_obj_coerce, 'params obj from string, coerced' ); + deepEqual( $.deparam.fragment( 'foo.html#' + params_str ), params_obj, 'params obj from string' ); + deepEqual( $.deparam.fragment( 'foo.html#' + params_str, true ), params_obj_coerce, 'params obj from string, coerced' ); + deepEqual( $.deparam.fragment( 'http://a:b@example.com:1234/foo.html#' + params_str ), params_obj, 'params obj from string' ); + deepEqual( $.deparam.fragment( 'http://a:b@example.com:1234/foo.html#' + params_str, true ), params_obj_coerce, 'params obj from string, coerced' ); + deepEqual( $.deparam.fragment( 'http://a:b@example.com:1234/foo.html?bippity-boppity-boo#' + params_str ), params_obj, 'params obj from string' ); + deepEqual( $.deparam.fragment( 'http://a:b@example.com:1234/foo.html?bippity-boppity-boo#' + params_str, true ), params_obj_coerce, 'params obj from string, coerced' ); + + deepEqual( $.deparam.fragment( '#!' + params_str ), params_obj, 'params obj from string' ); + deepEqual( $.deparam.fragment( '#!' + params_str, true ), params_obj_coerce, 'params obj from string, coerced' ); + deepEqual( $.deparam.fragment( 'foo.html#!' + params_str ), params_obj, 'params obj from string' ); + deepEqual( $.deparam.fragment( 'foo.html#!' + params_str, true ), params_obj_coerce, 'params obj from string, coerced' ); + deepEqual( $.deparam.fragment( 'http://a:b@example.com:1234/foo.html#!' + params_str ), params_obj, 'params obj from string' ); + deepEqual( $.deparam.fragment( 'http://a:b@example.com:1234/foo.html#!' + params_str, true ), params_obj_coerce, 'params obj from string, coerced' ); + deepEqual( $.deparam.fragment( 'http://a:b@example.com:1234/foo.html?bippity-boppity-boo#!' + params_str ), params_obj, 'params obj from string' ); + deepEqual( $.deparam.fragment( 'http://a:b@example.com:1234/foo.html?bippity-boppity-boo#!' + params_str, true ), params_obj_coerce, 'params obj from string, coerced' ); + + $.param.fragment.ajaxCrawlable( false ); +}); + +//////////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// + +QUnit.module( 'jQuery.fn' ); + +$.elemUrlAttr({ span: 'arbitrary_attr' }); +var test_elems = 'a form link span'.split(' '); + +function init_url_attr( container, url ) { + var container = $('
              ').hide().appendTo('body'); + $.each( test_elems, function(i,v){ + $('<' + v + '/>') + .attr( $.elemUrlAttr()[ v ], url ) + .appendTo( container ); + }); + return container; +}; + +function test_url_attr( container ) { + var url; + + $.each( test_elems, function(i,v){ + var val = container.children( v ).attr( $.elemUrlAttr()[ v ] ); + if ( !url ) { + url = val; + } else if ( val !== url ) { + url = -1; + } + }); + + return url; +}; + +test( 'jQuery.fn.querystring', function() { + expect( 60 ); + + function fake_encode( params_str ) { + return '?' + $.map( params_str.split('&'), encodeURIComponent ).join('&').replace( /%3D/g, '=' ).replace( /%2B/g, '+' ); + } + + var pre = 'http://a:b@example.com:1234/foo.html', + post = '#get-on-the-floor', + current_url = pre + post; + + run_many_tests( + + // execute this for each array item + function(){ + var container, + elems; + + container = init_url_attr( container, current_url ); + elems = container.children('span'); + equal( elems.length, 1, 'select the correct elements' ); + equal( elems.querystring.apply( elems, [ 'arbitrary_attr' ].concat( aps.call( arguments ) ) ), elems, 'pass query string' ); + + container = init_url_attr( container, current_url ); + elems = container.children('a, link'); + equal( elems.length, 2, 'select the correct elements' ); + equal( elems.querystring.apply( elems, [ 'href' ].concat( aps.call( arguments ) ) ), elems, 'pass query string' ); + + container = init_url_attr( container, current_url ); + elems = container.children(); + equal( elems.querystring.apply( elems, aps.call( arguments ) ), elems, 'pass query string' ); + + current_url = test_url_attr( container ); + }, + + // tests: + + [ { a:'2' } ], + + function(result){ + equal( current_url, pre + '?a=2' + post, '$.fn.querystring( url, Object )' ); + }, + + [ { b:'2' } ], + + function(result){ + equal( current_url, pre + '?a=2&b=2' + post, '$.fn.querystring( url, Object )' ); + }, + + [ { c:true, d:false, e:'undefined', f:'' } ], + + function(result){ + equal( current_url, pre + '?a=2&b=2&c=true&d=false&e=undefined&f=' + post, '$.fn.querystring( url, Object )' ); + }, + + [ { a:[4,5,6]}],//, b:{x:[7], y:8, z:[9,0,'true','false','undefined','']} }, 2 ], + + function(result){ + var params = old_jquery + ? 'a=4&a=5&a=6&b=[object+Object]' + : 'a[]=4&a[]=5&a[]=6&b[x][]=7&b[y]=8&b[z][]=9&b[z][]=0&b[z][]=true&b[z][]=false&b[z][]=undefined&b[z][]='; + + equal( current_url, pre + fake_encode( params ) + post, '$.fn.querystring( url, Object, 2 )' ); + }, + + [ { a:'1', c:'2' }, 1 ], + + function(result){ + var params = old_jquery + ? 'a=4&a=5&a=6&b=[object+Object]&c=2' + : 'a[]=4&a[]=5&a[]=6&b[x][]=7&b[y]=8&b[z][]=9&b[z][]=0&b[z][]=true&b[z][]=false&b[z][]=undefined&b[z][]=&c=2'; + + equal( current_url, pre + fake_encode( params ) + post, '$.fn.querystring( url, Object, 1 )' ); + }, + + [ 'foo=1' ], + + function(result){ + var params = old_jquery + ? 'a=4&a=5&a=6&b=[object+Object]&c=2&foo=1' + : 'a[]=4&a[]=5&a[]=6&b[x][]=7&b[y]=8&b[z][]=9&b[z][]=0&b[z][]=true&b[z][]=false&b[z][]=undefined&b[z][]=&c=2&foo=1'; + + equal( current_url, pre + fake_encode( params ) + post, '$.fn.querystring( url, String )' ); + }, + + [ 'foo=2&bar=3', 1 ], + + function(result){ + var params = old_jquery + ? 'a=4&a=5&a=6&b=[object+Object]&bar=3&c=2&foo=1' + : 'a[]=4&a[]=5&a[]=6&b[x][]=7&b[y]=8&b[z][]=9&b[z][]=0&b[z][]=true&b[z][]=false&b[z][]=undefined&b[z][]=&bar=3&c=2&foo=1'; + + equal( current_url, pre + fake_encode( params ) + post, '$.fn.querystring( url, String, 1 )' ); + }, + + [ 'http://example.com/test.html?/path/to/file.php#the-cow-goes-moo', 2 ], + + function(result){ + equal( current_url, pre + '?/path/to/file.php' + post, '$.fn.querystring( url, String, 2 )' ); + }, + + [ '?another-example', 2 ], + + function(result){ + equal( current_url, pre + '?another-example' + post, '$.fn.querystring( url, String, 2 )' ); + }, + + [ 'i_am_out_of_witty_strings', 2 ], + + function(result){ + equal( current_url, pre + '?i_am_out_of_witty_strings' + post, '$.fn.querystring( url, String, 2 )' ); + } + + ); + +}); + +test( 'jQuery.fn.fragment', function() { + expect( 240 ); + + function fake_encode( params_str ) { + return '#' + $.map( params_str.split('&'), encodeURIComponent ).join('&').replace( /%3D/g, '=' ).replace( /%2B/g, '+' ); + } + + var pre = 'http://a:b@example.com:1234/foo.html?and-dance-with-me', + current_url = pre; + + run_many_tests( + + // execute this for each array item + function( params, merge_mode ){ + current_url = test_fn_fragment( current_url, params, merge_mode ); + }, + + // tests: + + [ { a:'2' } ], + + function(result){ + equal( current_url, pre + '#a=2', '$.fn.fragment( url, Object )' ); + }, + + [ { b:'2' } ], + + function(result){ + equal( current_url, pre + '#a=2&b=2', '$.fn.fragment( url, Object )' ); + }, + + [ { c:true, d:false, e:'undefined', f:'' } ], + + function(result){ + equal( current_url, pre + '#a=2&b=2&c=true&d=false&e=undefined&f=', '$.fn.fragment( url, Object )' ); + }, + + [ { a:[4,5,6]}],//, b:{x:[7], y:8, z:[9,0,'true','false','undefined','']} }, 2 ], + + function(result){ + var params = old_jquery + ? 'a=4&a=5&a=6&b=[object+Object]' + : 'a[]=4&a[]=5&a[]=6&b[x][]=7&b[y]=8&b[z][]=9&b[z][]=0&b[z][]=true&b[z][]=false&b[z][]=undefined&b[z][]='; + + equal( current_url, pre + fake_encode( params ), '$.fn.fragment( url, Object, 2 )' ); + }, + + [ { a:'1', c:'2' }, 1 ], + + function(result){ + var params = old_jquery + ? 'a=4&a=5&a=6&b=[object+Object]&c=2' + : 'a[]=4&a[]=5&a[]=6&b[x][]=7&b[y]=8&b[z][]=9&b[z][]=0&b[z][]=true&b[z][]=false&b[z][]=undefined&b[z][]=&c=2'; + + equal( current_url, pre + fake_encode( params ), '$.fn.fragment( url, Object, 1 )' ); + }, + + [ 'foo=1' ], + + function(result){ + var params = old_jquery + ? 'a=4&a=5&a=6&b=[object+Object]&c=2&foo=1' + : 'a[]=4&a[]=5&a[]=6&b[x][]=7&b[y]=8&b[z][]=9&b[z][]=0&b[z][]=true&b[z][]=false&b[z][]=undefined&b[z][]=&c=2&foo=1'; + + equal( current_url, pre + fake_encode( params ), '$.fn.fragment( url, String )' ); + }, + + [ 'foo=2&bar=3', 1 ], + + function(result){ + var params = old_jquery + ? 'a=4&a=5&a=6&b=[object+Object]&bar=3&c=2&foo=1' + : 'a[]=4&a[]=5&a[]=6&b[x][]=7&b[y]=8&b[z][]=9&b[z][]=0&b[z][]=true&b[z][]=false&b[z][]=undefined&b[z][]=&bar=3&c=2&foo=1'; + + equal( current_url, pre + fake_encode( params ), '$.fn.fragment( url, String, 1 )' ); + }, + + [ 'http://example.com/test.html?the-cow-goes-moo#/path/to/file.php', 2 ], + + function(result){ + equal( current_url, pre + '#/path/to/file.php', '$.fn.fragment( url, String, 2 )' ); + }, + + [ '#another-example', 2 ], + + function(result){ + equal( current_url, pre + '#another-example', '$.fn.fragment( url, String, 2 )' ); + }, + + [ 'i_am_out_of_witty_strings', 2 ], + + function(result){ + equal( current_url, pre + '#i_am_out_of_witty_strings', '$.fn.fragment( url, String, 2 )' ); + } + + ); + + $.param.fragment.ajaxCrawlable( true ); + + function test_fn_fragment( url, params, merge_mode? ) { + var container, + elems; + + container = init_url_attr( container, url ); + elems = container.children('span'); + equal( elems.length, 1, 'select the correct elements' ); + equal( elems.fragment( 'arbitrary_attr', params, merge_mode ), elems, 'pass fragment' ); + + container = init_url_attr( container, url ); + elems = container.children('a, link'); + equal( elems.length, 2, 'select the correct elements' ); + equal( elems.fragment( params, merge_mode ), elems, 'pass fragment' ); + + container = init_url_attr( container, url ); + elems = container.children(); + equal( elems.fragment( params, merge_mode ), elems, 'pass fragment' ); + + return test_url_attr( container ); + }; + + equal( test_fn_fragment( 'foo', {} ) , 'foo#!', '$.fn.fragment( url, Object )' ); + equal( test_fn_fragment( 'foo', { b:2, a:1 } ) , 'foo#!a=1&b=2', '$.fn.fragment( url, Object )' ); + equal( test_fn_fragment( 'foo#', { b:2, a:1 } ) , 'foo#!a=1&b=2', '$.fn.fragment( url, Object )' ); + equal( test_fn_fragment( 'foo#!', { b:2, a:1 } ) , 'foo#!a=1&b=2', '$.fn.fragment( url, Object )' ); + equal( test_fn_fragment( 'foo#c=3&a=4', { b:2, a:1 } ) , 'foo#!a=1&b=2&c=3', '$.fn.fragment( url, Object )' ); + equal( test_fn_fragment( 'foo#!c=3&a=4', { b:2, a:1 } ) , 'foo#!a=1&b=2&c=3', '$.fn.fragment( url, Object )' ); + + equal( test_fn_fragment( 'foo', '' ) , 'foo#!', '$.fn.fragment( url, String )' ); + equal( test_fn_fragment( 'foo', 'b=2&a=1' ) , 'foo#!a=1&b=2', '$.fn.fragment( url, String )' ); + equal( test_fn_fragment( 'foo#', 'b=2&a=1' ) , 'foo#!a=1&b=2', '$.fn.fragment( url, String )' ); + equal( test_fn_fragment( 'foo#!', 'b=2&a=1' ) , 'foo#!a=1&b=2', '$.fn.fragment( url, String )' ); + equal( test_fn_fragment( 'foo#c=3&a=4', 'b=2&a=1' ) , 'foo#!a=1&b=2&c=3', '$.fn.fragment( url, String )' ); + equal( test_fn_fragment( 'foo#!c=3&a=4', 'b=2&a=1' ) , 'foo#!a=1&b=2&c=3', '$.fn.fragment( url, String )' ); + + equal( test_fn_fragment( 'foo', '#' ) , 'foo#!', '$.fn.fragment( url, String )' ); + equal( test_fn_fragment( 'foo', '#b=2&a=1' ) , 'foo#!a=1&b=2', '$.fn.fragment( url, String )' ); + equal( test_fn_fragment( 'foo#', '#b=2&a=1' ) , 'foo#!a=1&b=2', '$.fn.fragment( url, String )' ); + equal( test_fn_fragment( 'foo#!', '#b=2&a=1' ) , 'foo#!a=1&b=2', '$.fn.fragment( url, String )' ); + equal( test_fn_fragment( 'foo#c=3&a=4', '#b=2&a=1' ) , 'foo#!a=1&b=2&c=3', '$.fn.fragment( url, String )' ); + equal( test_fn_fragment( 'foo#!c=3&a=4', '#b=2&a=1' ) , 'foo#!a=1&b=2&c=3', '$.fn.fragment( url, String )' ); + + equal( test_fn_fragment( 'foo', '#!' ) , 'foo#!', '$.fn.fragment( url, String )' ); + equal( test_fn_fragment( 'foo', '#!b=2&a=1' ) , 'foo#!a=1&b=2', '$.fn.fragment( url, String )' ); + equal( test_fn_fragment( 'foo#', '#!b=2&a=1' ) , 'foo#!a=1&b=2', '$.fn.fragment( url, String )' ); + equal( test_fn_fragment( 'foo#!', '#!b=2&a=1' ) , 'foo#!a=1&b=2', '$.fn.fragment( url, String )' ); + equal( test_fn_fragment( 'foo#c=3&a=4', '#!b=2&a=1' ) , 'foo#!a=1&b=2&c=3', '$.fn.fragment( url, String )' ); + equal( test_fn_fragment( 'foo#!c=3&a=4', '#!b=2&a=1' ) , 'foo#!a=1&b=2&c=3', '$.fn.fragment( url, String )' ); + + $.param.fragment.ajaxCrawlable( false ); + + // If a params fragment starts with ! and BBQ is not in ajaxCrawlable mode, + // things can get very ugly, very quickly. + equal( test_fn_fragment( 'foo', '#!' ) , 'foo#!=', '$.fn.fragment( url, String )' ); + equal( test_fn_fragment( 'foo', '#!b=2&a=1' ) , 'foo#!b=2&a=1', '$.fn.fragment( url, String )' ); + equal( test_fn_fragment( 'foo#', '#!b=2&a=1' ) , 'foo#!b=2&a=1', '$.fn.fragment( url, String )' ); + equal( test_fn_fragment( 'foo#!', '#!b=2&a=1' ) , 'foo#!=&!b=2&a=1', '$.fn.fragment( url, String )' ); + equal( test_fn_fragment( 'foo#c=3&a=4', '#!b=2&a=1' ) , 'foo#!b=2&a=1&c=3', '$.fn.fragment( url, String )' ); + equal( test_fn_fragment( 'foo#!c=3&a=4', '#!b=2&a=1' ) , 'foo#!b=2&!c=3&a=1', '$.fn.fragment( url, String )' ); + +}); + +//////////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// + +QUnit.module( 'jQuery.bbq' ); + +test( 'jQuery.bbq.pushState(), jQuery.bbq.getState(), jQuery.bbq.removeState(), window.onhashchange', function() { + expect( old_jquery ? 95 : 167 ); + + var a, b, c, d, e, f, x, y, hash, hash_actual, obj, event, msg = 'Testing window.onhashchange and history'; + + $.bbq.pushState(); + equal( window.location.hash.replace( /^#/, ''), '', 'window.location hash should be empty' ); + + $.bbq.pushState({ a:'1', b:'1' }); + deepEqual( $.deparam.fragment(), { a:'1', b:'1' }, 'hash should be set properly' ); + + $(window).bind( 'hashchange', function(evt) { + var hash_str = $.param.fragment(), + param_obj = $.bbq.getState(), + param_val = $.bbq.getState( 'param_name' ); + + event = evt; + hash = $.param.fragment(); + hash_actual = location.hash; + obj = { str: $.bbq.getState(), coerce: $.bbq.getState( true ) }; + a = { str: $.bbq.getState( 'a' ), coerce: $.bbq.getState( 'a', true ) }; + b = { str: $.bbq.getState( 'b' ), coerce: $.bbq.getState( 'b', true ) }; + c = { str: $.bbq.getState( 'c' ), coerce: $.bbq.getState( 'c', true ) }; + d = { str: $.bbq.getState( 'd' ), coerce: $.bbq.getState( 'd', true ) }; + e = { str: $.bbq.getState( 'e' ), coerce: $.bbq.getState( 'e', true ) }; + f = { str: $.bbq.getState( 'f' ), coerce: $.bbq.getState( 'f', true ) }; + + }).trigger( 'hashchange' ); + + deepEqual( obj.str, { a:'1', b:'1' }, 'hashchange triggered manually: $.bbq.getState()' ); + deepEqual( obj.coerce, { a:1, b:1 }, 'hashchange triggered manually: $.bbq.getState( true )' ); + equal( a.str, '1', 'hashchange triggered manually: $.bbq.getState( "a" )' ); + equal( a.coerce, 1, 'hashchange triggered manually: $.bbq.getState( "a", true )' ); + + if ( !old_jquery ) { + deepEqual( event.getState(), { a:'1', b:'1' }, 'hashchange triggered manually: event.getState()' ); + deepEqual( event.getState(true), { a:1, b:1 }, 'hashchange triggered manually: event.getState( true )' ); + equal( event.getState('a'), '1', 'hashchange triggered manually: event.getState( "a" )' ); + equal( event.getState('a',true), 1, 'hashchange triggered manually: event.getState( "a", true )' ); + } + + run_many_tests( + // run asynchronously + 250, + + // execute this for each array item + function(){ + notice( msg += '.' ); + $.bbq.pushState.apply( this, aps.call( arguments ) ); + }, + + // execute this at the end + function(){ + notice(); + }, + + // tests: + + [ { a:'2' } ], + + function(result){ + equal( hash_actual, '#' + hash, 'hash should begin with #!' ); + deepEqual( obj.str, { a:'2', b:'1' }, '$.bbq.getState()' ); + deepEqual( obj.coerce, { a:2, b:1 }, '$.bbq.getState( true )' ); + equal( a.str, '2', '$.bbq.getState( "a" )' ); + equal( a.coerce, 2, '$.bbq.getState( "a", true )' ); + if ( !old_jquery ) { + deepEqual( event.getState(), { a:'2', b:'1' }, 'event.getState()' ); + deepEqual( event.getState(true), { a:2, b:1 }, 'event.getState( true )' ); + equal( event.getState('a'), '2', 'event.getState( "a" )' ); + equal( event.getState('a',true), 2, 'event.getState( "a", true )' ); + } + }, + + [ { b:'2' } ], + + function(result){ + equal( hash_actual, '#' + hash, 'hash should begin with #!' ); + deepEqual( obj.str, { a:'2', b:'2' }, '$.bbq.getState()' ); + deepEqual( obj.coerce, { a:2, b:2 }, '$.bbq.getState( true )' ); + equal( b.str, '2', '$.bbq.getState( "b" )' ); + equal( b.coerce, 2, '$.bbq.getState( "b", true )' ); + if ( !old_jquery ) { + deepEqual( event.getState(), { a:'2', b:'2' }, 'event.getState()' ); + deepEqual( event.getState(true), { a:2, b:2 }, 'event.getState( true )' ); + equal( event.getState('b'), '2', 'event.getState( "b" )' ); + equal( event.getState('b',true), 2, 'event.getState( "b", true )' ); + } + }, + + [ { c:true, d:false, e:'undefined', f:'' } ], + + function(result){ + equal( hash_actual, '#' + hash, 'hash should begin with #!' ); + deepEqual( obj.str, { a:'2', b:'2', c:'true', d:'false', e:'undefined', f:'' }, '$.bbq.getState()' ); + deepEqual( obj.coerce, { a:2, b:2, c:true, d:false, e:undefined, f:'' }, '$.bbq.getState( true )' ); + equal( c.str, 'true', '$.bbq.getState( "c" )' ); + equal( c.coerce, true, '$.bbq.getState( "c", true )' ); + equal( d.str, 'false', '$.bbq.getState( "d" )' ); + equal( d.coerce, false, '$.bbq.getState( "d", true )' ); + equal( e.str, 'undefined', '$.bbq.getState( "e" )' ); + equal( e.coerce, undefined, '$.bbq.getState( "e", true )' ); + equal( f.str, '', '$.bbq.getState( "f" )' ); + equal( f.coerce, '', '$.bbq.getState( "f", true )' ); + if ( !old_jquery ) { + deepEqual( event.getState(), { a:'2', b:'2', c:'true', d:'false', e:'undefined', f:'' }, 'event.getState()' ); + deepEqual( event.getState(true), { a:2, b:2, c:true, d:false, e:undefined, f:'' }, 'event.getState( true )' ); + equal( event.getState('c'), 'true', 'event.getState( "c" )' ); + equal( event.getState('c',true), true, 'event.getState( "c", true )' ); + equal( event.getState('d'), 'false', 'event.getState( "d" )' ); + equal( event.getState('d',true), false, 'event.getState( "d", true )' ); + equal( event.getState('e'), 'undefined', 'event.getState( "e" )' ); + equal( event.getState('e',true), undefined, 'event.getState( "e", true )' ); + equal( event.getState('f'), '', 'event.getState( "f" )' ); + equal( event.getState('f',true), '', 'event.getState( "f", true )' ); + } + }, + + function(result){ + $.param.fragment.ajaxCrawlable( true ); + }, + + function(result){ + $.bbq.removeState( 'c' ); + }, + + function(result){ + equal( hash_actual, '#!' + hash, 'hash should begin with #!' ); + deepEqual( obj.str, { a:'2', b:'2', d:'false', e:'undefined', f:'' }, '$.bbq.getState()' ); + deepEqual( obj.coerce, { a:2, b:2, d:false, e:undefined, f:'' }, '$.bbq.getState( true )' ); + equal( a.str, '2', '$.bbq.getState( "a" )' ); + equal( a.coerce, 2, '$.bbq.getState( "a", true )' ); + equal( b.str, '2', '$.bbq.getState( "b" )' ); + equal( b.coerce, 2, '$.bbq.getState( "b", true )' ); + equal( c.str, undefined, '$.bbq.getState( "c" )' ); + equal( c.coerce, undefined, '$.bbq.getState( "c", true )' ); + equal( d.str, 'false', '$.bbq.getState( "d" )' ); + equal( d.coerce, false, '$.bbq.getState( "d", true )' ); + equal( e.str, 'undefined', '$.bbq.getState( "e" )' ); + equal( e.coerce, undefined, '$.bbq.getState( "e", true )' ); + equal( f.str, '', '$.bbq.getState( "f" )' ); + equal( f.coerce, '', '$.bbq.getState( "f", true )' ); + if ( !old_jquery ) { + deepEqual( event.getState(), { a:'2', b:'2', d:'false', e:'undefined', f:'' }, 'event.getState()' ); + deepEqual( event.getState(true), { a:2, b:2, d:false, e:undefined, f:'' }, 'event.getState( true )' ); + equal( event.getState('a'), '2', 'event.getState( "a" )' ); + equal( event.getState('a',true), 2, 'event.getState( "a", true )' ); + equal( event.getState('b'), '2', 'event.getState( "b" )' ); + equal( event.getState('b',true), 2, 'event.getState( "b", true )' ); + equal( event.getState('c'), undefined, 'event.getState( "c" )' ); + equal( event.getState('c',true), undefined, 'event.getState( "c", true )' ); + equal( event.getState('d'), 'false', 'event.getState( "d" )' ); + equal( event.getState('d',true), false, 'event.getState( "d", true )' ); + equal( event.getState('e'), 'undefined', 'event.getState( "e" )' ); + equal( event.getState('e',true), undefined, 'event.getState( "e", true )' ); + equal( event.getState('f'), '', 'event.getState( "f" )' ); + equal( event.getState('f',true), '', 'event.getState( "f", true )' ); + } + }, + + function(result){ + $.bbq.removeState( [ 'd', 'e', 'f', 'nonexistent' ] ); + }, + + function(result){ + equal( hash_actual, '#!' + hash, 'hash should begin with #!' ); + deepEqual( obj.str, { a:'2', b:'2' }, '$.bbq.getState()' ); + deepEqual( obj.coerce, { a:2, b:2 }, '$.bbq.getState( true )' ); + equal( a.str, '2', '$.bbq.getState( "a" )' ); + equal( a.coerce, 2, '$.bbq.getState( "a", true )' ); + equal( b.str, '2', '$.bbq.getState( "b" )' ); + equal( b.coerce, 2, '$.bbq.getState( "b", true )' ); + equal( c.str, undefined, '$.bbq.getState( "c" )' ); + equal( c.coerce, undefined, '$.bbq.getState( "c", true )' ); + equal( d.str, undefined, '$.bbq.getState( "d" )' ); + equal( d.coerce, undefined, '$.bbq.getState( "d", true )' ); + equal( e.str, undefined, '$.bbq.getState( "e" )' ); + equal( e.coerce, undefined, '$.bbq.getState( "e", true )' ); + equal( f.str, undefined, '$.bbq.getState( "f" )' ); + equal( f.coerce, undefined, '$.bbq.getState( "f", true )' ); + if ( !old_jquery ) { + deepEqual( event.getState(), { a:'2', b:'2' }, 'event.getState()' ); + deepEqual( event.getState(true), { a:2, b:2 }, 'event.getState( true )' ); + equal( event.getState('a'), '2', 'event.getState( "a" )' ); + equal( event.getState('a',true), 2, 'event.getState( "a", true )' ); + equal( event.getState('b'), '2', 'event.getState( "b" )' ); + equal( event.getState('b',true), 2, 'event.getState( "b", true )' ); + equal( event.getState('c'), undefined, 'event.getState( "c" )' ); + equal( event.getState('c',true), undefined, 'event.getState( "c", true )' ); + equal( event.getState('d'), undefined, 'event.getState( "d" )' ); + equal( event.getState('d',true), undefined, 'event.getState( "d", true )' ); + equal( event.getState('e'), undefined, 'event.getState( "e" )' ); + equal( event.getState('e',true), undefined, 'event.getState( "e", true )' ); + equal( event.getState('f'), undefined, 'event.getState( "f" )' ); + equal( event.getState('f',true), undefined, 'event.getState( "f", true )' ); + } + }, + + function(result){ + $.bbq.removeState(); + }, + + function(result){ + equal( hash_actual, '#!', 'hash should just be #!' ); + deepEqual( obj.str, {}, '$.bbq.getState()' ); + deepEqual( obj.coerce, {}, '$.bbq.getState( true )' ); + equal( a.str, undefined, '$.bbq.getState( "a" )' ); + equal( a.coerce, undefined, '$.bbq.getState( "a", true )' ); + equal( b.str, undefined, '$.bbq.getState( "b" )' ); + equal( b.coerce, undefined, '$.bbq.getState( "b", true )' ); + equal( c.str, undefined, '$.bbq.getState( "c" )' ); + equal( c.coerce, undefined, '$.bbq.getState( "c", true )' ); + equal( d.str, undefined, '$.bbq.getState( "d" )' ); + equal( d.coerce, undefined, '$.bbq.getState( "d", true )' ); + equal( e.str, undefined, '$.bbq.getState( "e" )' ); + equal( e.coerce, undefined, '$.bbq.getState( "e", true )' ); + equal( f.str, undefined, '$.bbq.getState( "f" )' ); + equal( f.coerce, undefined, '$.bbq.getState( "f", true )' ); + if ( !old_jquery ) { + deepEqual( event.getState(), {}, 'event.getState()' ); + deepEqual( event.getState(true), {}, 'event.getState( true )' ); + equal( event.getState('a'), undefined, 'event.getState( "a" )' ); + equal( event.getState('a',true), undefined, 'event.getState( "a", true )' ); + equal( event.getState('b'), undefined, 'event.getState( "b" )' ); + equal( event.getState('b',true), undefined, 'event.getState( "b", true )' ); + equal( event.getState('c'), undefined, 'event.getState( "c" )' ); + equal( event.getState('c',true), undefined, 'event.getState( "c", true )' ); + equal( event.getState('d'), undefined, 'event.getState( "d" )' ); + equal( event.getState('d',true), undefined, 'event.getState( "d", true )' ); + equal( event.getState('e'), undefined, 'event.getState( "e" )' ); + equal( event.getState('e',true), undefined, 'event.getState( "e", true )' ); + equal( event.getState('f'), undefined, 'event.getState( "f" )' ); + equal( event.getState('f',true), undefined, 'event.getState( "f", true )' ); + } + }, + + [ { a:'2', b:'2', c:true, d:false, e:'undefined', f:'' } ], + + [ { a:[4,5,6]}],//, b:{x:[7], y:8, z:[9,0,'true','false','undefined','']} }, 2 ], + + function(result){ + var b_str = old_jquery + ? '[object Object]' + : {x:['7'], y:'8', z:['9','0','true','false','undefined','']}, + b_coerce = old_jquery + ? '[object Object]' + : {x:[7], y:8};//z:[9,0,true,false,undefined,'']}; + + equal( hash_actual, '#!' + hash, 'hash should begin with #!' ); + deepEqual( obj.str, { a:['4','5','6'], b:b_str }, '$.bbq.getState()' ); + deepEqual( obj.coerce, { a:[4,5,6], b:b_coerce }, '$.bbq.getState( true )' ); + deepEqual( a.str, ['4','5','6'], '$.bbq.getState( "a" )' ); + deepEqual( a.coerce, [4,5,6], '$.bbq.getState( "a", true )' ); + if ( !old_jquery ) { + deepEqual( event.getState(), { a:['4','5','6'], b:b_str }, 'event.getState()' ); + deepEqual( event.getState(true), { a:[4,5,6], b:b_coerce }, 'event.getState( true )' ); + deepEqual( event.getState('a'), ['4','5','6'], 'event.getState( "a" )' ); + deepEqual( event.getState('a',true), [4,5,6], 'event.getState( "a", true )' ); + } + }, + + [ { a:'1', c:'2' }, 1 ], + + function(result){ + var b_str = old_jquery + ? '[object Object]' + : {x:['7'], y:'8', z:['9','0','true','false','undefined','']}, + b_coerce = old_jquery + ? '[object Object]' + : {x:[7], y:8};//, z:[9,0,true,false,undefined,'']}; + + equal( hash_actual, '#!' + hash, 'hash should begin with #!' ); + deepEqual( obj.str, { a:['4','5','6'], b:b_str, c:'2' }, '$.bbq.getState()' ); + deepEqual( obj.coerce, { a:[4,5,6], b:b_coerce, c:2 }, '$.bbq.getState( true )' ); + if ( !old_jquery ) { + deepEqual( event.getState(), { a:['4','5','6'], b:b_str, c:'2' }, 'event.getState()' ); + deepEqual( event.getState(true), { a:[4,5,6], b:b_coerce, c:2 }, 'event.getState( true )' ); + } + }, + + [ '#/path/to/file.php', 2 ], + + function(result){ + equal( hash_actual, '#!' + hash, 'hash should begin with #!' ); + equal( hash, '/path/to/file.php', '$.param.fragment()' ); + if ( !old_jquery ) { + equal( event.fragment, '/path/to/file.php', 'event.fragment' ); + } + }, + + [], + + function(result){ + equal( hash_actual, '#!', 'hash should just be #!' ); + equal( hash, '', '$.param.fragment()' ); + if ( !old_jquery ) { + equal( event.fragment, '', 'event.fragment' ); + } + }, + + function(result){ + $(window).bind( 'hashchange', function(evt){ + x = $.param.fragment(); + }); + }, + + [ '#omg_ponies', 2 ], + + function(result){ + equal( hash, 'omg_ponies', 'event handler 1: $.param.fragment()' ); + equal( x, 'omg_ponies', 'event handler 2: $.param.fragment()' ); + + hash = x = ''; + equal( hash + x, '', 'vars reset' ); + + $(window).triggerHandler( 'hashchange' ); + equal( hash, 'omg_ponies', 'event handler 1: $.param.fragment()' ); + equal( x, 'omg_ponies', 'event handler 2: $.param.fragment()' ); + + hash = x = ''; + equal( hash + x, '', 'vars reset' ); + + $(window).unbind( 'hashchange' ); + }, + + [ '#almost_done?not_search', 2 ], + + function(result){ + equal( hash, '', 'event handler 1: $.param.fragment()' ); + equal( x, '', 'event handler 2: $.param.fragment()' ); + + var events:any;// = $.data( window, 'events' ); + ok( !events || !events.hashchange, 'hashchange event unbound' ); + }, + + [ '#' ], + + function(result){ + x = []; + $(window).bind( 'hashchange', function(evt){ + x.push( $.param.fragment() ); + }); + }, + + function(result){ + !is_chrome && window.history.go( -1 ); + }, + + function(result){ + !is_chrome && window.history.go( -1 ); + }, + + function(result){ + !is_chrome && window.history.go( -1 ); + }, + + function(result){ + !is_chrome && window.history.go( -1 ); + }, + + function(result){ + if ( is_chrome ) { + // Read about this issue here: http://benalman.com/news/2009/09/chrome-browser-history-buggine/ + ok( true, 'history is sporadically broken in chrome, this is a known bug, so this test is skipped in chrome' ); + } else { + deepEqual( x, ['almost_done?not_search', 'omg_ponies', '', '/path/to/file.php'], 'back button and window.bbq.go(-1) should work' ); + } + + $(window).unbind( 'hashchange' ); + var events: any;// = $.data( window, 'events' ); + ok( !events || !events.hashchange, 'hashchange event unbound' ); + }, + + function(result){ + $.param.fragment.ajaxCrawlable( false ); + }, + + [ '#all_done' ] + + ); + +}); + + +}); // END CLOSURE \ No newline at end of file diff --git a/jquery.bbq/jquery.bbq.d.ts b/jquery.bbq/jquery.bbq.d.ts index b34ea0eb36..5e94efea99 100644 --- a/jquery.bbq/jquery.bbq.d.ts +++ b/jquery.bbq/jquery.bbq.d.ts @@ -1,42 +1,160 @@ // Type definitions for jquery.bbq 1.2 // Project: http://benalman.com/projects/jquery-bbq-plugin/ -// Definitions by: https://github.com/sunetos +// Definitions by: Adam R. Smith // Definitions: https://github.com/borisyankov/DefinitelyTyped -interface JQueryBBQ { - pushState(params?: any, merge_mode?: number): void; - getState(key?: string, coerce?: bool): any; - removeState(...key: any[]): void; +/// + +module JQueryBbq { + + interface JQuery { + /** + * Adds a 'state' into the browser history at the current position, setting + * location.hash and triggering any bound callbacks + * (provided the new state is different than the previous state). + * + * @name params A serialized params string or a hash string beginning with # to merge into location.hash. + * @name merge_mode Merge behavior defaults to 0 if merge_mode is not specified (unless a hash string beginning with # is specified, in which case merge behavior defaults to 2) + */ + pushState(params?: string, merge_mode?: number): void; + + pushState(params?: any, merge_mode?: number): void; + + /** + * Retrieves the current 'state' from the browser history, parsing + * location.hash for a specific key or returning an object containing the + * entire state, optionally coercing numbers, booleans, null and undefined + * values. + * + * @name key An optional state key for which to return a value. + * @name coerce If true, coerces any numbers or true, false, null, and undefined to their actual value. Defaults to false + */ + getState(key?: string, coerce?: bool): any; + + getState(coerce?: bool): any; + + /** + * Remove one or more keys from the current browser history 'state', creating + * a new state, setting location.hash and triggering any bound + * callbacks (provided the new state is different than + * the previous state). + * + * @name key One or more key values to remove from the current state. + */ + removeState(...key: any[]): void; + } + + interface ParamFragment { + (url?: string): string; + + (url: string, params: any, merge_mode?: number): string; + + /** + * Specify characters that will be left unescaped when fragments are created + * or merged using , or when the fragment is modified + * using . This option only applies to serialized data + * object fragments, and not set-as-string fragments. Does not affect the + * query string. Defaults to ",/" (comma, forward slash). + * + * @name chars The characters to not escape in the fragment. If unspecified, defaults to empty string (escape all characters). + */ + noEscape: (chars?: string) => void; + + /** + * TODO: DESCRIBE + * + * @name state TODO: DESCRIBE + */ + ajaxCrawlable(state?: bool): bool; + } + + interface JQueryDeparam { + /** + * Deserialize a params string into an object, optionally coercing numbers, + * booleans, null and undefined values; this method is the counterpart to the + * internal jQuery.param method. + * + * @name params A params string to be parsed. + * @name coerce If true, coerces any numbers or true, false, null, and undefined to their actual value. Defaults to false if omitted. + */ + (params: string, coerce?: bool): any; + + + /** + * Parse the query string from a URL or the current window.location.href, + * deserializing it into an object, optionally coercing numbers, booleans, + * null and undefined values. + * + * @name url An optional params string or URL containing query string params to be parsed. If url is omitted, the current window.location.href is used. + * @name coerce If true, coerces any numbers or true, false, null, and undefined to their actual value. Defaults to false if omitted. + */ + querystring(url?: string, coerce?: bool): any; + + /** + * Parse the fragment (hash) from a URL or the current window.location.href, + * deserializing it into an object, optionally coercing numbers, booleans, + * null and undefined values. + * + * @name url An optional params string or URL containing fragment (hash) params to be parsed. If url is omitted, the current window.location.href is used. + * @name coerce If true, coerces any numbers or true, false, null, and undefined to their actual value. Defaults to false if omitted. + */ + fragment(url?: string, coerce?: bool): any; + } + + interface EventObject extends JQueryEventObject { + fragment: string; + + getState( key?: string, coerce? :bool ); + } } interface JQueryParam { - (obj: any): string; - (obj: any, traditional: bool): string; + /** + * Parse the query string from a URL or the current window.location.href, + * deserializing it into an object, optionally coercing numbers, booleans, + * null and undefined values. + * + * @name url An optional params string or URL containing query string params to be parsed. If url is omitted, the current window.location.href is used. + * @name coerce (Boolean) If true, coerces any numbers or true, false, null, and undefined to their actual value. Defaults to false if omitted. + * @name merge_mode An object representing the deserialized params string. + */ + querystring(url?: string, coerce?: bool, merge_mode?: number): string; - querystring(url?: string): string; - querystring(url: string, params: any, merge_mode?: number): string; - fragment: { - noEscape: (chars?: string) => void; - (url?: string): string; - (url: string, params: any, merge_mode?: number): string; - }; -} + querystring(url?: string, coerce?: any, merge_mode?: number): string; -interface JQueryDeparam { - (params: string, coerce?: bool): any; - querystring(url?: string, coerce?: bool): any; - fragment(url?: string, coerce?: bool): any; + fragment: JQueryBbq.ParamFragment; + + /** + * Returns a params string equivalent to that returned by the internal + * jQuery.param method, but sorted, which makes it suitable for use as a + * cache key. + * + * @name obj An object to be serialized. + * @name traditional Params deep/shallow serialization mode. See the documentation at http://api.jquery.com/jQuery.param/ for more detail. + */ + sorted(obj: any, traditional?: bool): string; } interface JQueryStatic { - bbq: JQueryBBQ; - param: JQueryParam; - deparam: JQueryDeparam; + bbq: JQueryBbq.JQuery; - elemUrlAttr(tag_attr: any): any; + deparam: JQueryBbq.JQueryDeparam; + + /** + * Get the internal "Default URL attribute per tag" list, or augment the list + * with additional tag-attribute pairs, in case the defaults are insufficient. + * + * @name tag_attr An object containing a list of tag names and their associated default attribute names in the format { tag: 'attr', ... } to be merged into the internal tag-attribute list. + */ + elemUrlAttr(tag_attr?: any): any; } interface JQuery { - querystring(attr?: any, params?: any, merge_mode?: number): JQuery; - fragment(attr?: any, params?: any, merge_mode?: number): JQuery; + querystring(attr?: any, params?: any, merge_mode?: number): JQuery; + + fragment(attr?: any, params?: any, merge_mode?: number): JQuery; + + hashchange(eventData?: any, handler?: (eventObject: JQueryBbq.EventObject) => any): JQuery; + + hashchange(handler: (eventObject: JQueryBbq.EventObject) => any): JQuery; } diff --git a/jquery.clientSideLogging/jquery.clientSideLogging-tests.ts b/jquery.clientSideLogging/jquery.clientSideLogging-tests.ts new file mode 100644 index 0000000000..35974af26a --- /dev/null +++ b/jquery.clientSideLogging/jquery.clientSideLogging-tests.ts @@ -0,0 +1,17 @@ +/// + +$.clientSideLogging({ + log_level: 3, + client_info: { + location:true, + screen_size:true, + user_agent:true, + window_size:false + } +}); + +$.info({msg:$(this).parents('li').find('input:text').val()}); +$.error({msg:$(this).parents('li').find('input:text').val()}); +$.log($(this).parents('li').find('input:text').val()); + +$.post('/log?type=error&msg=YOUR_ERROR_MESSAGE'); \ No newline at end of file diff --git a/jquery.clientSideLogging/jquery.clientSideLogging.d.ts b/jquery.clientSideLogging/jquery.clientSideLogging.d.ts new file mode 100644 index 0000000000..d2031029e4 --- /dev/null +++ b/jquery.clientSideLogging/jquery.clientSideLogging.d.ts @@ -0,0 +1,31 @@ +// Type definitions for jquery.clientSideLogging. +// Project: https://github.com/remybach/jQuery.clientSideLogging +// Definitions by: Diullei Gomes +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface ClientSideLoggingClientInfoObject { + location?: bool; // The url to the page on which the error occurred. + screen_size?: bool; // The size of the user's screen (different to the window size because the window might not be maximized) + user_agent?: bool; // The user agent string. + window_size?: bool; // The window size. +} + +interface ClientSideLoggingObject { + error_url?: string; // The url to which errors logs are sent + info_url?: string; // The url to which info logs are sent + log_url?: string; // The url to which standard logs are sent + log_level?: number; // The level at which to log. This allows you to keep the calls to the logging in your code and just change this variable to log varying degrees. 1 = only error, 2 = error & log, 3 = error, log & info + native_error?: bool; // Whether or not to send native js errors as well (using window.onerror). + hijack_console?: bool; // Hijacks the default console functionality (ie: all your console.error/info/log are belong to us). + query_var?: string; // The variable to send the log message through as. + client_info?: ClientSideLoggingClientInfoObject; // Configuration for what info about the client's browser is logged. +} + +interface JQueryStatic { + info: (what?: any) => any; + error: (what?: any) => any; + log: (what?: any) => any; + clientSideLogging: (options: ClientSideLoggingObject) => any; +} diff --git a/jquery.cycle/jquery.cycle-tests.ts b/jquery.cycle/jquery.cycle-tests.ts new file mode 100644 index 0000000000..2b5bd668e5 --- /dev/null +++ b/jquery.cycle/jquery.cycle-tests.ts @@ -0,0 +1,324 @@ +/// +/// + +// As basic as it can be +$('#element').cycle(); + +/* Beginner Demos */ + +$('#s1').cycle('fade'); + +$('#s2').cycle({ + fx: 'scrollDown' +}); + +$('#s3').cycle({ + fx: 'fade', + speed: 2500 +}); + +$('#s4').cycle({ + fx: 'scrollDown', + speed: 300, + timeout: 2000 +}); + +$('#s5').cycle({ + fx: 'fade', + pause: true +}); + +$('#s6').cycle({ + fx: 'scrollDown', + random: true +}); + +/* Intermediate Demos (Part 1) */ +$('#s1').cycle({ + fx: 'zoom', + easing: 'easeInBounce', + delay: -4000 +}); + +$('#s2').cycle({ + fx: 'scrollDown', + easing: 'easeOutBounce', + delay: -2000 +}); + +$('#s3').cycle({ + fx: 'zoom', + sync: false, + delay: -4000 +}); + +$('#s4').cycle({ + fx: 'scrollDown', + sync: false, + delay: -2000 +}); + +$('#s5').cycle({ + fx: 'shuffle', + delay: -4000 +}); + +$('#s6').cycle({ + fx: 'shuffle', + shuffle: { + top: -230, + left: 230 + }, + easing: 'easeInOutBack', + delay: -2000 +}); + +/* Intermediate Demos (Part 2) */ + +$('#s1').cycle({ + fx: 'slideY', + speed: 300, + next: '#s1', + timeout: 0 +}); + +$('#s2').cycle({ + fx: 'fade', + speed: 'fast', + timeout: 0, + next: '#next2', + prev: '#prev2' +}); + +$('#s3').cycle({ + fx: 'fade', + speed: 300, + timeout: 3000, + next: '#s3', + pause: true +}); + +$('#s4') +.before('